repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
abhayanigam/Learn_Python_Programming
|
matplotlib/doughNut_chart.py
|
<reponame>abhayanigam/Learn_Python_Programming<filename>matplotlib/doughNut_chart.py<gh_stars>1-10
import numpy as np
from matplotlib import pyplot as plt
fruit = ['apple','orange','mango','guava']
quatity = [67,34,100,29]
plt.pie(quatity,labels = fruit,radius = 1) #radius of outer circle.
plt.pie([1],colors = ['w'],radius = 0.5) #radius of inner circle and colour of inner circle, 1 for one value with wwhite color.
plt.show()
|
Vadimatorik/googleQt
|
src/gmail/messages/MessagesRoutes.cpp
|
/**********************************************************
DO NOT EDIT
This file was generated from stone specification "messages"
Part of "Ardi - the organizer" project.
<EMAIL>
www.prokarpaty.net
***********************************************************/
#include "gmail/messages/MessagesRoutes.h"
#include "Endpoint.h"
#include "gmail/GmailRoutes.h"
using namespace googleQt;
using namespace messages;
void MessagesRoutes::batchModify(const gmail::BatchModifyMessageArg& arg ){
batchModify_Async(arg)->waitForResultAndRelease();
}
GoogleVoidTask* MessagesRoutes::batchModify_Async(const gmail::BatchModifyMessageArg& arg)
{
GoogleVoidTask* t = m_end_point->produceVoidTask();
m_end_point->postStyleB2Empty
(m_end_point->buildGmailUrl("messages", arg),
arg,
t);
return t;
}
void MessagesRoutes::batchModify_AsyncCB(
const gmail::BatchModifyMessageArg& arg,
std::function<void()> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->postStyleB2Empty
(m_end_point->buildGmailUrl("messages", arg),
arg,
completed_callback,
failed_callback);
}
void MessagesRoutes::deleteOperation(const gmail::IdArg& arg ){
deleteOperation_Async(arg)->waitForResultAndRelease();
}
GoogleVoidTask* MessagesRoutes::deleteOperation_Async(const gmail::IdArg& arg)
{
GoogleVoidTask* t = m_end_point->produceVoidTask();
m_end_point->deleteStyle
(m_end_point->buildGmailUrl("messages", arg),
t);
return t;
}
void MessagesRoutes::deleteOperation_AsyncCB(
const gmail::IdArg& arg,
std::function<void()> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->deleteStyle
(m_end_point->buildGmailUrl("messages", arg),
completed_callback,
failed_callback);
}
std::unique_ptr<MessageResource> MessagesRoutes::get(const gmail::IdArg& arg){
return get_Async(arg)->waitForResultAndRelease();
}
GoogleTask<MessageResource>* MessagesRoutes::get_Async(const gmail::IdArg& arg)
{
GoogleTask<MessageResource>* t = m_end_point->produceTask<MessageResource>();
m_end_point->getStyle<
MessageResource,
MessageResource::factory
>
(m_end_point->buildGmailUrl("messages", arg),
t);
return t;
}
void MessagesRoutes::get_AsyncCB(
const gmail::IdArg& arg,
std::function<void(std::unique_ptr<MessageResource>)> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->getStyle
<
MessageResource,
MessageResource::factory
>
(m_end_point->buildGmailUrl("messages", arg),
completed_callback,
failed_callback);
}
std::unique_ptr<MessageListRes> MessagesRoutes::list(const gmail::ListArg& arg){
return list_Async(arg)->waitForResultAndRelease();
}
GoogleTask<MessageListRes>* MessagesRoutes::list_Async(const gmail::ListArg& arg)
{
GoogleTask<MessageListRes>* t = m_end_point->produceTask<MessageListRes>();
m_end_point->getStyle<
MessageListRes,
MessageListRes::factory
>
(m_end_point->buildGmailUrl("messages", arg),
t);
return t;
}
void MessagesRoutes::list_AsyncCB(
const gmail::ListArg& arg,
std::function<void(std::unique_ptr<MessageListRes>)> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->getStyle
<
MessageListRes,
MessageListRes::factory
>
(m_end_point->buildGmailUrl("messages", arg),
completed_callback,
failed_callback);
}
std::unique_ptr<MessageResource> MessagesRoutes::modify(const gmail::ModifyMessageArg& arg){
return modify_Async(arg)->waitForResultAndRelease();
}
GoogleTask<MessageResource>* MessagesRoutes::modify_Async(const gmail::ModifyMessageArg& arg)
{
GoogleTask<MessageResource>* t = m_end_point->produceTask<MessageResource>();
m_end_point->postStyleB<
MessageResource,
MessageResource::factory
,gmail::ModifyMessageArg>
(m_end_point->buildGmailUrl("messages", arg),
arg,
t);
return t;
}
void MessagesRoutes::modify_AsyncCB(
const gmail::ModifyMessageArg& arg,
std::function<void(std::unique_ptr<MessageResource>)> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->postStyleB
<
MessageResource,
MessageResource::factory
, gmail::ModifyMessageArg
>
(m_end_point->buildGmailUrl("messages", arg),
arg,
completed_callback,
failed_callback);
}
std::unique_ptr<MessageResource> MessagesRoutes::send(const gmail::SendMimeMessageArg& arg){
return send_Async(arg)->waitForResultAndRelease();
}
GoogleTask<MessageResource>* MessagesRoutes::send_Async(const gmail::SendMimeMessageArg& arg)
{
GoogleTask<MessageResource>* t = m_end_point->produceTask<MessageResource>();
m_end_point->postStyleB<
MessageResource,
MessageResource::factory
,gmail::SendMimeMessageArg>
(m_end_point->buildGmailUrl("messages", arg),
arg,
t);
return t;
}
void MessagesRoutes::send_AsyncCB(
const gmail::SendMimeMessageArg& arg,
std::function<void(std::unique_ptr<MessageResource>)> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->postStyleB
<
MessageResource,
MessageResource::factory
, gmail::SendMimeMessageArg
>
(m_end_point->buildGmailUrl("messages", arg),
arg,
completed_callback,
failed_callback);
}
void MessagesRoutes::trash(const gmail::TrashMessageArg& arg ){
trash_Async(arg)->waitForResultAndRelease();
}
GoogleVoidTask* MessagesRoutes::trash_Async(const gmail::TrashMessageArg& arg)
{
GoogleVoidTask* t = m_end_point->produceVoidTask();
m_end_point->postStyle
(m_end_point->buildGmailUrl("messages", arg),
t);
return t;
}
void MessagesRoutes::trash_AsyncCB(
const gmail::TrashMessageArg& arg,
std::function<void()> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->postStyle
(m_end_point->buildGmailUrl("messages", arg),
completed_callback,
failed_callback);
}
void MessagesRoutes::untrash(const gmail::UntrashMessageArg& arg ){
untrash_Async(arg)->waitForResultAndRelease();
}
GoogleVoidTask* MessagesRoutes::untrash_Async(const gmail::UntrashMessageArg& arg)
{
GoogleVoidTask* t = m_end_point->produceVoidTask();
m_end_point->postStyle
(m_end_point->buildGmailUrl("messages", arg),
t);
return t;
}
void MessagesRoutes::untrash_AsyncCB(
const gmail::UntrashMessageArg& arg,
std::function<void()> completed_callback ,
std::function<void(std::unique_ptr<GoogleException>)> failed_callback)
{
m_end_point->postStyle
(m_end_point->buildGmailUrl("messages", arg),
completed_callback,
failed_callback);
}
|
HydrologicEngineeringCenter/heclib
|
heclib/heclib_c/src/Internal/zprintFileInfo.c
|
#include <stdio.h>
#include "heclib7.h"
#include "zdssMessages.h"
#include "zdssKeys.h"
#include "zdssVals.h"
#include "hecdssInternal.h"
/**
* Function: zprintFileInfo
*
* Use: Semi-Private
*
* Description: Prints information about a DSS file on closing
*
* Declaration: void zprintFileInfo(long long *ifltab)
*
* Parameters: long long ifltab
* An integer array dimensioned to int*8 [250] that contains file specific information.
* This should be considered as a "handle" array and must be passed to any function that accesses that file.
*
*
* Note: Strings are defined in zdssMessages.h for portability
*
*
*
* Author: <NAME>
* Date: 2012
* Organization: US Army Corps of Engineers, Hydrologic Engineering Center (USACE HEC)
* All Rights Reserved
*
**/
void zprintFileInfo(long long *ifltab)
{
long long kbytes;
long long mbytes;
long long *fileHeader;
char messageString[90];
if (zgetVersion(ifltab) != 7) {
zmessage(ifltab, "Print file info called with incorrect version");
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE,
"This function is for DSS version 7; it is being called with a %d version file.", zgetVersion(ifltab));
zmessage(ifltab, messageString);
return;
}
fileHeader = (long long *)ifltab[zdssKeys.kfileHeader];
kbytes = fileHeader[zdssFileKeys.kfileSize] * 8 / 1024;
mbytes = kbytes / 1024;
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_01, fileHeader[zdssFileKeys.knumberRecords]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_02, fileHeader[zdssFileKeys.kfileSize]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_03, kbytes, mbytes);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_04, fileHeader[zdssFileKeys.kdead]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_05, fileHeader[zdssFileKeys.kmaxHash]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_06, fileHeader[zdssFileKeys.khashsUsed]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_07, fileHeader[zdssFileKeys.kmaxPathsOneHash]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_08, fileHeader[zdssFileKeys.kmaxPathsHashCode]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_09, fileHeader[zdssFileKeys.khashCollisions]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_10, fileHeader[zdssFileKeys.ktotalBins]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_11, fileHeader[zdssFileKeys.kbinsOverflow]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_12, ifltab[zdssKeys.knumberReads]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_13, ifltab[zdssKeys.knumberWrites]);
zmessage(ifltab, messageString);
_snprintf_s(messageString, sizeof(messageString), _TRUNCATE, FILE_INFO_MESS_14, ifltab[zdssKeys.klocksDenied]);
zmessage(ifltab, messageString);
}
void zprintfileinfo_(long long *ifltab)
{
zprintFileInfo(ifltab);
}
|
sportdb/sport.db
|
sportdb-readers/test/test_read.rb
|
<gh_stars>100-1000
# encoding: utf-8
###
# to run use
# ruby -I ./lib -I ./test test/test_read.rb
require 'helper'
class TestRead < MiniTest::Test
def test_read
SportDb.connect( adapter: 'sqlite3', database: ':memory:' )
SportDb.create_all ## build schema
## turn on logging to console
ActiveRecord::Base.logger = Logger.new(STDOUT)
path = "../../../openfootball/england/2015-16/.conf.txt"
# path = "../../../openfootball/england/2017-18/.conf.txt"
# path = "../../../openfootball/england/2018-19/.conf.txt"
# path = "../../../openfootball/england/2019-20/.conf.txt"
SportDb.read( path )
path = "../../../openfootball/england/2015-16/1-premierleague-i.txt"
# path = "../../../openfootball/england/2017-18/1-premierleague-i.txt"
# path = "../../../openfootball/england/2018-19/1-premierleague.txt"
# path = "../../../openfootball/england/2019-20/1-premierleague.txt"
SportDb.read( path )
# path = "../../../openfootball/england/2017-18/1-premierleague-ii.txt"
# SportDb.read( path )
end # method test_read
end # class TestReader
|
lsds/Crossbow
|
clib-multigpu/stream.h
|
#ifndef __CROSSBOW_STREAM_H_
#define __CROSSBOW_STREAM_H_
#include <cuda_runtime.h>
#include "cublas_v2.h"
#include <cudnn.h>
#include <curand.h>
#include "device.h"
#include "databuffer.h"
#include "variable.h"
#include "list.h"
#include "dataflow.h"
#include "operator.h"
#include "model.h"
#include "recorddataset.h"
#include "utils.h"
typedef struct crossbow_stream *crossbowStreamP;
typedef struct crossbow_stream {
int id;
/* Each stream belongs to a particular device */
int deviceId;
crossbowModelSynchronisationMode_t mode;
int branches;
cudaStream_t *stream;
cublasHandle_t *cublasHandle;
cudnnHandle_t *cudnnHandle;
curandGenerator_t curandGenerator;
/* The event that marks the completion of a task */
cudaEvent_t event;
#ifdef INTRA_TASK_MEASUREMENTS
cudaEvent_t start;
#endif
#ifdef MAKESPAN_MEASUREMENTS
cudaEvent_t barrier;
#endif
int splits;
crossbowDataBufferP input;
crossbowVariableP examples;
crossbowVariableP labels;
crossbowRecordDatasetP dataset;
int ops;
/*
* A kernel can produce more than one output buffers,
* which will be appended to a corresponding list.
*/
crossbowListP *outputs;
/*
* A list of local variables used by operators in the
* dataflow that are not read-only and need to return
* to their corresponding queue.
*
* [Update 12/3] There a list per operator.
*/
crossbowListP *locals;
int task;
crossbowPhase_t phi; /* If CHECK, dataflow execution returns accuracy results */
long freeP[2];
crossbowDataflowP dataflow;
crossbowOperatorP op;
crossbowModelP model;
/* Attributes associated with the parameter server synchronisation model */
crossbowModelP theModel;
cublasHandle_t modelSynchronisationHandle;
cudaStream_t modelSynchronisationStream;
} crossbow_stream_t;
crossbowStreamP crossbowStreamCreate (int, crossbowDeviceP, int, int, crossbowVariableSchemaP, crossbowVariableSchemaP, int, crossbowModelSynchronisationMode_t, unsigned long long);
crossbowDataBufferP crossbowStreamOperatorGetInput (crossbowStreamP, crossbowOperatorP);
crossbowDataBufferP crossbowStreamOperatorGetOutput (crossbowStreamP, crossbowOperatorP);
crossbowDataBufferP crossbowStreamGetCurrentInput (crossbowStreamP);
crossbowDataBufferP crossbowStreamGetPeerInput (crossbowStreamP);
crossbowDataBufferP crossbowStreamGetCurrentOutput (crossbowStreamP);
crossbowDataBufferP crossbowStreamGetPeerOutput (crossbowStreamP);
void crossbowStreamComputeInputCheckSum (crossbowStreamP);
void crossbowStreamComputeCheckSum (crossbowStreamP);
void crossbowStreamUpdateModel (crossbowStreamP);
void crossbowStreamClear (crossbowStreamP);
void crossbowStreamFree (crossbowStreamP);
#endif /* __CROSSBOW_STREAM_H_ */
|
PacktPublishing/Practical-OneOps
|
Chapter 09/circuit-oneops-1-master/components/cookbooks/cb_cluster/recipes/cluster-repair.rb
|
<reponame>PacktPublishing/Practical-OneOps<filename>Chapter 09/circuit-oneops-1-master/components/cookbooks/cb_cluster/recipes/cluster-repair.rb
Chef::Log.info("couchbase_cluster repair action")
include_recipe 'couchbase::base'
|
KonstantinLeontev/c-lessons
|
LinkedList/LinkedList.cpp
|
<filename>LinkedList/LinkedList.cpp
#include <cstddef>
struct EnemySpaceShip
{
int x_coord;
int y_coord;
int weaponPower;
EnemySpaceShip* p_nextEnemy;
};
EnemySpaceShip* p_enemies = NULL;
EnemySpaceShip* getEnemy(void)
{
EnemySpaceShip *p_ship = new EnemySpaceShip;
p_ship->x_coord = 0.0;
p_ship->y_coord = 0.0;
p_ship->weaponPower = 20;
p_ship->p_nextEnemy = p_enemies;
p_enemies = p_ship;
return p_ship;
}
void upgradeWeapons(EnemySpaceShip* p_ship)
{
p_ship->weaponPower += 10;
}
int main()
{
EnemySpaceShip* ship = getEnemy();
upgradeWeapons(ship);
}
|
kiran-blockchain/comcast-india-go
|
more-examples/06-variables/02-declarations/exercises/05-undeclarables/solution/main.go
|
// Copyright © 2018 <NAME>
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
func main() {
// var 3speed int
// var !speed int
// var spe?ed int
// var var int
// var func int
// var package int
}
|
swordqiu/mcclient_java
|
src/main/java/com/yunionyun/mcp/mcclient/managers/impl/ActionManager.java
|
<reponame>swordqiu/mcclient_java
package com.yunionyun.mcp.mcclient.managers.impl;
import com.yunionyun.mcp.mcclient.EndpointType;
import com.yunionyun.mcp.mcclient.managers.BaseLogActionManager;
/**
* @author zxc
* @date 2020/01/17
*/
public class ActionManager extends BaseLogActionManager {
public ActionManager() {
this(EndpointType.InternalURL);
}
public ActionManager(EndpointType endpointType) {
super(
"action",
"actions",
endpointType,
new String[]{
"id",
"start_time",
"service",
"ops_time",
"obj_id",
"obj_type",
"obj_name",
"user",
"user_id",
"tenant",
"tenant_id",
"owner_tenant_id",
"action",
"success",
"notes"
},
new String[]{});
}
}
|
brainvisa/aims-free
|
aimsalgo/src/aimsalgo/signalfilter/filteringfunction_nonlinear_rgb_d.h
|
/* Copyright (C) 2000-2013 CEA
*
* This software and supporting documentation were developed by
* bioPICSEL
* CEA/DSV/I²BM/MIRCen/LMN, Batiment 61,
* 18, route du Panorama
* 92265 Fontenay-aux-Roses
* France
*/
#ifndef AIMS_SIGNALFILTER_FILTERINGFUNCTION_NONLINEAR_RGB_D_H
#define AIMS_SIGNALFILTER_FILTERINGFUNCTION_NONLINEAR_RGB_D_H
//--- aims -------------------------------------------------------------------
#include <aims/signalfilter/filteringfunction_nonlinear_rgb.h>
#include <aims/signalfilter/filteringfunction_nonlinear.h> // aims::NonLinFilterFunc
#include <aims/utility/channel.h> // ChannelSelector
#include <aims/connectivity/structuring_element.h> // aims::StructuringElement
//--- cartodata --------------------------------------------------------------
#include <cartodata/volume/volume.h> // carto::VolumeRef
//----------------------------------------------------------------------------
namespace aims {
/// Templated function to process filter on multichannel data
/// (AimsRGB, AimsRGBA, ...)
///
/// This function does not filter image but only apply filter on set of
/// multichannel data, commonly the neighborhood of a voxel.
/// \param f function to use (must derive from \c NonLinFilterFunc)
/// \param volume data to evaluate filter on
/// \return result of the filter on data
template <typename VoxelType>
inline VoxelType multichannelfiltervalues_nonlin(
NonLinFilterFunc<typename VoxelType::ChannelType> & f,
const carto::VolumeRef<VoxelType> &volume
)
{
ChannelSelector< carto::VolumeRef<VoxelType>,
carto::VolumeRef<typename VoxelType::ChannelType>
> selector;
VoxelType r;
int32_t samples = DataTypeInfo<VoxelType>::samples();
// Split data and process filter on each channel
for( int32_t s = 0; s < samples; s++ )
{
carto::VolumeRef<typename VoxelType::ChannelType> c = selector.select( volume, s );
r[s] = f.execute( c );
}
return r;
}
/// Templated function to process filter on multichannel data
/// (AimsRGB, AimsRGBA, ...)
///
/// This function does not filter image but only apply filter on set of
/// multichannel data, commonly the neighborhood of a voxel.
/// \param f function to use (must derive from \c NonLinFilterFunc)
/// \param volume data to evaluate filter on
/// \param se structuring element to evaluate filter on
/// \return result of the filter on data
template <typename VoxelType>
inline VoxelType multichannelfiltervalues_nonlin(
NonLinFilterFunc<typename VoxelType::ChannelType> & f,
const carto::VolumeRef<VoxelType> &volume,
const StructuringElementRef & se
)
{
ChannelSelector< carto::VolumeRef<VoxelType>,
carto::VolumeRef<typename VoxelType::ChannelType>
> selector;
VoxelType r;
int32_t samples = DataTypeInfo<VoxelType>::samples();
// Split data and process filter on each channel
for( int32_t s = 0; s < samples; s++ )
{
carto::VolumeRef<typename VoxelType::ChannelType> c = selector.select( volume, s );
r[s] = f.execute( c, se );
}
return r;
}
} // namespace aims
#endif
|
OCLC-Developer-Network/circill-toolkit
|
service/ncip/src/main/java/org/oclc/circill/toolkit/service/ncip/HoldingsInformation.java
|
/*
* Copyright (c) 2010 eXtensible Catalog Organization.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the MIT/X11 license. The text of the license can be
* found at http://www.opensource.org/licenses/mit-license.php.
*/
package org.oclc.circill.toolkit.service.ncip;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* A choice of one or more occurrences of Structured Holdings Data OR
* a single occurrence of Unstructured Holdings Data.
*/
public class HoldingsInformation {
protected List<StructuredHoldingsData> structuredHoldingsDatas = new ArrayList<>();
protected String unstructuredHoldingsData;
public List<StructuredHoldingsData> getStructuredHoldingsDatas() {
return structuredHoldingsDatas;
}
public StructuredHoldingsData getStructuredHoldingsData() {
return structuredHoldingsDatas != null ? (structuredHoldingsDatas.size() > 0 ? structuredHoldingsDatas.get(structuredHoldingsDatas.size() - 1) : null) : null;
}
public StructuredHoldingsData getStructuredHoldingsData(final int index) {
return structuredHoldingsDatas != null ? (structuredHoldingsDatas.size() > 0 ? structuredHoldingsDatas.get(index) : null) : null;
}
public void setStructuredHoldingsDatas(final List<StructuredHoldingsData> structuredHoldingsDatas) {
this.structuredHoldingsDatas = structuredHoldingsDatas;
}
public void setStructuredHoldingsData(final int index, final StructuredHoldingsData structuredHoldingsDatas) {
this.structuredHoldingsDatas.set(index, structuredHoldingsDatas);
}
/**
* Set the list of {@link StructuredHoldingsData}s to this structuredHoldingsDatas.
*
* @param structuredHoldingsDatas the list of {@link StructuredHoldingsData}s
*/
public void setStructuredHoldingsData(final StructuredHoldingsData structuredHoldingsDatas) {
if (this.structuredHoldingsDatas != null) {
this.structuredHoldingsDatas.clear();
}
if (structuredHoldingsDatas != null) {
if (this.structuredHoldingsDatas == null) {
this.structuredHoldingsDatas = new ArrayList<>();
}
this.structuredHoldingsDatas.add(structuredHoldingsDatas);
} else {
this.structuredHoldingsDatas = null;
}
}
public String getUnstructuredHoldingsData() {
return unstructuredHoldingsData;
}
public void setUnstructuredHoldingsData(final String unstructuredHoldingsData) {
this.unstructuredHoldingsData = unstructuredHoldingsData;
}
/**
* Generic toString() implementation.
*
* @return String
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
final HoldingsInformation rhs = (HoldingsInformation) obj;
return new EqualsBuilder().append(structuredHoldingsDatas, rhs.structuredHoldingsDatas).append(unstructuredHoldingsData, rhs.unstructuredHoldingsData).isEquals();
}
@Override
public int hashCode() {
final int result = new HashCodeBuilder(817955299, 1320306035).append(structuredHoldingsDatas).append(unstructuredHoldingsData).toHashCode();
return result;
}
}
|
IPVP-MC/iBase
|
base/src/main/java/com/doctordark/util/cuboid/NamedCuboid.java
|
package com.doctordark.util.cuboid;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.Map;
/**
* Represents a {@link NamedCuboid} for regions that can be given a name.
*
* @author desht
*/
public class NamedCuboid extends Cuboid {
protected String name;
public NamedCuboid(Cuboid other) {
super(other.getWorld(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2);
}
public NamedCuboid(World world, int x1, int y1, int z1, int x2, int y2, int z2) {
super(world, x1, y1, z1, x2, y2, z2);
}
public NamedCuboid(Location location) {
super(location, location);
}
public NamedCuboid(Location first, Location second) {
super(first, second);
}
public NamedCuboid(Map<String, Object> map) {
super(map);
this.name = (String) map.get("name");
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = super.serialize();
map.put("name", this.name);
return map;
}
/**
* Gets the name of this {@link NamedCuboid}.
*
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Sets the name of this {@link NamedCuboid}.
*
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
@Override
public NamedCuboid clone() {
return (NamedCuboid) super.clone();
}
@Override
public String toString() {
return "NamedCuboid: " + this.worldName + ',' + this.x1 + ',' + this.y1 + ',' + this.z1 + "=>" + this.x2 + ',' + this.y2 + ',' + this.z2 + ':' + this.name;
}
}
|
reftel/jetty.project
|
jetty-websocket/websocket-client/src/main/java/org/eclipse/jetty/websocket/client/WebSocketUpgradeRequest.java
|
<reponame>reftel/jetty.project
//
// ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.client;
import java.net.HttpCookie;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpConversation;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.HttpResponse;
import org.eclipse.jetty.client.HttpResponseException;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Response.CompleteListener;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.http.HttpConnectionOverHTTP;
import org.eclipse.jetty.client.http.HttpConnectionUpgrader;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.UrlEncoded;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.UpgradeException;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.WebSocketConstants;
import org.eclipse.jetty.websocket.api.extensions.ExtensionConfig;
import org.eclipse.jetty.websocket.api.extensions.ExtensionFactory;
import org.eclipse.jetty.websocket.client.io.UpgradeListener;
import org.eclipse.jetty.websocket.client.io.WebSocketClientConnection;
import org.eclipse.jetty.websocket.common.AcceptHash;
import org.eclipse.jetty.websocket.common.SessionFactory;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.common.events.EventDriver;
import org.eclipse.jetty.websocket.common.extensions.ExtensionStack;
public class WebSocketUpgradeRequest extends HttpRequest implements CompleteListener, HttpConnectionUpgrader
{
private static final Logger LOG = Log.getLogger(WebSocketUpgradeRequest.class);
private class ClientUpgradeRequestFacade implements UpgradeRequest
{
private List<ExtensionConfig> extensions;
private List<String> subProtocols;
private Object session;
public ClientUpgradeRequestFacade()
{
this.extensions = new ArrayList<>();
this.subProtocols = new ArrayList<>();
}
public void init(ClientUpgradeRequest request)
{
this.extensions = new ArrayList<>(request.getExtensions());
this.subProtocols = new ArrayList<>(request.getSubProtocols());
request.getHeaders().forEach((name, values) ->
values.forEach((value) -> header(name, value))
);
for (HttpCookie cookie : request.getCookies())
{
cookie(cookie);
}
}
@Override
public List<ExtensionConfig> getExtensions()
{
return extensions;
}
@Override
public List<String> getSubProtocols()
{
return subProtocols;
}
@Override
public void addExtensions(ExtensionConfig... configs)
{
for (ExtensionConfig config : configs)
{
this.extensions.add(config);
}
updateExtensionHeader();
}
@Override
public void addExtensions(String... configs)
{
this.extensions.addAll(ExtensionConfig.parseList(configs));
updateExtensionHeader();
}
@Override
public void clearHeaders()
{
throw new UnsupportedOperationException("Clearing all headers breaks WebSocket upgrade");
}
@Override
public String getHeader(String name)
{
return getHttpFields().get(name);
}
@Override
public int getHeaderInt(String name)
{
String value = getHttpFields().get(name);
if(value == null) {
return -1;
}
return Integer.parseInt(value);
}
@Override
public List<String> getHeaders(String name)
{
return getHttpFields().getValuesList(name);
}
@Override
public String getHttpVersion()
{
return getVersion().asString();
}
@Override
public String getOrigin()
{
return getHttpFields().get(HttpHeader.ORIGIN);
}
@Override
public Map<String, List<String>> getParameterMap()
{
Map<String,List<String>> paramMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
String query = getQueryString();
MultiMap<String> multimap = new MultiMap<>();
UrlEncoded.decodeTo(query,multimap,StandardCharsets.UTF_8);
paramMap.putAll(multimap);
return paramMap;
}
@Override
public String getProtocolVersion()
{
String ver = getHttpFields().get(HttpHeader.SEC_WEBSOCKET_VERSION);
if (ver == null)
{
return Integer.toString(WebSocketConstants.SPEC_VERSION);
}
return ver;
}
@Override
public String getQueryString()
{
return getURI().getQuery();
}
@Override
public URI getRequestURI()
{
return getURI();
}
@Override
public Object getSession()
{
return this.session;
}
@Override
public Principal getUserPrincipal()
{
// HttpClient doesn't use Principal concepts
return null;
}
@Override
public boolean hasSubProtocol(String test)
{
return getSubProtocols().contains(test);
}
@Override
public boolean isOrigin(String test)
{
return test.equalsIgnoreCase(getOrigin());
}
@Override
public boolean isSecure()
{
// TODO: need to obtain information from actual request to know of SSL was used?
return "wss".equalsIgnoreCase(getURI().getScheme());
}
@Override
public void setCookies(List<HttpCookie> cookies)
{
for(HttpCookie cookie: cookies)
cookie(cookie);
}
@Override
public void setExtensions(List<ExtensionConfig> configs)
{
this.extensions = configs;
updateExtensionHeader();
}
private void updateExtensionHeader()
{
HttpFields headers = getHttpFields();
headers.remove(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
for (ExtensionConfig config : extensions)
{
headers.add(HttpHeader.SEC_WEBSOCKET_EXTENSIONS,config.getParameterizedName());
}
}
@Override
public void setHeader(String name, List<String> values)
{
getHttpFields().put(name,values);
}
@Override
public void setHeader(String name, String value)
{
getHttpFields().put(name,value);
}
@Override
public void setHeaders(Map<String, List<String>> headers)
{
for (Map.Entry<String, List<String>> entry : headers.entrySet())
{
getHttpFields().put(entry.getKey(),entry.getValue());
}
}
@Override
public void setHttpVersion(String httpVersion)
{
version(HttpVersion.fromString(httpVersion));
}
@Override
public void setMethod(String method)
{
method(method);
}
@Override
public void setRequestURI(URI uri)
{
throw new UnsupportedOperationException("Cannot reset/change RequestURI");
}
@Override
public void setSession(Object session)
{
this.session = session;
}
@Override
public void setSubProtocols(List<String> protocols)
{
this.subProtocols = protocols;
}
@Override
public void setSubProtocols(String... protocols)
{
this.subProtocols.clear();
this.subProtocols.addAll(Arrays.asList(protocols));
}
@Override
public List<HttpCookie> getCookies()
{
return WebSocketUpgradeRequest.this.getCookies();
}
@Override
public Map<String, List<String>> getHeaders()
{
Map<String, List<String>> headersMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
HttpFields fields = getHttpFields();
for(String name: fields.getFieldNamesCollection())
{
headersMap.put(name,fields.getValuesList(name));
}
return headersMap;
}
@Override
public String getHost()
{
return WebSocketUpgradeRequest.this.getHost();
}
@Override
public String getMethod()
{
return WebSocketUpgradeRequest.this.getMethod();
}
}
private final WebSocketClient wsClient;
private final EventDriver localEndpoint;
private final CompletableFuture<Session> fut;
/** WebSocket API UpgradeRequest Facade to HttpClient HttpRequest */
private final ClientUpgradeRequestFacade apiRequestFacade;
private UpgradeListener upgradeListener;
/**
* Exists for internal use of HttpClient by WebSocketClient.
* <p>
* Maintained for Backward compatibility and also for JSR356 WebSocket ClientContainer use.
*
* @param wsClient the WebSocketClient that this request uses
* @param httpClient the HttpClient that this request uses
* @param request the ClientUpgradeRequest (backward compat) to base this request from
*/
protected WebSocketUpgradeRequest(WebSocketClient wsClient, HttpClient httpClient, ClientUpgradeRequest request)
{
this(wsClient, httpClient,request.getRequestURI(),request.getLocalEndpoint());
apiRequestFacade.init(request);
}
/**
* Initiating a WebSocket Upgrade using HTTP/1.1
*
* @param wsClient the WebSocketClient that this request uses
* @param httpClient the HttpClient that this request uses
* @param localEndpoint the local endpoint (following Jetty WebSocket Client API rules) to use for incoming
* WebSocket events
* @param wsURI the WebSocket URI to connect to
*/
public WebSocketUpgradeRequest(WebSocketClient wsClient, HttpClient httpClient, URI wsURI, Object localEndpoint)
{
super(httpClient,new HttpConversation(),wsURI);
apiRequestFacade = new ClientUpgradeRequestFacade();
if (!wsURI.isAbsolute())
{
throw new IllegalArgumentException("WebSocket URI must be an absolute URI: " + wsURI);
}
String scheme = wsURI.getScheme();
if (scheme == null || !(scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")))
{
throw new IllegalArgumentException("WebSocket URI must use 'ws' or 'wss' scheme: " + wsURI);
}
this.wsClient = wsClient;
try
{
if (!this.wsClient.isRunning())
{
this.wsClient.start();
}
}
catch (Exception e)
{
throw new IllegalStateException("Unable to start WebSocketClient", e);
}
this.localEndpoint = this.wsClient.getEventDriverFactory().wrap(localEndpoint);
this.fut = new CompletableFuture<Session>();
getConversation().setAttribute(HttpConnectionUpgrader.class.getName(), this);
}
private final String genRandomKey()
{
byte[] bytes = new byte[16];
ThreadLocalRandom.current().nextBytes(bytes);
return new String(B64Code.encode(bytes));
}
private ExtensionFactory getExtensionFactory()
{
return this.wsClient.getExtensionFactory();
}
private SessionFactory getSessionFactory()
{
return this.wsClient.getSessionFactory();
}
private void initWebSocketHeaders()
{
method(HttpMethod.GET);
version(HttpVersion.HTTP_1_1);
// The Upgrade Headers
header(HttpHeader.UPGRADE,"websocket");
header(HttpHeader.CONNECTION,"Upgrade");
// The WebSocket Headers
header(HttpHeader.SEC_WEBSOCKET_KEY,genRandomKey());
header(HttpHeader.SEC_WEBSOCKET_VERSION,"13");
// (Per the hybi list): Add no-cache headers to avoid compatibility issue.
// There are some proxies that rewrite "Connection: upgrade"
// to "Connection: close" in the response if a request doesn't contain
// these headers.
header(HttpHeader.PRAGMA,"no-cache");
header(HttpHeader.CACHE_CONTROL,"no-cache");
// handle "Sec-WebSocket-Extensions"
if (!apiRequestFacade.getExtensions().isEmpty())
{
for (ExtensionConfig ext : apiRequestFacade.getExtensions())
{
header(HttpHeader.SEC_WEBSOCKET_EXTENSIONS,ext.getParameterizedName());
}
}
// handle "Sec-WebSocket-Protocol"
if (!apiRequestFacade.getSubProtocols().isEmpty())
{
for (String protocol : apiRequestFacade.getSubProtocols())
{
header(HttpHeader.SEC_WEBSOCKET_SUBPROTOCOL,protocol);
}
}
if (upgradeListener != null)
{
upgradeListener.onHandshakeRequest(apiRequestFacade);
}
}
@Override
public void onComplete(Result result)
{
if (LOG.isDebugEnabled())
{
LOG.debug("onComplete() - {}",result);
}
URI requestURI = result.getRequest().getURI();
Response response = result.getResponse();
int responseStatusCode = response.getStatus();
String responseLine = responseStatusCode + " " + response.getReason();
if (result.isFailed())
{
if (LOG.isDebugEnabled())
{
if (result.getFailure() != null)
LOG.debug("General Failure", result.getFailure());
if (result.getRequestFailure() != null)
LOG.debug("Request Failure", result.getRequestFailure());
if (result.getResponseFailure() != null)
LOG.debug("Response Failure", result.getResponseFailure());
}
Throwable failure = result.getFailure();
if ((failure instanceof java.io.IOException) || (failure instanceof UpgradeException))
{
// handle as-is
handleException(failure);
}
else
{
// wrap in UpgradeException
handleException(new UpgradeException(requestURI,responseStatusCode,responseLine,failure));
}
}
if (responseStatusCode != HttpStatus.SWITCHING_PROTOCOLS_101)
{
// Failed to upgrade (other reason)
handleException(new UpgradeException(requestURI,responseStatusCode,"Failed to upgrade to websocket: Unexpected HTTP Response Status Code: " + responseLine));
}
}
private void handleException(Throwable failure)
{
localEndpoint.incomingError(failure);
fut.completeExceptionally(failure);
}
@Override
public ContentResponse send() throws InterruptedException, TimeoutException, ExecutionException
{
throw new RuntimeException("Working with raw ContentResponse is invalid for WebSocket");
}
@Override
public void send(final CompleteListener listener)
{
initWebSocketHeaders();
super.send(listener);
}
public CompletableFuture<Session> sendAsync()
{
send(this);
return fut;
}
@Override
public void upgrade(HttpResponse response, HttpConnectionOverHTTP oldConn)
{
if (!this.getHeaders().get(HttpHeader.UPGRADE).equalsIgnoreCase("websocket"))
{
// Not my upgrade
throw new HttpResponseException("Not WebSocket Upgrade",response);
}
// Check the Accept hash
String reqKey = this.getHeaders().get(HttpHeader.SEC_WEBSOCKET_KEY);
String expectedHash = AcceptHash.hashKey(reqKey);
String respHash = response.getHeaders().get(HttpHeader.SEC_WEBSOCKET_ACCEPT);
if (expectedHash.equalsIgnoreCase(respHash) == false)
{
throw new HttpResponseException("Invalid Sec-WebSocket-Accept hash",response);
}
// We can upgrade
EndPoint endp = oldConn.getEndPoint();
WebSocketClientConnection connection = new WebSocketClientConnection(endp,wsClient.getExecutor(),wsClient.getScheduler(),localEndpoint.getPolicy(),
wsClient.getBufferPool());
URI requestURI = this.getURI();
WebSocketSession session = getSessionFactory().createSession(requestURI,localEndpoint,connection);
session.setUpgradeRequest(new ClientUpgradeRequest(this));
session.setUpgradeResponse(new ClientUpgradeResponse(response));
connection.addListener(session);
ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
List<ExtensionConfig> extensions = new ArrayList<>();
HttpField extField = response.getHeaders().getField(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
if (extField != null)
{
String[] extValues = extField.getValues();
if (extValues != null)
{
for (String extVal : extValues)
{
QuotedStringTokenizer tok = new QuotedStringTokenizer(extVal,",");
while (tok.hasMoreTokens())
{
extensions.add(ExtensionConfig.parse(tok.nextToken()));
}
}
}
}
extensionStack.negotiate(extensions);
extensionStack.configure(connection.getParser());
extensionStack.configure(connection.getGenerator());
// Setup Incoming Routing
connection.setNextIncomingFrames(extensionStack);
extensionStack.setNextIncoming(session);
// Setup Outgoing Routing
session.setOutgoingHandler(extensionStack);
extensionStack.setNextOutgoing(connection);
session.addManaged(extensionStack);
session.setFuture(fut);
wsClient.addManaged(session);
if (upgradeListener != null)
{
upgradeListener.onHandshakeResponse(new ClientUpgradeResponse(response));
}
// Now swap out the connection
endp.upgrade(connection);
}
public void setUpgradeListener(UpgradeListener upgradeListener)
{
this.upgradeListener = upgradeListener;
}
private HttpFields getHttpFields()
{
return super.getHeaders();
}
}
|
xiegudong45/typeidea
|
venv/lib/python3.6/site-packages/django/contrib/gis/geos/prototypes/misc.py
|
"""
This module is for the miscellaneous GEOS routines, particularly the
ones that return the area, distance, and length.
"""
from ctypes import POINTER, c_double, c_int
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string
from django.contrib.gis.geos.prototypes.geom import geos_char_p
from django.utils.six.moves import range
__all__ = ['geos_area', 'geos_distance', 'geos_length', 'geos_isvalidreason']
class DblFromGeom(GEOSFuncFactory):
"""
Argument is a Geometry, return type is double that is passed
in by reference as the last argument.
"""
restype = c_int # Status code returned
errcheck = staticmethod(check_dbl)
def get_func(self, num_geom=1):
argtypes = [GEOM_PTR for i in range(num_geom)]
argtypes += [POINTER(c_double)]
self.argtypes = argtypes
return super(DblFromGeom, self).get_func()
# ### ctypes prototypes ###
# Area, distance, and length prototypes.
geos_area = DblFromGeom('GEOSArea')
geos_distance = DblFromGeom('GEOSDistance', num_geom=2)
geos_length = DblFromGeom('GEOSLength')
geos_isvalidreason = GEOSFuncFactory(
'GEOSisValidReason', restype=geos_char_p, errcheck=check_string, argtypes=[GEOM_PTR]
)
|
ngageoint/geopackage-core-android
|
src/main/java/mil/nga/geopackage/extension/metadata/reference/MetadataReferenceDao.java
|
<gh_stars>0
package mil.nga.geopackage.extension.metadata.reference;
import java.sql.SQLException;
import java.util.List;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedUpdate;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import mil.nga.geopackage.GeoPackageCore;
import mil.nga.geopackage.db.GeoPackageCoreConnection;
import mil.nga.geopackage.db.GeoPackageDao;
/**
* Metadata Reference Data Access Object
*
* @author osbornb
*/
public class MetadataReferenceDao
extends GeoPackageDao<MetadataReference, Void> {
/**
* Create the DAO
*
* @param geoPackage
* GeoPackage
* @return dao
* @since 4.0.0
*/
public static MetadataReferenceDao create(GeoPackageCore geoPackage) {
return create(geoPackage.getDatabase());
}
/**
* Create the DAO
*
* @param db
* database connection
* @return dao
* @since 4.0.0
*/
public static MetadataReferenceDao create(GeoPackageCoreConnection db) {
return GeoPackageDao.createDao(db, MetadataReference.class);
}
/**
* Constructor, required by ORMLite
*
* @param connectionSource
* connection
* @param dataClass
* data class
* @throws SQLException
* upon failure
*/
public MetadataReferenceDao(ConnectionSource connectionSource,
Class<MetadataReference> dataClass) throws SQLException {
super(connectionSource, dataClass);
}
/**
* {@inheritDoc}
* <p>
* Update using the foreign key columns
*/
@Override
public int update(MetadataReference metadataReference) throws SQLException {
UpdateBuilder<MetadataReference, Void> ub = updateBuilder();
ub.updateColumnValue(MetadataReference.COLUMN_REFERENCE_SCOPE,
metadataReference.getReferenceScope().getValue());
ub.updateColumnValue(MetadataReference.COLUMN_TABLE_NAME,
metadataReference.getTableName());
ub.updateColumnValue(MetadataReference.COLUMN_COLUMN_NAME,
metadataReference.getColumnName());
ub.updateColumnValue(MetadataReference.COLUMN_ROW_ID_VALUE,
metadataReference.getRowIdValue());
ub.updateColumnValue(MetadataReference.COLUMN_TIMESTAMP,
metadataReference.getTimestamp());
setFkWhere(ub.where(), metadataReference.getFileId(),
metadataReference.getParentId());
PreparedUpdate<MetadataReference> update = ub.prepare();
int updated = update(update);
return updated;
}
/**
* {@inheritDoc}
* <p>
* Delete using the foreign key columns
*/
@Override
public int delete(MetadataReference metadataReference) throws SQLException {
DeleteBuilder<MetadataReference, Void> db = deleteBuilder();
setFkWhere(db.where(), metadataReference.getFileId(),
metadataReference.getParentId());
int deleted = db.delete();
return deleted;
}
/**
* Delete metadata references with foreign keys to the metadata file id
*
* @param fileId
* file id
* @return deleted count
* @throws SQLException
* upon failure
*/
public int deleteByMetadata(long fileId) throws SQLException {
DeleteBuilder<MetadataReference, Void> db = deleteBuilder();
db.where().eq(MetadataReference.COLUMN_FILE_ID, fileId);
int deleted = db.delete();
return deleted;
}
/**
* Remove metadata references (by updating the field to null) with foreign
* keys to the metadata parent id
*
* @param parentId
* parent id
* @return updated count
* @throws SQLException
* upon failure
*/
public int removeMetadataParent(long parentId) throws SQLException {
UpdateBuilder<MetadataReference, Void> ub = updateBuilder();
ub.updateColumnValue(MetadataReference.COLUMN_PARENT_ID, null);
ub.where().eq(MetadataReference.COLUMN_PARENT_ID, parentId);
PreparedUpdate<MetadataReference> update = ub.prepare();
int updated = update(update);
return updated;
}
/**
* Query by the metadata ids
*
* @param fileId
* file id
* @param parentId
* parent id
* @return metadata references
* @throws SQLException
* upon failure
*/
public List<MetadataReference> queryByMetadata(long fileId, Long parentId)
throws SQLException {
QueryBuilder<MetadataReference, Void> qb = queryBuilder();
setFkWhere(qb.where(), fileId, parentId);
List<MetadataReference> metadataReferences = qb.query();
return metadataReferences;
}
/**
* Query by the metadata ids
*
* @param fileId
* file id
* @return metadata references
* @throws SQLException
* upon failure
*/
public List<MetadataReference> queryByMetadata(long fileId)
throws SQLException {
QueryBuilder<MetadataReference, Void> qb = queryBuilder();
qb.where().eq(MetadataReference.COLUMN_FILE_ID, fileId);
List<MetadataReference> metadataReferences = qb.query();
return metadataReferences;
}
/**
* Query by the metadata parent ids
*
* @param parentId
* parent id
* @return metadata references
* @throws SQLException
* upon failure
*/
public List<MetadataReference> queryByMetadataParent(long parentId)
throws SQLException {
QueryBuilder<MetadataReference, Void> qb = queryBuilder();
qb.where().eq(MetadataReference.COLUMN_PARENT_ID, parentId);
List<MetadataReference> metadataReferences = qb.query();
return metadataReferences;
}
/**
* Query by table name
*
* @param tableName
* table name
* @return metadata references
* @throws SQLException
* upon failure
* @since 3.3.0
*/
public List<MetadataReference> queryByTable(String tableName)
throws SQLException {
return queryForEq(MetadataReference.COLUMN_TABLE_NAME, tableName);
}
/**
* Set the foreign key column criteria in the where clause
*
* @param where
* where clause
* @param fileId
* file id
* @param parentId
* parent id
* @throws SQLException
*/
private void setFkWhere(Where<MetadataReference, Void> where, long fileId,
Long parentId) throws SQLException {
where.eq(MetadataReference.COLUMN_FILE_ID, fileId);
if (parentId == null) {
where.and().isNull(MetadataReference.COLUMN_PARENT_ID);
} else {
where.and().eq(MetadataReference.COLUMN_PARENT_ID, parentId);
}
}
/**
* Delete by table name
*
* @param tableName
* table name
* @return rows deleted
* @throws SQLException
* upon failure
* @since 3.2.0
*/
public int deleteByTableName(String tableName) throws SQLException {
DeleteBuilder<MetadataReference, Void> db = deleteBuilder();
db.where().eq(MetadataReference.COLUMN_TABLE_NAME, tableName);
PreparedDelete<MetadataReference> deleteQuery = db.prepare();
int deleted = delete(deleteQuery);
return deleted;
}
}
|
koichi-murakami/g4python
|
source/geometry/pyG4EllipticalTube.cc
|
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
#include <pybind11/pybind11.h>
#include "G4EllipticalTube.hh"
namespace py = pybind11;
// --------------------------------------------------------------------------
namespace {
G4EllipticalTube* CreateEllipticalTube(const G4String& name,
G4double theDx,
G4double theDy,
G4double theDz)
{
return new G4EllipticalTube(name, theDx, theDy, theDz);
}
}
// ==========================================================================
void export_G4EllipticalTube(py::module& m)
{
py::class_<G4EllipticalTube, G4VSolid,
std::unique_ptr<G4EllipticalTube, py::nodelete>>
(m, "G4EllipticalTube")
// ---
.def(py::init<const G4String&, G4double, G4double, G4double>())
// ---
.def("GetDx", &G4EllipticalTube::GetDx)
.def("GetDy", &G4EllipticalTube::GetDy)
.def("GetDz", &G4EllipticalTube::GetDz)
.def("SetDx", &G4EllipticalTube::SetDx)
.def("SetDy", &G4EllipticalTube::SetDy)
.def("SetDz", &G4EllipticalTube::SetDz)
;
// ---
m.def("CreateEllipticalTube", &::CreateEllipticalTube,
py::return_value_policy::reference);
}
|
educlong/phpmysqlangularjs
|
angularJsDemo2/milestone-120/angular/app/scripts/controllers/upload.js
|
<reponame>educlong/phpmysqlangularjs
'use strict';
function uploadCtrl(FileUploader) {
var vm = this;
var uploader = vm.uploader = new FileUploader({
url: 'scripts/upload.php'
});
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function(item /*{File|FileLikeObject}*/ , options) {
return this.queue.length < 10;
}
});
}
angular.module('app').controller('uploadCtrl', ['FileUploader', uploadCtrl]);
|
vol4tim/DAO-IPCI
|
dapp/src/modules/holder/reducer.js
|
import _ from 'lodash'
import { LOAD_MODULE, CALL_FUNC } from './actionTypes'
const initialState = {
modules: [
// {
// address: '0x697b0ac5112a9eace5164e9a76b1e629ded5a990',
// token: '0x697b0ac5112a9eace5164e9a76b1e629ded5a990',
// holdDuration: 3600
// }
]
}
export default function holder(state = initialState, action) {
switch (action.type) {
case LOAD_MODULE: {
const module = _.find(state.modules, ['address', action.payload.address])
let modules
if (module) {
modules = state.modules.map((item) => {
if (item.address === action.payload.address) {
return {
...item,
token: action.payload.token,
holdDuration: action.payload.holdDuration
}
}
return item
})
} else {
modules = [
...state.modules,
action.payload
]
}
return { ...state, modules }
}
case CALL_FUNC: {
const modules = state.modules.map((item) => {
if (item.address === action.payload.address) {
if (_.has(item, 'funcs')) {
return {
...item,
funcs: {
...item.funcs,
[action.payload.action]: {
input: action.payload.input,
output: action.payload.output
}
}
}
}
return {
...item,
funcs: {
[action.payload.action]: {
input: action.payload.input,
output: action.payload.output
}
}
}
}
return item
})
return { ...state, modules }
}
default:
return state;
}
}
|
24apurv/gym-management-java
|
src/com/mail/EmailUtil.java
|
<reponame>24apurv/gym-management-java<filename>src/com/mail/EmailUtil.java
package com.mail;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailUtil {
public static void sendAttachmentEmail(Session session,String toEmail,String subject,String body)
{
try {
MimeMessage msg=new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("<EMAIL>", "NoReply-TitanXFitness"));
msg.setReplyTo(InternetAddress.parse("<EMAIL>", false));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, toEmail);
BodyPart messageBodyPart=new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart=new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart=new MimeBodyPart();
String filename="C:/Invoice/invoice.pdf";
DataSource source=new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("invoice.pdf");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
System.out.println("Sent succesfully!");
} catch (Exception ex) {
Logger.getLogger(EmailUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void sendEmail(Session session,String toEmail,String subject,String body)
{
try {
MimeMessage msg=new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("<EMAIL>", "NoReply-TitanXFitness"));
msg.setReplyTo(InternetAddress.parse("<EMAIL>", false));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, toEmail);
msg.setText(body);
Transport.send(msg);
System.out.println("Sent succesfully!");
} catch (Exception ex) {
Logger.getLogger(EmailUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
jupsal/schmies-jTEM
|
libUnzipped/de/jtem/mfc/matrix/AbstractComplex2By2.java
|
/**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2002-2009, Technische Universität Berlin, jTEM
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
**/
package de.jtem.mfc.matrix;
import java.io.Serializable;
import de.jtem.mfc.field.Complex;
import de.jtem.mfc.field.Field;
import de.jtem.mfc.vector.Complex2;
/** This class is the base for all classes that are or can be represented as
** a complex 2-by-2 matrix.
**
** <p> Most of its functionallity is implemented
** in protected methods. This enables derived classes to specialize and omit
** certain functions. For example, it does not make any sense to add {@link
** de.jtem.mfc.group.Moebius} transformations.
**
** <p> To minimize the object count its
** 4 complex entries <code>a,b,c,d</code> are represented by 8 double values
** <code>{@link #aRe}, {@link #aIm}, {@link #bRe}, {@link #bIm}, {@link
** #cRe}, {@link #cIm}, {@link #dRe}, {@link #dIm}</code>, e.g.:
**
** <pre>
** [ a b ] [ aRe + i aIm bRe + i bIm ]
** [ ] = [ ]
** [ c d ] [ dRe + i dIm dRe + i dIm ]
** </pre>
**
** <p> All methods avoid the creation of temporarily used objects
** in their internal computations unless the opposite is stated in their
** descriptions.
**
** <p>This class has <code>final</code> member objects, which are
** used as dummy variables. Thus, it is definitely not thread-safe.
**
** @author schmies */
public abstract class AbstractComplex2By2 implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/** @deprecated superceded by EPS */
public static final double EPSILON = 1.e-14;
/** threashold for zero tests; default is 1e-14 */
public static final double EPS = 1.e-14;
/** the square of {@link #EPS} */
public static final double EPSSQR = EPS * EPS;
/**
* Dummy variable used in calculations.
*/
static final Complex dummyComplex = new Complex();
/**
* Dummy variable used in calculations.
*/
static final Complex2By2 dummyComplex2By2 = new Complex2By2();
/** entry of the matrix */
protected double aRe, aIm, bRe, bIm, cRe, cIm, dRe, dIm;
/** creates an identity matrix */
protected AbstractComplex2By2() {
assignIdentity();
}
/** creates a matrix with the prescribed entries */
protected AbstractComplex2By2( final double aRe, final double aIm,
final double bRe, final double bIm,
final double cRe, final double cIm,
final double dRe, final double dIm) {
assign( aRe, aIm, bRe, bIm, cRe, cIm, dRe, dIm );
}
/** creates a matrix with the prescribed entries */
protected AbstractComplex2By2( final Complex a, final Complex b,
final Complex c, final Complex d) {
assign( a.re, a.im, b.re, b.im, c.re, c.im, d.re, d.im);
}
/** creates a matrix with the prescribed entries */
protected AbstractComplex2By2(final Field.Complex a,
final Field.Complex b,
final Field.Complex c,
final Field.Complex d) {
assign(a.getRe(), a.getIm(), b.getRe(), b.getIm(),
c.getRe(), c.getIm(), d.getRe(), d.getIm());
}
/** creates a matrix equaling prescribed matrix */
public AbstractComplex2By2( final AbstractComplex2By2 m ) {
assign( m );
}
/** returns entry <code>a</code> of this */
public Complex getA() {
return new Complex( aRe, aIm );
}
/** assigns <code>a</code> with entry <code>a</code> of this
** @param a complex value which is assigned with entry <code>a</code>. */
public void getA( final Complex a ) {
a.assign( aRe, aIm );
}
/** sets entry <code>a</code> of this with <code>a</code> */
protected void setA( final Complex a ) {
aRe = a.re;
aIm = a.im;
}
/** returns entry <code>b</code> of this */
public Complex getB() {
return new Complex( bRe, bIm );
}
/** assigns <code>b</code> with entry <code>b</code> of this
** @param b complex value which is assigned with entry <code>b</code>.*/
public void getB( final Complex b ) {
b.assign( bRe, bIm );
}
/** sets entry <code>b</code> of this with <code>b</code> */
protected void setB( final Complex b ) {
bRe = b.re;
bIm = b.im;
}
/** returns entry <code>c</code> of this */
public Complex getC() {
return new Complex( cRe, cIm );
}
/** assigns <code>c</code> with entry <code>c</code> of this
** @param c complex value which is assigned with entry <code>c</code>. */
public void getC( final Complex c ) {
c.assign( cRe, cIm );
}
/** sets entry <code>c</code> of this with <code>c</code> */
protected void setC( final Complex c ) {
cRe = c.re;
cIm = c.im;
}
/** returns entry <code>d</code> of this */
public Complex getD() {
return new Complex( dRe, dIm );
}
/** assigns <code>d</code> with entry <code>d</code> of this
** @param d complex value which is assigned with entry <code>d</code>. */
public void getD( final Complex d ){
d.assign( dRe, dIm );
}
/** sets entry <code>d</code> of this with <code>d</code> */
protected void setD( final Complex d ) {
dRe = d.re;
dIm = d.im;
}
/** assigns this with the zero matrix */
protected void assignZero() {
assign( 0, 0, 0, 0, 0, 0, 0, 0 );
}
/** assigns this with the identity matrix */
protected void assignIdentity() {
assign( 1, 0, 0, 0, 0, 0, 1, 0 );
}
/** assigns this with the prescribed entries */
protected void assign( double aRe, double aIm, double bRe, double bIm,
double cRe, double cIm, double dRe, double dIm) {
this.aRe = aRe; this.aIm = aIm; this.bRe = bRe; this.bIm = bIm;
this.cRe = cRe; this.cIm = cIm; this.dRe = dRe; this.dIm = dIm;
}
/** assigns this with the prescribed entries */
protected void assign( final Complex a, final Complex b,
final Complex c, final Complex d ) {
assign( a.re, a.im, b.re, b.im, c.re, c.im, d.re, d.im );
}
/** assigns this with the prescribed matrix */
protected void assign( final AbstractComplex2By2 s ) {
assign( s.aRe, s.aIm, s.bRe, s.bIm, s.cRe, s.cIm, s.dRe, s.dIm );
}
/** assigns this with the product of itself and a */
protected void assignTimes( final AbstractComplex2By2 a ) {
assignTimes(this, a );
}
/**
* multiplies <code>a</code> and <code>b</code> and stores
* the result in <code>c</code>.
*/
public static void times( final AbstractComplex2By2 a,
final AbstractComplex2By2 b,
final AbstractComplex2By2 c ) {
if( a == c || b == c) {
double d1r = a.aRe*b.aRe-a.aIm*b.aIm + a.bRe*b.cRe-a.bIm*b.cIm;
double d1i = a.aRe*b.aIm+a.aIm*b.aRe + a.bRe*b.cIm+a.bIm*b.cRe;
double d2r = a.aRe*b.bRe-a.aIm*b.bIm + a.bRe*b.dRe-a.bIm*b.dIm;
double d2i = a.aRe*b.bIm+a.aIm*b.bRe + a.bRe*b.dIm+a.bIm*b.dRe;
double d3r = a.cRe*b.aRe-a.cIm*b.aIm + a.dRe*b.cRe-a.dIm*b.cIm;
double d3i = a.cRe*b.aIm+a.cIm*b.aRe + a.dRe*b.cIm+a.dIm*b.cRe;
double d4r = a.cRe*b.bRe-a.cIm*b.bIm + a.dRe*b.dRe-a.dIm*b.dIm;
double d4i = a.cRe*b.bIm+a.cIm*b.bRe + a.dRe*b.dIm+a.dIm*b.dRe;
c.aRe=d1r; c.aIm=d1i; c.bRe=d2r; c.bIm=d2i; c.cRe=d3r; c.cIm=d3i; c.dRe=d4r; c.dIm=d4i;
} else {
c.aRe = a.aRe*b.aRe-a.aIm*b.aIm + a.bRe*b.cRe-a.bIm*b.cIm;
c.aIm = a.aRe*b.aIm+a.aIm*b.aRe + a.bRe*b.cIm+a.bIm*b.cRe;
c.bRe = a.aRe*b.bRe-a.aIm*b.bIm + a.bRe*b.dRe-a.bIm*b.dIm;
c.bIm = a.aRe*b.bIm+a.aIm*b.bRe + a.bRe*b.dIm+a.bIm*b.dRe;
c.cRe = a.cRe*b.aRe-a.cIm*b.aIm + a.dRe*b.cRe-a.dIm*b.cIm;
c.cIm = a.cRe*b.aIm+a.cIm*b.aRe + a.dRe*b.cIm+a.dIm*b.cRe;
c.dRe = a.cRe*b.bRe-a.cIm*b.bIm + a.dRe*b.dRe-a.dIm*b.dIm;
c.dIm = a.cRe*b.bIm+a.cIm*b.bRe + a.dRe*b.dIm+a.dIm*b.dRe;
}
}
/** assigns this with the product of <code>a</code> and <code>b</code> */
protected void assignTimes( final AbstractComplex2By2 a, final AbstractComplex2By2 b ) {
times( a, b, this );
}
/** assigns this with the product of itself and <code>r</code> */
protected void assignTimes( final double r ) {
assignTimes( this, r );
}
/** assigns this with the product of <code>m</code> and <code>r</code> */
protected void assignTimes( final AbstractComplex2By2 m, final double r ) {
if( m == this ) {
aRe *= r; aIm *= r;
bRe *= r; bIm *= r;
cRe *= r; cIm *= r;
dRe *= r; dIm *= r;
} else {
aRe = m.aRe * r; aIm = m.aIm * r;
bRe = m.bRe * r; bIm = m.bIm * r;
cRe = m.cRe * r; cIm = m.cIm * r;
dRe = m.dRe * r; dIm = m.dIm * r;
}
}
/** assigns this with the product of itself and <code>x+iy</code> */
protected void assignTimes( final double x, final double y ) {
assignTimes( this, x, y );
}
/** assigns this with the product of <code>m</code> and <code>x+iy</code> */
protected void assignTimes( final AbstractComplex2By2 m, final double x, final double y ) {
if( m == this ) {
double tmp;
tmp = aRe * x - aIm * y;
aIm = aIm * x + aRe * y;
aRe = tmp;
tmp = bRe * x - bIm * y;
bIm = bIm * x + bRe * y;
bRe = tmp;
tmp = cRe * x - cIm * y;
cIm = cIm * x + cRe * y;
cRe = tmp;
tmp = dRe * x - dIm * y;
dIm = dIm * x + dRe * y;
dRe = tmp;
} else {
aRe = m.aRe * x - m.aIm * y;
aIm = m.aIm * x + m.aRe * y;
bRe = m.bRe * x - m.bIm * y;
bIm = m.bIm * x + m.bRe * y;
cRe = m.cRe * x - m.cIm * y;
cIm = m.cIm * x + m.cRe * y;
dRe = m.dRe * x - m.dIm * y;
dIm = m.dIm * x + m.dRe * y;
}
}
/** returns product of this and <code>z</code> */
protected void assignTimes( final Complex z ) {
assignTimes( this, z.re, z.im );
}
/** assigns this with the product of <code>m</code> and <code>z</code> */
protected void assignTimes( final AbstractComplex2By2 m, final Complex z ) {
assignTimes( m, z.re, z.im );
}
/** assigns this with the product of itself and inverse of <code>m</code>*/
protected void assignDivide( final AbstractComplex2By2 m ) {
assignDivide( this, m );
}
/**
* multiplies <code>a</code> and inverse of <code>b</code> and stores
* the result in <code>c</code>.
*/
public static void divide( final AbstractComplex2By2 a,
final AbstractComplex2By2 b,
final AbstractComplex2By2 c ) {
double detRe = b.aRe * b.dRe - b.aIm * b.dIm - ( b.bRe * b.cRe - b.bIm * b.cIm );
double detIm = b.aRe * b.dIm + b.aIm * b.dRe - ( b.bRe * b.cIm + b.bIm * b.cRe );
double nn = detRe * detRe + detIm * detIm;
if( nn == 0 )
throw new RuntimeException( "Matrix is not invertible. " );
if( a==c || b==c ) {
double d1r = a.aRe*b.dRe-a.aIm*b.dIm - a.bRe*b.cRe+a.bIm*b.cIm;
double d1i = a.aRe*b.dIm+a.aIm*b.dRe - a.bRe*b.cIm-a.bIm*b.cRe;
double d2r = a.bRe*b.aRe-a.bIm*b.aIm - a.aRe*b.bRe+a.aIm*b.bIm;
double d2i = a.bRe*b.aIm+a.bIm*b.aRe - a.aRe*b.bIm-a.aIm*b.bRe;
double d3r = a.cRe*b.dRe-a.cIm*b.dIm - a.dRe*b.cRe+a.dIm*b.cIm;
double d3i = a.cRe*b.dIm+a.cIm*b.dRe - a.dRe*b.cIm-a.dIm*b.cRe;
double d4r = a.dRe*b.aRe-a.dIm*b.aIm - a.cRe*b.bRe+a.cIm*b.bIm;
double d4i = a.dRe*b.aIm+a.dIm*b.aRe - a.cRe*b.bIm-a.cIm*b.bRe;
c.aRe=d1r; c.aIm=d1i; c.bRe=d2r; c.bIm=d2i; c.cRe=d3r; c.cIm=d3i; c.dRe=d4r; c.dIm=d4i;
} else {
c.aRe = a.aRe*b.dRe-a.aIm*b.dIm - a.bRe*b.cRe+a.bIm*b.cIm;
c.aIm = a.aRe*b.dIm+a.aIm*b.dRe - a.bRe*b.cIm-a.bIm*b.cRe;
c.bRe = a.bRe*b.aRe-a.bIm*b.aIm - a.aRe*b.bRe+a.aIm*b.bIm;
c.bIm = a.bRe*b.aIm+a.bIm*b.aRe - a.aRe*b.bIm-a.aIm*b.bRe;
c.cRe = a.cRe*b.dRe-a.cIm*b.dIm - a.dRe*b.cRe+a.dIm*b.cIm;
c.cIm = a.cRe*b.dIm+a.cIm*b.dRe - a.dRe*b.cIm-a.dIm*b.cRe;
c.dRe = a.dRe*b.aRe-a.dIm*b.aIm - a.cRe*b.bRe+a.cIm*b.bIm;
c.dIm = a.dRe*b.aIm+a.dIm*b.aRe - a.cRe*b.bIm-a.cIm*b.bRe;
}
c.assignDivide( nn );
}
/** assigns this with the product of <code>a</code> and inverse of <code>b</code> */
protected void assignDivide( final AbstractComplex2By2 a, final AbstractComplex2By2 b ) {
divide( a, b, this );
}
/** assigns this with the product of itself and <code>1/r</code> */
protected void assignDivide( final double r ) {
assignDivide( this, r );
}
/** assigns this with the product of <code>m</code> and <code>1/r</code> */
protected void assignDivide( final AbstractComplex2By2 m, final double r ) {
if( m == this ) {
aRe /= r; aIm /= r;
bRe /= r; bIm /= r;
cRe /= r; cIm /= r;
dRe /= r; dIm /= r;
} else {
aRe = m.aRe / r; aIm = m.aIm / r;
bRe = m.bRe / r; bIm = m.bIm / r;
cRe = m.cRe / r; cIm = m.cIm / r;
dRe = m.dRe / r; dIm = m.dIm / r;
}
}
/** assigns this with the product of itself and <code>1/(x+iy)</code> */
protected void assignDivide( final double x, final double y ) {
assignDivide( this, x, y );
}
/** assigns this with the product of <code>m</code> and <code>1/(x+iy)</code> */
protected void assignDivide( final AbstractComplex2By2 m, final double x, final double y ) {
double nn = x * x + y * y;
if( nn != 0 ) {
assignTimes( m, x, -y );
}
assignDivide( nn );
}
/** assigns this with the product of itself and <code>1/z</code> */
protected void assignDivide( final Complex z ) {
assignDivide( this, z.re, z.im );
}
/** assigns this with the product of <code>m</code> and <code>1/z</code> */
protected void assignDivide( final AbstractComplex2By2 m, final Complex z ) {
double nn = z.re * z.re + z.im * z.im;
if( nn != 0 ) {
assignTimes( m, z.re, -z.im );
}
assignDivide( nn );
}
/** assigns this with the sum of itself and a */
protected void assignPlus( final AbstractComplex2By2 a ) {
assignPlus(this, a );
}
/**
* adds <code>a</code> and <code>b</code> and stores
* the result in <code>c</code>.
*/
public static void plus( final AbstractComplex2By2 a,
final AbstractComplex2By2 b,
final AbstractComplex2By2 c ) {
c.aRe = a.aRe + b.aRe;
c.aIm = a.aIm + b.aIm;
c.bRe = a.bRe + b.bRe;
c.bIm = a.bIm + b.bIm;
c.cRe = a.cRe + b.cRe;
c.cIm = a.cIm + b.cIm;
c.dRe = a.dRe + b.dRe;
c.dIm = a.dIm + b.dIm;
}
/** assigns this with the sum of <code>a</code> and <code>b</code> */
protected void assignPlus( final AbstractComplex2By2 a, final AbstractComplex2By2 b ) {
plus( a, b, this );
}
/** adds <code>x</code> to all entries of this */
protected void assignPlus( final double x ) {
assignPlus( this, x );
}
/** adds <code>x</code> to all entries of <code>m</code> and
and assigns this with the result. */
protected void assignPlus( final AbstractComplex2By2 m, final double x ) {
aRe = m.aRe + x;
bRe = m.bRe + x;
cRe = m.cRe + x;
dRe = m.dRe + x;
}
/** adds <code>x+iy</code> to all entries of this */
protected void assignPlus( final double x, final double y ) {
assignPlus( this, x, y );
}
/** adds <code>x+iy</code> to all entries of <code>m</code> and
and assigns this with the result. */
protected void assignPlus( final AbstractComplex2By2 m, final double x, final double y ) {
aRe = m.aRe + x;
aIm = m.aIm + y;
bRe = m.bRe + x;
bIm = m.bIm + y;
cRe = m.cRe + x;
cIm = m.cIm + y;
dRe = m.dRe + x;
dIm = m.dIm + y;
}
/** adds <code>z</code> to all entries of this */
protected void assignPlus( final Complex z ) {
assignPlus( this, z.re, z.im );
}
/** adds <code>z</code> to all entries of <code>m</code> and
and assigns this with the result. */
protected void assignPlus( final AbstractComplex2By2 m, final Complex z ) {
assignPlus( m, z.re, z.im );
}
/** subtracts <code>a</code> from this */
protected void assignMinus( final AbstractComplex2By2 a ) {
assignMinus(this, a );
}
/**
* subtracts <code>b</code> from <code>a</code> and stores
* the result in <code>c</code>.
*/
public static void minus( final AbstractComplex2By2 a,
final AbstractComplex2By2 b,
final AbstractComplex2By2 c ) {
c.aRe = a.aRe - b.aRe;
c.aIm = a.aIm - b.aIm;
c.bRe = a.bRe - b.bRe;
c.bIm = a.bIm - b.bIm;
c.cRe = a.cRe - b.cRe;
c.cIm = a.cIm - b.cIm;
c.dRe = a.dRe - b.dRe;
c.dIm = a.dIm - b.dIm;
}
/** subtracts <code>b</code> from <code>a</code> and stores the result it this */
protected void assignMinus( final AbstractComplex2By2 a, final AbstractComplex2By2 b ) {
minus( a, b, this );
}
/** subtracts <code>x</code> from all entries of this */
protected void assignMinus( final double x ) {
assignMinus( this, x );
}
/** subtracts <code>x</code> from all entries of <code>m</code> and
and assigns this with the result. */
protected void assignMinus( final AbstractComplex2By2 m, final double x ) {
aRe = m.aRe - x;
bRe = m.bRe - x;
cRe = m.cRe - x;
dRe = m.dRe - x;
}
/** subtracts <code>x+iy</code> to all entries of this */
protected void assignMinus( final double x, final double y ) {
assignMinus( this, x, y );
}
/** subtracts <code>x+iy</code> to all entries of <code>m</code> and
and assigns this with the result. */
protected void assignMinus( final AbstractComplex2By2 m, final double x, final double y ) {
aRe = m.aRe - x;
aIm = m.aIm - y;
bRe = m.bRe - x;
bIm = m.bIm - y;
cRe = m.cRe - x;
cIm = m.cIm - y;
dRe = m.dRe - x;
dIm = m.dIm - y;
}
/** subtracts <code>z</code> from all entries of this */
protected void assignMinus( final Complex z ) {
assignMinus( this, z.re, z.im );
}
/** subtracts <code>z</code> to all entries of <code>m</code> and
and assigns this with the result. */
protected void assignMinus( final AbstractComplex2By2 m, final Complex z ) {
assignMinus( m, z.re, z.im );
}
/** assigns this with the negative of <code>a</code> */
protected void assignNeg( final AbstractComplex2By2 a ) {
aRe = -a.aRe;
aIm = -a.aIm;
bRe = -a.bRe;
bIm = -a.bIm;
cRe = -a.cRe;
cIm = -a.cIm;
dRe = -a.dRe;
dIm = -a.dIm;
}
/** assigns this with its own negative */
protected void assignNeg() {
assignNeg( this );
}
/** assigns this with the conjugateative of <code>a</code> */
protected void assignConjugate( final AbstractComplex2By2 a ) {
if( a == this ) {
aIm = -a.aIm;
bIm = -a.bIm;
cIm = -a.cIm;
dIm = -a.dIm;
} else {
aRe = a.aRe;
aIm = -a.aIm;
bRe = a.cRe;
bIm = -a.cIm;
cRe = a.bRe;
cIm = -a.bIm;
dRe = a.dRe;
dIm = -a.dIm;
}
}
/** assigns this with its own conjugate */
protected void assignConjugate() {
assignConjugate( this );
}
/** assigns this with the transposed of <code>a</code> */
protected void assignTranspose( final AbstractComplex2By2 a ) {
if( a == this ) {
double tmp;
tmp = bRe; bRe = cRe; cRe = tmp;
tmp = bIm; bIm = cIm; cIm = tmp;
} else {
aRe = a.aRe;
aIm = a.aIm;
bRe = a.cRe;
bIm = a.cIm;
cRe = a.bRe;
cIm = a.bIm;
dRe = a.dRe;
dIm = a.dIm;
}
}
/** assigns this with its own transposed */
protected void assignTranspose() {
assignTranspose( this );
}
/** assigns this with the transposed and conjugated of <code>a</code> */
protected void assignStar( final AbstractComplex2By2 a ) {
if( a == this ) {
double tmp;
tmp = bRe; bRe = cRe; cRe = tmp;
tmp = bIm; bIm = -cIm; cIm = -tmp;
aIm = -aIm;
dIm = -dIm;
} else {
aRe = a.aRe;
aIm = -a.aIm;
bRe = a.cRe;
bIm = -a.cIm;
cRe = a.bRe;
cIm = -a.bIm;
dRe = a.dRe;
dIm = -a.dIm;
}
}
/** assigns this with its own transposed and conjugated*/
protected void assignStar() {
assignStar( this );
}
/** assigns this with the adjugate of <code>a</code> */
protected void assignAdjugate( final AbstractComplex2By2 a ) {
double tmp;
tmp = a.aRe; aRe = a.dRe; dRe = tmp;
tmp = a.aIm; aIm = a.dIm; dIm = tmp;
bRe = -a.bRe;
bIm = -a.bIm;
cRe = -a.cRe;
cIm = -a.cIm;
}
/** assigns this with its own adjugate */
protected void assignAdjugate() {
assignAdjugate( this );
}
/** assigns this with the inverse of <code>m</code> */
protected void assignInvert( final AbstractComplex2By2 m ) {
double detRe = m.aRe*m.dRe - m.aIm*m.dIm - ( m.bRe*m.cRe - m.bIm*m.cIm );
double detIm = m.aRe*m.dIm + m.aIm*m.dRe - ( m.bRe*m.cIm + m.bIm*m.cRe );
double nn = detRe * detRe + detIm * detIm;
if( nn == 0 )
throw new RuntimeException( m + " matrix is not invertable" );
assignAdjugate( m );
assignTimes( detRe / nn, - detIm / nn );
}
/** assigns this with its own inverse */
protected void assignInvert() {
assignInvert( this );
}
/** assigns this with the adjoined of <code>a</code> */
protected void assignAdjoined( final AbstractComplex2By2 a ) {
double tmp;
tmp = a.bRe; bRe = a.cRe; cRe = tmp;
tmp = -a.bIm; bIm = -a.cIm; cIm = tmp;
aRe = a.aRe; aIm = -a.aIm;
dRe = a.dRe; dIm = -a.dIm;
}
/** assigns this with its own adjoined */
protected void assignAdjoined() {
assignAdjoined( this );
}
/** assigns this with <code>m</code> and normalizes (determinant equals 1) it */
protected void assignNormalizeDeterminant( final AbstractComplex2By2 m ) {
final double detRe = m.aRe*m.dRe - m.aIm*m.dIm - ( m.bRe*m.cRe - m.bIm*m.cIm );
final double detIm = m.aRe*m.dIm + m.aIm*m.dRe - ( m.bRe*m.cIm + m.bIm*m.cRe );
if( Math.abs( detIm ) > EPS || Math.abs( detRe - 1.0 ) > EPS ) {
final double rr = Math.sqrt( Complex.abs( detRe, detIm ) );
final double ii = Complex.arg( detRe, detIm ) / 2;
final double sqrtOfDetRe = rr * Math.cos( ii );
final double sqrtOfDetIm = rr * Math.sin( ii );
final double nn = sqrtOfDetRe*sqrtOfDetRe + sqrtOfDetIm*sqrtOfDetIm;
if( nn == 0 )
throw new ArithmeticException("Matrix determinant is zero" );
if( this != m )
assign(m);
assignTimes( sqrtOfDetRe, -sqrtOfDetIm );
assignDivide( nn );
}
}
/** normalizes (determinant equals 1) this */
protected void assignNormalizeDeterminant() {
assignNormalizeDeterminant( this );
}
/**
* Assign <code>this</code> by column.
*
* @param column1 a {@link Complex2}: the first column. Must not be
* <code>null</code>
* @param column2 a {@link Complex2}: the second column. Must not be
* <code>null</code>
*/
protected void assignByColumn(final Complex2 column1,
final Complex2 column2) {
assign(column1.aRe, column1.aIm, column2.aRe, column2.aIm,
column1.bRe, column1.bIm, column2.bRe, column2.bIm);
}
/**
* Assign <code>this</code> with <code>t this t<sup>-1</sup>.
*
* @param t an {@link AbstractComplex2By2}: the matrix with which to
* conjugate
* @throws IllegalArgumentException if determinant of parameter
* <code>t</code> is <code>0.0</code>.
*/
protected void assignConjugateWith(final AbstractComplex2By2 t)
throws IllegalArgumentException {
t.determinant(dummyComplex);
if (dummyComplex.re == 0.0 && dummyComplex.im == 0.0) {
throw new IllegalArgumentException("Det t == 0.0. ");
}
this.assignAdjugate();
this.assignTimes(t, this);
this.assignAdjugate();
this.assignTimes(t, this);
this.assignDivide(dummyComplex);
}
/**
* Assign <code>this</code> with <code>t this t<sup>*</sup></code>.
*
* @param t an {@link AbstractComplex2By2}: the matrix to adjoin
*/
protected void assignAdjoinedWith(final AbstractComplex2By2 t) {
this.assignTimes(t, this);
this.assignAdjoined();
this.assignTimes(t, this);
this.assignAdjoined();
}
/**
* <p>Assign <code>this</code> by prescribing eigenvectors and
* eigenvalues. </p>
*
* <p> The given eigenvectors must be linearly independent. </p>
*
* @param eigenvalue1Re a <code>double</code>: real part of the first
* eigenvalue
* @param eigenvalue1Im a <code>double</code>: imaginary part of the
* first eigenvalue
* @param eigenvector1 a {@link Complex2}: first eigenvector
* @param eigenvalue2Re a <code>double</code>: real part of the second
* eigenvalue
* @param eigenvalue2Im a <code>double</code>: imaginary part of the
* second eigenvalue
* @param eigenvector2 a {@link Complex2}: second eigenvector
*/
protected void assignByEigenvectors(final double eigenvalue1Re,
final double eigenvalue1Im,
final Complex2 eigenvector1,
final double eigenvalue2Re,
final double eigenvalue2Im,
final Complex2 eigenvector2) {
/* Let this be a diagonal matrix with the eigenvalues as entries. */
this.assign(eigenvalue1Re, eigenvalue1Im, 0.0, 0.0,
0.0, 0.0, eigenvalue2Re, eigenvalue2Im);
/* Make a matrix whose columns are the eigenvectors. */
dummyComplex2By2.assignByColumn(eigenvector1, eigenvector2);
/* Transform this. */
this.assignConjugateWith(dummyComplex2By2);
}
/**
* <p>Assign <code>this</code> by prescribing eigenvectors and
* eigenvalues. </p>
*
* <p> The given eigenvectors must be linearly independent. </p>
*
* @param eigenvalue1 a {@link Field.Complex}: first eigenvalue
* @param eigenvector1 a {@link Complex2}: first eigenvector
* @param eigenvalue2 a {@link Field.Complex}: second eigenvalue
* @param eigenvector2 a {@link Complex2}: second eigenvector
*/
protected void assignByEigenvectors(final Complex eigenvalue1,
final Complex2 eigenvector1,
final Complex eigenvalue2,
final Complex2 eigenvector2) {
assignByEigenvectors(eigenvalue1.re, eigenvalue1.im, eigenvector1,
eigenvalue2.re, eigenvalue2.im, eigenvector2);
}
/** returns square of eucleaden norm */
final public double absSqr() {
return aRe*aRe + aIm*aIm + bRe*bRe + bIm*bIm + cRe*cRe + cIm*cIm +dRe*dRe + dIm*dIm;
}
/** returns eucleaden norm */
final public double abs() {
return Math.sqrt( absSqr() );
}
/** returns square of eucleaden distance of this to <code>s</code> */
final public double distSqr( final AbstractComplex2By2 s ) {
return
(s.aRe-aRe)*(s.aRe-aRe) + (s.aIm-aIm)*(s.aIm-aIm) +
(s.bRe-bRe)*(s.bRe-bRe) + (s.bIm-bIm)*(s.bIm-bIm) +
(s.cRe-cRe)*(s.cRe-cRe) + (s.cIm-cIm)*(s.cIm-cIm) +
(s.dRe-dRe)*(s.dRe-dRe) + (s.dIm-dIm)*(s.dIm-dIm);
}
/** returns eucleaden distance of this to <code>s</code> */
final public double dist( final AbstractComplex2By2 s ) {
return Math.sqrt( distSqr( s ) );
}
/** returns determinant of this */
final public Complex determinant() {
Complex det = new Complex();
determinant( det );
return det;
}
/** assigns <code>det</code> with the determinant of this
** @param det complex value which is assigned with the determinant */
final public void determinant( final Complex det ) {
final double detRe = aRe*dRe - aIm*dIm - bRe*cRe + bIm*cIm;
final double detIm = aRe*dIm + aIm*dRe - bRe*cIm - bIm*cRe;
det.assign( detRe, detIm );
}
/** returns trace of this */
final public Complex trace() {
Complex trace = new Complex();
trace( trace );
return trace;
}
/** assigns <code>trace</code> with the trace of this
** @param trace complex value which is assigned with the trace */
final public void trace( final Complex trace ) {
trace.assign( aRe + dRe, aIm + dIm );
}
/** returns the square of absulate value of the bigger eigenvalue.
** It creates a temporarily used instance of <code>Field.Complex</code> */
final public double normSqr() {
final Complex bigEV = new Complex();
getEigenValues( null, bigEV );
return bigEV.absSqr();
}
/** returns the absulate value of the bigger eigenvalue.
** It creates one temporarily used instance of <code>Field.Complex</code> */
final public double norm() {
final Complex bigEV = new Complex();
getEigenValues( null, bigEV );
return bigEV.abs();
}
/** assigns <code>smallEV</code> with the smaller eigenvalue of this
** and <code>bigEV</code> with the bigger;
** both, <code>smallEV</code> and <code>bigEV</code>, may be <code>null</code>. */
final public void getEigenValues( final Complex smallEV, final Complex bigEV ) {
final double detRe = aRe*dRe - aIm*dIm - bRe*cRe + bIm*cIm;
final double detIm = aRe*dIm + aIm*dRe - bRe*cIm - bIm*cRe;
final double aPlusDRe = aRe + dRe;
final double aPlusDIm = aIm + dIm;
// dis = (a+d)^2 - 4*det
final double disRe = aPlusDRe * aPlusDRe - aPlusDIm * aPlusDIm - 4*detRe;
final double disIm = aPlusDRe * aPlusDIm + aPlusDIm * aPlusDRe - 4*detIm;
// compute sqrt of dis
final double rr = Math.sqrt( Complex.abs( disRe, disIm ) );
final double ii = Complex.arg( disRe, disIm ) / 2;
double sqrtOfDisRe = rr * Math.cos( ii );
double sqrtOfDisIm = rr * Math.sin( ii );
// we want < a+b, dis^0.5 > to be non negative
if( aPlusDRe * sqrtOfDisRe + aPlusDIm * sqrtOfDisIm < 0 ) {
sqrtOfDisRe = -sqrtOfDisRe;
sqrtOfDisIm = -sqrtOfDisIm;
}
if( smallEV != null )
smallEV.assign( ( aPlusDRe - sqrtOfDisRe ) / 2,
( aPlusDIm - sqrtOfDisIm ) / 2 );
if( bigEV != null )
bigEV. assign( ( aPlusDRe + sqrtOfDisRe ) / 2,
( aPlusDIm + sqrtOfDisIm ) / 2 );
}
/** assigns the first two entries of array <code>ev</code> to the
** eigenvalues of the this;
** the first entry contains the eigenvalue with the smaller euclidean norm.
** if an entry of the array is <code>null</code> an instance of <code>Field.Complex</code> is created. */
final public void getEigenValues( final Complex[] ev ) {
if( ev[0] == null ) ev[0] = new Complex();
if( ev[1] == null ) ev[1] = new Complex();
getEigenValues( ev[0], ev[1] );
}
/** returns array containing the two eigenvalues;
** the first entry contains the eigenvalue with the smaller euclidean norm. */
final public Complex[] getEigenValues() {
final Complex[] ev = new Complex[2];
getEigenValues( ev );
return ev;
}
/** this is considered to equal <code>o</code> if
** their euclidean distance is smaller than <code>{@link #EPS}</code> */
public boolean equals(Object o) {
try {
return distSqr( (AbstractComplex2By2)o ) < EPS * EPS;
} catch(ClassCastException ex) {
return false;
}
}
public String toString() {
StringBuffer sb=new StringBuffer().append('(').append('(').append('(').append(aRe);
if(aIm>=0.0)
sb.append('+');
sb.append(aIm).append('i').append(')').append(',').append('(').append(bRe);
if(bIm>=0.0)
sb.append('+');
sb.append(bIm).append('i').append(')').append(')').append(',');
sb.append('(').append('(').append(cRe);
if(cIm>=0.0)
sb.append('+');
sb.append(cIm).append('i').append(')').append(',').append('(').append(dRe);
if(dIm>=0.0)
sb.append('+');
sb.append(dIm).append('i').append(')').append(')').append(')');
return sb.toString();
}
/**
* Multiplies <code>m</code> with <code>v</code> and stores the result
* in <code>w</code>.
*/
public static void times( AbstractComplex2By2 m, Complex2 v, Complex2 w ) {
if ( v == w ) {
double wARe = m.aRe*v.aRe-m.aIm*v.aIm + m.bRe*v.bRe-m.bIm*v.bIm;
double wAIm = m.aRe*v.aIm+m.aIm*v.aRe + m.bRe*v.bIm+m.bIm*v.bRe;
double wBRe = m.cRe*v.aRe-m.cIm*v.aIm + m.dRe*v.bRe-m.dIm*v.bIm;
double wBIm = m.cRe*v.aIm+m.cIm*v.aRe + m.dRe*v.bIm+m.dIm*v.bRe;
w.aRe=wARe; w.aIm=wAIm; w.bRe=wBRe; w.bIm=wBIm;
} else {
w.aRe = m.aRe*v.aRe-m.aIm*v.aIm + m.bRe*v.bRe-m.bIm*v.bIm;
w.aIm = m.aRe*v.aIm+m.aIm*v.aRe + m.bRe*v.bIm+m.bIm*v.bRe;
w.bRe = m.cRe*v.aRe-m.cIm*v.aIm + m.dRe*v.bRe-m.dIm*v.bIm;
w.bIm = m.cRe*v.aIm+m.cIm*v.aRe + m.dRe*v.bIm+m.dIm*v.bRe;
}
}
}
|
IbexOmega/CrazyCanvas
|
CrazyCanvas/Include/ECS/Systems/Player/WeaponSystem.h
|
#pragma once
#include "ECS/System.h"
#include "ECS/Components/Player/ProjectileComponent.h"
#include "ECS/Components/Player/WeaponComponent.h"
#include "Game/ECS/Components/Team/TeamComponent.h"
#include "ECS/Components/Multiplayer/PacketComponent.h"
#include "Game/ECS/Components/Rendering/ParticleEmitter.h"
#include "Game/ECS/Components/Rendering/MeshComponent.h"
#include "Game/ECS/Components/Rendering/AnimationComponent.h"
#include "Math/Math.h"
#include "Multiplayer/Packet/PacketPlayerAction.h"
#include "Multiplayer/Packet/PacketPlayerActionResponse.h"
#include "Containers/TUniquePtr.h"
namespace LambdaEngine
{
struct EntityCollisionInfo;
}
/*
* WeaponProperties
*/
struct WeaponProperties
{
float32 FireRate = 6.0f;
int32 AmmoCapacity = 50;
EAmmoType AmmoType = EAmmoType::AMMO_TYPE_PAINT;
};
inline LambdaEngine::TArray<LambdaEngine::ComponentAccess> GetFireProjectileComponentAccesses()
{
using namespace LambdaEngine;
return
{
{ RW, PositionComponent::Type() },
{ RW, ScaleComponent::Type()},
{ RW, RotationComponent::Type() },
{ RW, VelocityComponent::Type()},
{ R, OffsetComponent::Type()},
{ RW, WeaponComponent::Type()},
{ RW, AnimationAttachedComponent::Type()},
{ RW, TeamComponent::Type() },
{ RW, ProjectileComponent::Type()},
{ RW, DynamicCollisionComponent::Type() },
{ RW, MeshComponent::Type() },
};
}
/*
* WeaponSystem
*/
class WeaponSystem : public LambdaEngine::System
{
public:
WeaponSystem() = default;
~WeaponSystem() = default;
virtual void FixedTick(LambdaEngine::Timestamp deltaTime) = 0;
// Empty tick
virtual void Tick(LambdaEngine::Timestamp deltaTime) override
{
UNREFERENCED_VARIABLE(deltaTime);
}
virtual void Fire(LambdaEngine::Entity weaponEntity, WeaponComponent& weaponComponent, EAmmoType ammoType, const glm::vec3& position, const glm::vec3& velocity, uint8 playerTeam, uint32 angle);
void CalculateWeaponFireProperties(LambdaEngine::Entity weaponEntity, glm::vec3& position, glm::vec3& velocity, uint8& playerTeam);
public:
static bool Init();
static void Release();
FORCEINLINE static WeaponSystem& GetInstance()
{
VALIDATE(s_Instance != nullptr);
return *s_Instance;
}
protected:
virtual bool InitInternal() = 0;
void CreateBaseSystemRegistration(LambdaEngine::SystemRegistration& systemReg);
void UpdateWeapon(WeaponComponent& weaponComponent, float32 dt);
void StartReload(WeaponComponent& weaponComponent, PacketComponent<PacketPlayerAction>& packets);
void AbortReload(WeaponComponent& weaponComponent);
void OnProjectileHit(const LambdaEngine::EntityCollisionInfo& collisionInfo0, const LambdaEngine::EntityCollisionInfo& collisionInfo1);
glm::vec3 CalculateZeroingDirection(
const glm::vec3& weaponPos,
const glm::vec3& playerPos,
const glm::quat& playerDirection,
float32 zeroingDistance);
protected:
LambdaEngine::IDVector m_WeaponEntities;
private:
static LambdaEngine::TUniquePtr<WeaponSystem> s_Instance;
private:
float m_ZeroDist = 8.0f;
float m_YAngle = 5.0f;
};
|
greensoftwarelab/PyAnaDroid
|
anadroid/testing_framework/work/MonkeyRunnerWorkUnit.py
|
from anadroid.testing_framework.work.WorkUnit import WorkUnit
from anadroid.utils.Utils import execute_shell_command
RUNNER_OPTIONS = {
'plugin'
}
def convert_arg(key,val):
if key in RUNNER_OPTIONS:
return "-" + key + " " + val
else:
return "-" + key + " " + val
class MonkeyRunnerWorkUnit(WorkUnit):
"""extends WorkUnit functionality to adapt it to monkeyrunner executions."""
def __init__(self, bin_cmd):
super(MonkeyRunnerWorkUnit, self).__init__(bin_cmd)
def execute(self, package_name=None, *args, **kwargs):
self.command = (self.command + " " + package_name) if package_name is not None else self.command
for k, v in kwargs.items():
self.command += " " + convert_arg(k, v)
for v in args:
self.command += " " + v
print("executing command: " + self.command)
execute_shell_command(self.command).validate(("Error running command"))
def config(self, filepath=None, **kwargs):
cmd = self.command + " " + filepath if filepath is not None else self.command
for k, v in kwargs.items():
cmd += " " + convert_arg(k, v)
self.command = cmd
|
huangjinping/test111
|
HDJFKJ/HDJFKJ/HDAccessToken.h
|
#import <Foundation/Foundation.h>
@interface HDAccessToken : NSObject
@property (nonatomic, strong) NSString * phone;
@property (nonatomic, strong) NSString * nhAccessToken;
@end
|
ricbartm/homebrew-core
|
Formula/wesnoth.rb
|
<filename>Formula/wesnoth.rb
class Wesnoth < Formula
desc "Single- and multi-player turn-based strategy game"
homepage "https://www.wesnoth.org/"
url "https://downloads.sourceforge.net/project/wesnoth/wesnoth-1.12/wesnoth-1.12.6/wesnoth-1.12.6.tar.bz2"
sha256 "a50f384cead15f68f31cfa1a311e76a12098428702cb674d3521eb169eb92e4e"
revision 7
head "https://github.com/wesnoth/wesnoth.git"
bottle do
sha256 "415c02b6c6ff9664fb11f41ff9a7441356b3fb70eb4efc1d9dd21c3a9de7b370" => :high_sierra
sha256 "d1440a43271ccec672400bd6daefae1c448da134c35d4c282dffa038e934ed33" => :sierra
sha256 "f4de6ae40204fa43e16e0a970e508d7b9869965b06b1170e3a8b1c935f187c9c" => :el_capitan
end
option "with-ccache", "Speeds recompilation, convenient for beta testers"
option "with-debug", "Build with debugging symbols"
depends_on "scons" => :build
depends_on "gettext" => :build
depends_on "ccache" => :optional
depends_on "fribidi"
depends_on "boost"
depends_on "libpng"
depends_on "fontconfig"
depends_on "cairo"
depends_on "pango"
depends_on "sdl"
depends_on "sdl_image" # Must have png support
depends_on "sdl_mixer" # The music is in .ogg format
depends_on "sdl_net"
depends_on "sdl_ttf"
def install
mv "scons/gettext.py", "scons/gettext_tool.py"
inreplace "SConstruct", ", \"gettext\",", ", \"gettext_tool\","
args = %W[prefix=#{prefix} docdir=#{doc} mandir=#{man} fifodir=#{var}/run/wesnothd gettextdir=#{Formula["gettext"].opt_prefix}]
args << "OS_ENV=true"
args << "install"
args << "wesnoth"
args << "wesnothd"
args << "-j#{ENV.make_jobs}"
args << "ccache=true" if build.with? "ccache"
args << "build=debug" if build.with? "debug"
scons *args
end
test do
system bin/"wesnoth", "-p", pkgshare/"data/campaigns/tutorial/", testpath
end
end
|
ESRLLC/datacompliances-fe
|
app/containers/UserDashboard/containers/PackageList/Cart/saga.js
|
<filename>app/containers/UserDashboard/containers/PackageList/Cart/saga.js
import {
take,
takeLatest,
call,
put,
select,
fork,
cancel,
} from 'redux-saga/effects';
import { LOCATION_CHANGE, push } from 'react-router-redux';
import * as types from './constants';
import * as actions from './actions';
import Api from 'utils/apiHelper';
import { makeSelectToken } from 'containers/App/selectors';
function* loadCartDetail() {
const token = localStorage.getItem('token');
yield fork(
Api.get(
'cart/detail',
actions.loadCartDetailSuccess,
actions.loadCartDetailFailure,
token,
),
);
}
function* loadCartInfo() {
const token = localStorage.getItem('token');
yield fork(
Api.get(
'cart',
actions.loadCartInfoSuccess,
actions.loadCartInfoFailure,
token,
),
);
}
function* loadSubscribedPackage() {
const token = localStorage.getItem('token');
yield fork(
Api.get(
'package-subscription/detail',
actions.loadSubscribedPackageSuccess,
actions.loadSubscribedPackageFailure,
token,
),
);
}
function* redirectOnCartSubscribeSuccess() {
const action = yield take(types.CART_CHECKOUT_SUCCESS);
// yield put(push(`/user/dashboard`));
}
function* postCartSubscribeRequest(action) {
const token = localStorage.getItem('token');
const { packages } = action;
const successWatcher = yield fork(redirectOnCartSubscribeSuccess);
yield fork(
Api.post(
`package-subscription`,
actions.cartCheckoutSuccess,
actions.cartCheckoutFailure,
packages,
token,
),
);
yield take([LOCATION_CHANGE, types.CART_CHECKOUT_FAILURE]);
yield cancel(successWatcher);
}
function* redirectOnDeleteCartSuccess() {
const action = yield take(types.REMOVE_CART_SUCCESS);
// yield put(push(`/user/dashboard`));
}
function* removeCartRequest(action) {
const token = localStorage.getItem('token');
const { cart } = action;
const successWatcher = yield fork(redirectOnDeleteCartSuccess);
yield fork(
Api.patch(
`cart`,
actions.removeCartSuccess,
actions.removeCartFailure,
cart,
token,
),
);
yield take([LOCATION_CHANGE, types.REMOVE_CART_FAILURE]);
yield cancel(successWatcher);
}
function* redirectOnKhaltiVerificationSuccess() {
const action = yield take(types.VERIFY_KHALTI_PAYMENT_SECCESS);
// yield put(push(`/user/dashboard/my-cart`));
}
function* khaltiVerificationRequest(action) {
const { data } = action;
const token = localStorage.getItem('token');
const successWatcher = yield fork(redirectOnKhaltiVerificationSuccess);
yield fork(
Api.post(
`cart/khalti-payment`,
actions.verifyKhaltiPaymentSuccess,
actions.verifyKhaltiPaymentFailure,
data,
token,
),
);
yield take([LOCATION_CHANGE, types.VERIFY_KHALTI_PAYMENT_FAILURE]);
yield cancel(successWatcher);
}
export default function* cartWatcher() {
yield takeLatest(types.LOAD_CART_DETAIL_REQUEST, loadCartDetail);
yield takeLatest(types.CART_CHECKOUT_REQUEST, postCartSubscribeRequest);
yield takeLatest(
types.GET_SUBSCRIBED_PACKAGES_REQUEST,
loadSubscribedPackage,
);
yield takeLatest(types.REMOVE_CART_REQUEST, removeCartRequest);
yield takeLatest(types.LOAD_CART_INFO_REQUEST, loadCartInfo);
yield takeLatest(
types.VERIFY_KHALTI_PAYMENT_REQUEST,
khaltiVerificationRequest,
);
}
|
rileybathurst/snowledge
|
src/components/square.js
|
<reponame>rileybathurst/snowledge
import React from 'react';
// click on stuff from react docs
// needs an off as well but this is a start with on
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
};
} // constructor
render() {
return (
<button
className={this.state.value}
onClick={() => this.setState({value: 'X'})}
style={{height: '20px'}}
>
{this.state.value}
</button>
);
} // render
} // Square
export default Square;
|
maallen/mojito
|
webapp/src/main/resources/public/js/stores/ScreenshotViewerStore.js
|
<reponame>maallen/mojito
class ScreenshotViewerStore {
constructor() {
this.setDefaultState();
}
setDefaultState() {
this.show = false;
this.src = null;
this.number = 0;
this.total = 0;
this.branchStatisticScreenshots = [];
this.textUnits = [];
}
open(branchStatisticsScreenshots) {
this.branchStatisticScreenshots = branchStatisticsScreenshots;
this.loadScreenshot(1);
this.show = true;
}
loadScreenshot(number) {
if (this.branchStatisticScreenshots.length > 0) {
this.number = number;
this.total = this.branchStatisticScreenshots.length;
let branchStatisticScreenshot = this.branchStatisticScreenshots[this.number - 1];
this.src = branchStatisticScreenshot.src;
this.textUnits = branchStatisticScreenshot.textUnits;
}
}
close() {
this.setDefaultState();
}
goToPrevious() {
if (this.number > 1) {
this.loadScreenshot(this.number - 1);
}
}
goToNext() {
if (this.number < this.total) {
this.loadScreenshot(this.number + 1);
}
}
}
export default ScreenshotViewerStore;
|
mturlo/op-rabbit
|
core/src/test/scala/com/spingo/op_rabbit/subscriptionSpec.scala
|
<reponame>mturlo/op-rabbit
package com.spingo.op_rabbit
import com.spingo.scoped_fixtures.ScopedFixtures
import com.spingo.op_rabbit.helpers.RabbitTestHelpers
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Try}
class SubscriptionSpec extends AnyFunSpec with Matchers with ScopedFixtures with RabbitTestHelpers {
implicit val executionContext = ExecutionContext.global
val queueName = s"test-queue-rabbit-control"
trait RabbitFixtures {
}
describe("Failed subscription") {
it("propagates the exception via the initialized future") {
implicit val recoveryStrategy = RecoveryStrategy.limitedRedeliver()
new RabbitFixtures {
val s = Subscription.run(rabbitControl) {
import Directives._
channel(qos = 1) {
consume(pqueue("very-queue")) {
ack
}
}
}
val Failure(ex) = Try(await(s.initialized))
ex.getMessage() should include ("no queue 'very-queue' in vhost")
}
}
}
describe("Allocating and releasing channels") {
// it("allocates a channel on subscription, and closes it on shutdown") {
// new RabbitFixtures {
// val channelWatcher = new com.rabbitmq.client.ShutdownListener {
// private val _p = Promise[com.rabbitmq.client.ShutdownSignalException]
// val shutdown = _p.future
// def shutdownCompleted(cause: com.rabbitmq.client.ShutdownSignalException): Unit = {
// _p.success(cause)
// }
// }
// val binding = new Binding {
// val queueName = "test"
// var channel: Option[Channel] = None
// def bind(c: Channel): Unit = {
// channel = Some(c)
// }
// }
// val consumer = new Consumer {
// val name = "test"
// var channels = Seq.empty[Channel]
// var unsubscribes = Seq.empty[Int]
// val shutdownP = Promise[Unit]
// val subscribedP = Promise[Unit]
// var counter = 0
// def props(queueName: String) = Props {
// new Actor {
// def receive = {
// case Consumer.Unsubscribe =>
// unsubscribes = unsubscribes :+ counter
// sender ! true
// case Consumer.Subscribe(channel) =>
// subscribedP.success(Unit)
// channels = channels :+ channel
// counter += 1
// case Consumer.Shutdown =>
// shutdownP.success(Unit)
// context stop self
// }
// }
// }
// }
// val subscription = Subscription(binding, consumer)
// rabbitControl ! subscription
// await(subscription.initialized)
// await(consumer.subscribedP.future)
// binding.channel.nonEmpty should be(true)
// val channel = binding.channel.get
// channel.addShutdownListener(channelWatcher)
// consumer.channels should be (Seq(channel))
// // now test shutdown
// subscription.close()
// await(subscription.closed)
// // It closes the consumer
// await(consumer.shutdownP.future)
// // It closes the channel
// val shutdownReason = await(channelWatcher.shutdown).getReason
// shutdownReason.protocolMethodName should be ("channel.close")
// channel.isOpen should be (false) // close should have closed the channel associated with this subscription
// // Flush out the rest of the stuff
// actorSystem.shutdown()
// actorSystem.awaitTermination(timeout.duration)
// consumer.channels should be (Seq(channel)) // we shouldn't have received another channel after it was closed
// consumer.unsubscribes should be (Seq.empty)
// }
// }
}
}
|
Jeremyyang920/datadog-agent
|
pkg/process/procutil/process_posix_test.go
|
<filename>pkg/process/procutil/process_posix_test.go
// +build linux freebsd openbsd darwin
package procutil
import (
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestPidExists(t *testing.T) {
require.True(t, PidExists(os.Getpid()))
require.False(t, PidExists(0xdeadbeef))
}
|
HPezz/LekaOS
|
drivers/CoreVideo/external/source/st_jpeg_utils.cpp
|
<reponame>HPezz/LekaOS
/**
******************************************************************************
* @file jpeg_utils.c
* @author MCD Application Team
* @version V2.0.0
* @date 3-June-2016
* @brief This driver provides JPEG MCU (Minimum Coded Unit) blocks to RGB and RGB to JPEG MCU conversion functions.
*
* The STM32 HW JPEG decoder/encoder peripheral allows to decode/encode jpeg images.
* In decoding, the STM32 HW JPEG data output are organized in blocks called MCU (Minimum Coded Unit)
* as specified in the jpeg standard.
* In encoding, the STM32 HW JPEG data input must be organized in MCU blocks.
* Depending of the image color space and chrominance sampling, an MCU is generally organized in :
* N luminance (Y) blocks + a Blue chrominance (Cb) block + a Red chrominance (Cr) block.
* Each block size is 8x8 samples.
*
* The STM32 HW JPEG supports 3 possible color space :
* - YCbCr : an MCU is composed of 3 color components : Y , Cb and Cr
* - GrayScale : an MCU is composed of 1 single color component : Y
* - CMYK : an MCU is composed of 4 color components : Cyan, Magenta, Yellow, and Key (blacK)
*
* This utility file should be used on top of the STM32 HAL JPEG driver.
* In decoding, it allows to convert MCU blocks to RGB888 or ARGB8888 pixels stored to a destination
* frame buffer that can be displayed.
* In encoding, it allows to convert RGB888 or ARGB8888 pixels to MCU blocks.
*
* This utility supports following MCU Chroma sampling format and color space :
* - YCbCr 4:2:0 : Each MCU is composed of 4 Y 8x8 blocks + 1 Cb 8x8 block + Cr 8x8 block
* - YCbCr 4:2:2 : Each MCU is composed of 2 Y 8x8 blocks + 1 Cb 8x8 block + Cr 8x8 block
* - YCbCr 4:4:4 : Each MCU is composed of 1 Y 8x8 block + 1 Cb 8x8 block + Cr 8x8 block
* - GrayScale : Each MCU is composed of 1 Y 8x8 block
* - CMYK : Each MCU is composed of 1 Cyan 8x8 block + 1 Magenta 8x8 block + 1 Yellow 8x8 block + 1 Key 8x8
*block.
*
*
* @How to use this driver
*
* - The configuration file "jpeg_utils_conf_template.h" is used to configure this utility
* providing some useful flexibilities.
* This file should be copied to the application folder and modified as follows:
* - Rename it to "jpeg_utils_conf.h".
* - Update the name of the JPEG driver's header file, depending on the EVAL board you are using.
*
* Example if using the STM32F769I-EVAL board :
* - Copy the file "jpeg_utils_conf_template.h" to the application folder and rename it to "jpeg_utils_conf.h"
* - Edit the "jpeg_utils_conf.h" and change lines 51 and 52 as follow :
* #include "stm32f7xx_hal.h"
* #include "stm32f7xx_hal_jpeg.h"
*
* Using this configuration file, user can change the following settings:
* - Use RGB888 or ARGB8888 or RGB565 by setting the constant JPEG_RGB_FORMAT respectively to JPEG_RGB888,
*JPEG_ARGB8888 JPEG_RGB565.
* - Swap RED, and Blue offsets if user needs to change the color order to BGR (instead of RGB) by setting:
* #define JPEG_SWAP_RB 1
* - Enable or disable the decoding post-processing functions (YCbCr to RGB conversion functions) by setting
*the define USE_JPEG_DECODER respectively to 0 or 1.
* - Enable or disable the encoding pre-processing functions (RGB to YCbCr conversion functions) by setting the
*define USE_JPEG_ENCODER respectively to 0 or 1.
*
* * For Decoding:
* - First, function "JPEG_InitColorTables" should be called to initialize the YCbCr to RGB color
* conversion tables. This function needs to be called only one time at the beginning of the
* program whatever the number of jpeg files to be decoded.
*
* - As soon as the JPEG HW peripheral finished parsing the header of the JPEG input file,
* the HAL JPEG callback "HAL_JPEG_InfoReadyCallback" is launched providing the jpeg file
* characteristics found in its header.
* User can then call the utility function "JPEG_GetDecodeColorConvertFunc" with these
* information and retrieve the corresponding color conversion function and number of MCUs.
*
* Then each time an integer number of MCUs are available (from the HW JPEG output), user
* can call the retrieved function to convert these HW JPEG output data to RGB888 or
* ARGB8888 pixel stored to the specified destination buffer.
*
* * For Encoding:
* - First, function "JPEG_InitColorTables" should be called to initialize the YCbCr/RGB color
* conversion tables. This function needs to be called only one time at the beginning of the
* program whatever the number of jpeg files to be encoded or decoded.
*
* - First Use the utility function "JPEG_GetEncodeColorConvertFunc" with the input image informations
* to retrieve the corresponding color conversion function and number of MCUs.
*
* Then each time an RGB input buffer is available, user can call the retrieved function to convert
* RGB data to MCU blocks stored to the specified destination buffer.
*
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "external/st_jpeg_utils.h"
/* Private variables ---------------------------------------------------------*/
JPEG_MCU_RGB_ConvertorTypeDef JPEG_ConvertorParams;
int32_t CR_RED_LUT[256]; // Cr to Red color conversion Look Up Table
int32_t CB_BLUE_LUT[256]; // Cb to Blue color conversion Look Up Table
int32_t CR_GREEN_LUT[256]; // Cr to Green color conversion Look Up Table
int32_t CB_GREEN_LUT[256]; // Cb to Green color conversion Look Up Table
/* color clamp table : used for range limitting */
const uint8_t CLAMP_LUT[] = {
/* clamp range 0xffffffff to 0xffffff00 */
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
/* clamp range 0x00 to 0xff */
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0a,
0x0b,
0x0c,
0x0d,
0x0e,
0x0f,
0x10,
0x11,
0x12,
0x13,
0x14,
0x15,
0x16,
0x17,
0x18,
0x19,
0x1a,
0x1b,
0x1c,
0x1d,
0x1e,
0x1f,
0x20,
0x21,
0x22,
0x23,
0x24,
0x25,
0x26,
0x27,
0x28,
0x29,
0x2a,
0x2b,
0x2c,
0x2d,
0x2e,
0x2f,
0x30,
0x31,
0x32,
0x33,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x3a,
0x3b,
0x3c,
0x3d,
0x3e,
0x3f,
0x40,
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4a,
0x4b,
0x4c,
0x4d,
0x4e,
0x4f,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5a,
0x5b,
0x5c,
0x5d,
0x5e,
0x5f,
0x60,
0x61,
0x62,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6a,
0x6b,
0x6c,
0x6d,
0x6e,
0x6f,
0x70,
0x71,
0x72,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7a,
0x7b,
0x7c,
0x7d,
0x7e,
0x7f,
0x80,
0x81,
0x82,
0x83,
0x84,
0x85,
0x86,
0x87,
0x88,
0x89,
0x8a,
0x8b,
0x8c,
0x8d,
0x8e,
0x8f,
0x90,
0x91,
0x92,
0x93,
0x94,
0x95,
0x96,
0x97,
0x98,
0x99,
0x9a,
0x9b,
0x9c,
0x9d,
0x9e,
0x9f,
0xa0,
0xa1,
0xa2,
0xa3,
0xa4,
0xa5,
0xa6,
0xa7,
0xa8,
0xa9,
0xaa,
0xab,
0xac,
0xad,
0xae,
0xaf,
0xb0,
0xb1,
0xb2,
0xb3,
0xb4,
0xb5,
0xb6,
0xb7,
0xb8,
0xb9,
0xba,
0xbb,
0xbc,
0xbd,
0xbe,
0xbf,
0xc0,
0xc1,
0xc2,
0xc3,
0xc4,
0xc5,
0xc6,
0xc7,
0xc8,
0xc9,
0xca,
0xcb,
0xcc,
0xcd,
0xce,
0xcf,
0xd0,
0xd1,
0xd2,
0xd3,
0xd4,
0xd5,
0xd6,
0xd7,
0xd8,
0xd9,
0xda,
0xdb,
0xdc,
0xdd,
0xde,
0xdf,
0xe0,
0xe1,
0xe2,
0xe3,
0xe4,
0xe5,
0xe6,
0xe7,
0xe8,
0xe9,
0xea,
0xeb,
0xec,
0xed,
0xee,
0xef,
0xf0,
0xf1,
0xf2,
0xf3,
0xf4,
0xf5,
0xf6,
0xf7,
0xf8,
0xf9,
0xfa,
0xfb,
0xfc,
0xfd,
0xfe,
0xff,
/* clamp range 0x100 to 0x1ff */
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
};
/**
* @brief Convert YCbCr 4:2:0 blocks to RGB pixels
* @param pInBuffer : pointer to input YCbCr blocks buffer.
* @param pOutBuffer : pointer to output RGB888/ARGB8888 frame buffer.
* @param BlockIndex : index of the input buffer first block in the final image.
* @param DataCount : number of bytes in the input buffer .
* @param ConvertedDataCount : number of converted bytes from input buffer.
* @retval Number of blcoks converted from YCbCr to RGB
*/
uint32_t JPEG_MCU_YCbCr420_ARGB_ConvertBlocks(uint8_t *pInBuffer, uint8_t *pOutBuffer, uint32_t BlockIndex,
uint32_t DataCount, uint32_t *ConvertedDataCount)
{
uint32_t numberMCU;
uint32_t i, j, k, currentMCU, xRef, yRef;
uint32_t refline;
int32_t ycomp, crcomp, cbcomp;
int32_t c_red, c_blue, c_green;
uint8_t *pOutAddr, *pOutAddr2;
uint8_t *pChrom, *pLum;
numberMCU = DataCount / YCBCR_420_BLOCK_SIZE;
currentMCU = BlockIndex;
while (currentMCU < (numberMCU + BlockIndex)) {
xRef = ((currentMCU * 16) / JPEG_ConvertorParams.WidthExtend) * 16;
yRef = ((currentMCU * 16) % JPEG_ConvertorParams.WidthExtend);
refline = JPEG_ConvertorParams.ScaledWidth * xRef + (JPEG_BYTES_PER_PIXEL * yRef);
currentMCU++;
pChrom = pInBuffer + 256; /* pChroma = pInBuffer + 4*64 */
pLum = pInBuffer;
for (i = 0; i < 16; i += 2) {
if (i == 8) {
pLum = pInBuffer + 128;
}
if (refline < JPEG_ConvertorParams.ImageSize_Bytes) {
pOutAddr = pOutBuffer + refline;
pOutAddr2 = pOutAddr + JPEG_ConvertorParams.ScaledWidth;
for (k = 0; k < 2; k++) {
for (j = 0; j < 8; j += 2) {
cbcomp = (int32_t)(*(pChrom));
c_blue = (int32_t)(*(CB_BLUE_LUT + cbcomp));
crcomp = (int32_t)(*(pChrom + 64));
c_red = (int32_t)(*(CR_RED_LUT + crcomp));
c_green = ((int32_t)(*(CR_GREEN_LUT + crcomp)) + (int32_t)(*(CB_GREEN_LUT + cbcomp))) >> 16;
#if (JPEG_RGB_FORMAT == JPEG_ARGB8888)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint32_t *)pOutAddr = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
*((__IO uint32_t *)(pOutAddr + 4)) = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 8));
*(__IO uint32_t *)pOutAddr2 = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 8 + 1));
*((__IO uint32_t *)(pOutAddr2 + 4)) = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
#elif (JPEG_RGB_FORMAT == JPEG_RGB888)
ycomp = (int32_t)(*(pLum + j));
pOutAddr[JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr[JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr[JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
pOutAddr[3 + JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr[3 + JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr[3 + JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
/**********/
ycomp = (int32_t)(*(pLum + j + 8));
pOutAddr2[JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr2[JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr2[JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
/**********/
ycomp = (int32_t)(*(pLum + j + 8 + 1));
pOutAddr2[3 + JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr2[3 + JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr2[3 + JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
#elif (JPEG_RGB_FORMAT == JPEG_RGB565)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint16_t *)pOutAddr = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
*((__IO uint16_t *)(pOutAddr + 2)) = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 8));
*(__IO uint16_t *)pOutAddr2 = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 8 + 1));
*((__IO uint16_t *)(pOutAddr2 + 2)) = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
#endif /* JPEG_RGB_FORMAT */
pOutAddr += JPEG_BYTES_PER_PIXEL * 2;
pOutAddr2 += JPEG_BYTES_PER_PIXEL * 2;
pChrom++;
}
pLum += 64;
}
pLum = pLum - 128 + 16;
refline += 2 * JPEG_ConvertorParams.ScaledWidth;
}
}
pInBuffer += YCBCR_420_BLOCK_SIZE;
}
return numberMCU;
}
/**
* @brief Convert YCbCr 4:2:2 blocks to RGB pixels
* @param pInBuffer : pointer to input YCbCr blocks buffer.
* @param pOutBuffer : pointer to output RGB888/ARGB8888 frame buffer.
* @param BlockIndex : index of the input buffer first block in the final image.
* @param DataCount : number of bytes in the input buffer .
* @param ConvertedDataCount : number of converted bytes from input buffer.
* @retval Number of blcoks converted from YCbCr to RGB
*/
uint32_t JPEG_MCU_YCbCr422_ARGB_ConvertBlocks(uint8_t *pInBuffer, uint8_t *pOutBuffer, uint32_t BlockIndex,
uint32_t DataCount, uint32_t *ConvertedDataCount)
{
uint32_t numberMCU;
uint32_t i, j, k, currentMCU, xRef, yRef;
uint32_t refline;
int32_t ycomp, crcomp, cbcomp;
int32_t c_red, c_blue, c_green;
uint8_t *pOutAddr;
uint8_t *pChrom, *pLum;
numberMCU = DataCount / YCBCR_422_BLOCK_SIZE;
currentMCU = BlockIndex;
while (currentMCU < (numberMCU + BlockIndex)) {
xRef = ((currentMCU * 16) / JPEG_ConvertorParams.WidthExtend) * 8;
yRef = ((currentMCU * 16) % JPEG_ConvertorParams.WidthExtend);
refline = JPEG_ConvertorParams.ScaledWidth * xRef + (JPEG_BYTES_PER_PIXEL * yRef);
currentMCU++;
pChrom = pInBuffer + 128; /* pChroma = pInBuffer + 2*64 */
pLum = pInBuffer;
for (i = 0; i < 8; i++) {
if (refline < JPEG_ConvertorParams.ImageSize_Bytes) {
pOutAddr = pOutBuffer + refline;
for (k = 0; k < 2; k++) {
for (j = 0; j < 8; j += 2) {
cbcomp = (int32_t)(*(pChrom));
c_blue = (int32_t)(*(CB_BLUE_LUT + cbcomp));
crcomp = (int32_t)(*(pChrom + 64));
c_red = (int32_t)(*(CR_RED_LUT + crcomp));
c_green = ((int32_t)(*(CR_GREEN_LUT + crcomp)) + (int32_t)(*(CB_GREEN_LUT + cbcomp))) >> 16;
#if (JPEG_RGB_FORMAT == JPEG_ARGB8888)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint32_t *)pOutAddr = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
*((__IO uint32_t *)(pOutAddr + 4)) = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
#elif (JPEG_RGB_FORMAT == JPEG_RGB888)
ycomp = (int32_t)(*(pLum + j));
pOutAddr[JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr[JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr[JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
pOutAddr[3 + JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr[3 + JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr[3 + JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
#elif (JPEG_RGB_FORMAT == JPEG_RGB565)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint16_t *)pOutAddr = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
/**********/
ycomp = (int32_t)(*(pLum + j + 1));
*((__IO uint16_t *)(pOutAddr + 2)) = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
#endif /* JPEG_RGB_FORMAT*/
pOutAddr += JPEG_BYTES_PER_PIXEL * 2;
pChrom++;
}
pLum += 64;
}
pLum = pLum - 128 + 8;
refline += JPEG_ConvertorParams.ScaledWidth;
}
}
pInBuffer += YCBCR_422_BLOCK_SIZE;
}
return numberMCU;
}
/**
* @brief Convert YCbCr 4:4:4 blocks to RGB pixels
* @param pInBuffer : pointer to input YCbCr blocks buffer.
* @param pOutBuffer : pointer to output RGB888/ARGB8888 frame buffer.
* @param BlockIndex : index of the input buffer first block in the final image.
* @param DataCount : number of bytes in the input buffer .
* @param ConvertedDataCount : number of converted bytes from input buffer.
* @retval Number of blcoks converted from YCbCr to RGB
*/
uint32_t JPEG_MCU_YCbCr444_ARGB_ConvertBlocks(uint8_t *pInBuffer, uint8_t *pOutBuffer, uint32_t BlockIndex,
uint32_t DataCount, uint32_t *ConvertedDataCount)
{
uint32_t numberMCU;
uint32_t i, j, currentMCU, xRef, yRef;
uint32_t refline;
int32_t ycomp, crcomp, cbcomp;
int32_t c_red, c_blue, c_green;
uint8_t *pOutAddr;
uint8_t *pChrom, *pLum;
numberMCU = DataCount / YCBCR_444_BLOCK_SIZE;
currentMCU = BlockIndex;
while (currentMCU < (numberMCU + BlockIndex)) {
xRef = ((currentMCU * 8) / JPEG_ConvertorParams.WidthExtend) * 8;
yRef = ((currentMCU * 8) % JPEG_ConvertorParams.WidthExtend);
refline = JPEG_ConvertorParams.ScaledWidth * xRef + (JPEG_BYTES_PER_PIXEL * yRef);
currentMCU++;
pChrom = pInBuffer + 64; /* pChroma = pInBuffer + 4*64 */
pLum = pInBuffer;
for (i = 0; i < 8; i++) {
if (refline < JPEG_ConvertorParams.ImageSize_Bytes) {
pOutAddr = pOutBuffer + refline;
for (j = 0; j < 8; j++) {
cbcomp = (int32_t)(*pChrom);
c_blue = (int32_t)(*(CB_BLUE_LUT + cbcomp));
crcomp = (int32_t)(*(pChrom + 64));
c_red = (int32_t)(*(CR_RED_LUT + crcomp));
c_green = ((int32_t)(*(CR_GREEN_LUT + crcomp)) + (int32_t)(*(CB_GREEN_LUT + cbcomp))) >> 16;
#if (JPEG_RGB_FORMAT == JPEG_ARGB8888)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint32_t *)pOutAddr = (CLAMP(ycomp + c_red) << JPEG_RED_OFFSET) |
(CLAMP(ycomp + c_green) << JPEG_GREEN_OFFSET) |
(CLAMP(ycomp + c_blue) << JPEG_BLUE_OFFSET);
#elif (JPEG_RGB_FORMAT == JPEG_RGB888)
ycomp = (int32_t)(*(pLum + j));
pOutAddr[JPEG_RED_OFFSET / 8] = CLAMP(ycomp + c_red);
pOutAddr[JPEG_GREEN_OFFSET / 8] = CLAMP(ycomp + c_green);
pOutAddr[JPEG_BLUE_OFFSET / 8] = CLAMP(ycomp + c_blue);
#elif (JPEG_RGB_FORMAT == JPEG_RGB565)
ycomp = (int32_t)(*(pLum + j));
*(__IO uint16_t *)pOutAddr = ((CLAMP(ycomp + c_red) >> 3) << JPEG_RED_OFFSET) |
((CLAMP(ycomp + c_green) >> 2) << JPEG_GREEN_OFFSET) |
((CLAMP(ycomp + c_blue) >> 3) << JPEG_BLUE_OFFSET);
#endif /* JPEG_RGB_FORMAT */
pOutAddr += JPEG_BYTES_PER_PIXEL;
pChrom++;
}
pLum += 8;
refline += JPEG_ConvertorParams.ScaledWidth;
}
}
pInBuffer += YCBCR_444_BLOCK_SIZE;
}
return numberMCU;
}
/**
* @brief Convert Y Gray blocks to RGB pixels
* @param pInBuffer : pointer to input Luminance Y blocks buffer.
* @param pOutBuffer : pointer to output RGB888/ARGB8888 frame buffer.
* @param BlockIndex : index of the input buffer first block in the final image.
* @param DataCount : number of bytes in the input buffer .
* @param ConvertedDataCount : number of converted bytes from input buffer.
* @retval Number of blcoks converted from YCbCr to RGB
*/
uint32_t JPEG_MCU_Gray_ARGB_ConvertBlocks(uint8_t *pInBuffer, uint8_t *pOutBuffer, uint32_t BlockIndex,
uint32_t DataCount, uint32_t *ConvertedDataCount)
{
uint32_t numberMCU;
uint32_t currentMCU, xRef, yRef;
uint32_t refline;
uint32_t i, j, ySample;
uint8_t *pOutAddr, *pLum;
numberMCU = DataCount / GRAY_444_BLOCK_SIZE;
currentMCU = BlockIndex;
while (currentMCU < (numberMCU + BlockIndex)) {
xRef = ((currentMCU * 8) / JPEG_ConvertorParams.WidthExtend) * 8;
yRef = ((currentMCU * 8) % JPEG_ConvertorParams.WidthExtend);
refline = JPEG_ConvertorParams.ScaledWidth * xRef + (JPEG_BYTES_PER_PIXEL * yRef);
currentMCU++;
pLum = pInBuffer;
for (i = 0; i < 8; i++) {
pOutAddr = pOutBuffer + refline;
if (refline < JPEG_ConvertorParams.ImageSize_Bytes) {
for (j = 0; j < 8; j++) {
ySample = (uint32_t)(*pLum);
#if (JPEG_RGB_FORMAT == JPEG_ARGB8888)
*(__IO uint32_t *)pOutAddr = ySample | (ySample << 8) | (ySample << 16);
#elif (JPEG_RGB_FORMAT == JPEG_RGB888)
pOutAddr[0] = ySample;
pOutAddr[1] = ySample;
pOutAddr[2] = ySample;
#elif (JPEG_RGB_FORMAT == JPEG_RGB565)
*(__IO uint16_t *)pOutAddr = ((ySample >> 3) << 11) | ((ySample >> 2) << 5) | (ySample >> 3);
#endif /* JPEG_RGB_FORMAT */
pOutAddr += JPEG_BYTES_PER_PIXEL;
pLum++;
}
refline += JPEG_ConvertorParams.ScaledWidth;
}
}
pInBuffer += GRAY_444_BLOCK_SIZE;
}
return numberMCU;
}
/**
* @brief Convert CMYK blocks to RGB pixels
* @param pInBuffer : pointer to input CMYK blocks buffer.
* @param pOutBuffer : pointer to output RGB888/ARGB8888 frame buffer.
* @param BlockIndex : index of the input buffer first block in the final image.
* @param DataCount : number of bytes in the input buffer .
* @param ConvertedDataCount : number of converted bytes from input buffer.
* @retval Number of blcoks converted from CMYK to RGB
*/
uint32_t JPEG_MCU_YCCK_ARGB_ConvertBlocks(uint8_t *pInBuffer, uint8_t *pOutBuffer, uint32_t BlockIndex,
uint32_t DataCount, uint32_t *ConvertedDataCount)
{
uint32_t numberMCU;
uint32_t i, j, currentMCU, xRef, yRef;
uint32_t refline;
int32_t color_k;
int32_t c_red, c_blue, c_green;
uint8_t *pOutAddr, *pChrom;
numberMCU = DataCount / CMYK_444_BLOCK_SIZE;
currentMCU = BlockIndex;
while (currentMCU < (numberMCU + BlockIndex)) {
xRef = ((currentMCU * 8) / JPEG_ConvertorParams.WidthExtend) * 8;
yRef = ((currentMCU * 8) % JPEG_ConvertorParams.WidthExtend);
refline = JPEG_ConvertorParams.ScaledWidth * xRef + (JPEG_BYTES_PER_PIXEL * yRef);
currentMCU++;
pChrom = pInBuffer;
for (i = 0; i < 8; i++) {
if (refline < JPEG_ConvertorParams.ImageSize_Bytes) {
pOutAddr = pOutBuffer + refline;
for (j = 0; j < 8; j++) {
color_k = (int32_t)(*(pChrom + 192));
c_red = (color_k * ((int32_t)(*pChrom))) / 255;
c_green = (color_k * (int32_t)(*(pChrom + 64))) / 255;
c_blue = (color_k * (int32_t)(*(pChrom + 128))) / 255;
#if (JPEG_RGB_FORMAT == JPEG_ARGB8888)
*(__IO uint32_t *)pOutAddr =
(c_red << JPEG_RED_OFFSET) | (c_green << JPEG_GREEN_OFFSET) | (c_blue << JPEG_BLUE_OFFSET);
#elif (JPEG_RGB_FORMAT == JPEG_RGB888)
pOutAddr[JPEG_RED_OFFSET / 8] = c_red;
pOutAddr[JPEG_GREEN_OFFSET / 8] = c_green;
pOutAddr[JPEG_BLUE_OFFSET / 8] = c_blue;
#elif (JPEG_RGB_FORMAT == JPEG_RGB565)
*(__IO uint16_t *)pOutAddr = ((c_red >> 3) << JPEG_RED_OFFSET) |
((c_green >> 2) << JPEG_GREEN_OFFSET) |
((c_blue >> 3) << JPEG_BLUE_OFFSET);
#endif /* JPEG_RGB_FORMAT */
pOutAddr += JPEG_BYTES_PER_PIXEL;
pChrom++;
}
refline += JPEG_ConvertorParams.ScaledWidth;
}
}
pInBuffer += CMYK_444_BLOCK_SIZE;
}
return numberMCU;
}
/**
* @brief Retrive Decoding YCbCr to RGB color conversion function and block number
* @param pJpegInfo : JPEG_ConfTypeDef that contains the JPEG image informations.
* These info are available in the HAL callback "HAL_JPEG_InfoReadyCallback".
* @param pFunction : pointer to JPEG_YCbCrToRGB_Convert_Function , used to retrive the color conversion function
* depending of the jpeg image color space and chroma sampling info.
* @param ImageNbMCUs : pointer to uint32_t, used to retrive the total number of MCU blocks in the jpeg image.
* @retval HAL status : HAL_OK or HAL_ERROR.
*/
HAL_StatusTypeDef JPEG_GetDecodeColorConvertFunc(JPEG_ConfTypeDef *pJpegInfo,
JPEG_YCbCrToRGB_Convert_Function *pFunction, uint32_t *ImageNbMCUs)
{
uint32_t hMCU, vMCU;
JPEG_ConvertorParams.ColorSpace = pJpegInfo->ColorSpace;
JPEG_ConvertorParams.ImageWidth = pJpegInfo->ImageWidth;
JPEG_ConvertorParams.ImageHeight = pJpegInfo->ImageHeight;
JPEG_ConvertorParams.ImageSize_Bytes = pJpegInfo->ImageWidth * pJpegInfo->ImageHeight * JPEG_BYTES_PER_PIXEL;
JPEG_ConvertorParams.ChromaSubsampling = pJpegInfo->ChromaSubsampling;
if (JPEG_ConvertorParams.ColorSpace == JPEG_YCBCR_COLORSPACE) {
if (JPEG_ConvertorParams.ChromaSubsampling == JPEG_420_SUBSAMPLING) {
*pFunction = JPEG_MCU_YCbCr420_ARGB_ConvertBlocks;
JPEG_ConvertorParams.LineOffset = JPEG_ConvertorParams.ImageWidth % 16;
if (JPEG_ConvertorParams.LineOffset != 0) {
JPEG_ConvertorParams.LineOffset = 16 - JPEG_ConvertorParams.LineOffset;
}
JPEG_ConvertorParams.H_factor = 16;
JPEG_ConvertorParams.V_factor = 16;
} else if (JPEG_ConvertorParams.ChromaSubsampling == JPEG_422_SUBSAMPLING) {
*pFunction = JPEG_MCU_YCbCr422_ARGB_ConvertBlocks;
JPEG_ConvertorParams.LineOffset = JPEG_ConvertorParams.ImageWidth % 16;
if (JPEG_ConvertorParams.LineOffset != 0) {
JPEG_ConvertorParams.LineOffset = 16 - JPEG_ConvertorParams.LineOffset;
}
JPEG_ConvertorParams.H_factor = 16;
JPEG_ConvertorParams.V_factor = 8;
} else /*4:4:4*/
{
*pFunction = JPEG_MCU_YCbCr444_ARGB_ConvertBlocks;
JPEG_ConvertorParams.LineOffset = JPEG_ConvertorParams.ImageWidth % 8;
if (JPEG_ConvertorParams.LineOffset != 0) {
JPEG_ConvertorParams.LineOffset = 8 - JPEG_ConvertorParams.LineOffset;
}
JPEG_ConvertorParams.H_factor = 8;
JPEG_ConvertorParams.V_factor = 8;
}
} else if (JPEG_ConvertorParams.ColorSpace == JPEG_GRAYSCALE_COLORSPACE) {
*pFunction = JPEG_MCU_Gray_ARGB_ConvertBlocks;
JPEG_ConvertorParams.LineOffset = JPEG_ConvertorParams.ImageWidth % 8;
if (JPEG_ConvertorParams.LineOffset != 0) {
JPEG_ConvertorParams.LineOffset = 8 - JPEG_ConvertorParams.LineOffset;
}
JPEG_ConvertorParams.H_factor = 8;
JPEG_ConvertorParams.V_factor = 8;
} else if (JPEG_ConvertorParams.ColorSpace == JPEG_CMYK_COLORSPACE) {
*pFunction = JPEG_MCU_YCCK_ARGB_ConvertBlocks;
JPEG_ConvertorParams.LineOffset = JPEG_ConvertorParams.ImageWidth % 8;
if (JPEG_ConvertorParams.LineOffset != 0) {
JPEG_ConvertorParams.LineOffset = 8 - JPEG_ConvertorParams.LineOffset;
}
JPEG_ConvertorParams.H_factor = 8;
JPEG_ConvertorParams.V_factor = 8;
} else {
return HAL_ERROR; /* Color space Not supported*/
}
JPEG_ConvertorParams.WidthExtend = JPEG_ConvertorParams.ImageWidth + JPEG_ConvertorParams.LineOffset;
JPEG_ConvertorParams.ScaledWidth = JPEG_BYTES_PER_PIXEL * JPEG_ConvertorParams.ImageWidth;
hMCU = (JPEG_ConvertorParams.ImageWidth / JPEG_ConvertorParams.H_factor);
if ((JPEG_ConvertorParams.ImageWidth % JPEG_ConvertorParams.H_factor) != 0) {
hMCU++; /*+1 for horizenatl incomplete MCU */
}
vMCU = (JPEG_ConvertorParams.ImageHeight / JPEG_ConvertorParams.V_factor);
if ((JPEG_ConvertorParams.ImageHeight % JPEG_ConvertorParams.V_factor) != 0) {
vMCU++; /*+1 for vertical incomplete MCU */
}
JPEG_ConvertorParams.MCU_Total_Nb = (hMCU * vMCU);
*ImageNbMCUs = JPEG_ConvertorParams.MCU_Total_Nb;
return HAL_OK;
}
/**
* @brief Initializes the YCbCr -> RGB colors conversion Look Up Tables
* @param None
* @retval None
*/
void JPEG_InitPostProcColorTables(void)
{
int32_t index, i;
for (i = 0; i <= 255; i++) {
index = (i * 2) - 256;
CR_RED_LUT[i] = ((((int32_t)((1.40200 / 2) * (1L << 16))) * index) + ((int32_t)1 << (16 - 1))) >> 16;
CB_BLUE_LUT[i] = ((((int32_t)((1.77200 / 2) * (1L << 16))) * index) + ((int32_t)1 << (16 - 1))) >> 16;
CR_GREEN_LUT[i] = (-((int32_t)((0.71414 / 2) * (1L << 16)))) * index;
CB_GREEN_LUT[i] = (-((int32_t)((0.34414 / 2) * (1L << 16)))) * index;
}
}
/**
* @brief Initializes the colors conversion Look Up Tables
* @param None
* @retval None
*/
void JPEG_InitColorTables(void)
{
JPEG_InitPostProcColorTables();
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
danielsdeleo/basset
|
lib/basset/feature_extractor.rb
|
<filename>lib/basset/feature_extractor.rb
require File.join(File.dirname(__FILE__), "yaml_serialization")
module Basset
# Extracts features from a document. On initialization it expects the set of features that
# are to be extracted from documents. The extracted features will just be numbered in
# ascending order. This makes it easy to output feature sets for libraries like svmlight.
class FeatureExtractor
include YamlSerialization
# the constructor takes an array of feature names. These are the features that will be
# extracted from documents. All others will be ignored.
def initialize(feature_names)
@feature_names = {}
feature_names.each_with_index {|feature_name, index| @feature_names[feature_name] = index + 1}
end
def number_of_features
@feature_names.size
end
# returns an array of features, but with their names replaced with an integer identifier.
# They should be sorted in ascending identifier order. This is a generic representation that works
# well with other machine learning packages like svm_light.
def extract_numbered(document)
numbered_features = extract(document).collect do |feature|
Feature.new(@feature_names[feature.name], feature.value)
end
numbered_features.sort
end
# just returns the features from the document that the extractor is interested in
def extract(document)
document.vector_of_features.find_all do |feature|
@feature_names[feature.name]
end
end
# def extract_with_duplicate_removal(document)
# features = extract(document)
# # # now remove the unigrams that dupe bigram features
# # # first grab an array of the bigram ones
# # bigram_features = []
# # sorted_features.each {|feature| bigram_features << feature if feature.name =~ /.*_AND_.*/}
# # # now remove all the ones that have a match in the bigram features
# # sorted_features.each_with_index do |feature, index|
# # sorted_features.delete_at(index) if (feature.name !~ /_AND_/ and bigram_features.detect {|bf| bf.name =~ /^#{feature.name}_|_#{feature.name}$/})
# # end
# end
end
end
|
JustAWaifuHunter/Yoko
|
src/structures/Message.js
|
<gh_stars>1-10
const { MessageTypes } = require("../constants/Constants");
const { MESSAGE_LINK } = require("../constants/EndPoints");
const Base = require("./Base");
const MessageEmbed = require("./embed/MessageEmbed");
const User = require("./User");
module.exports = class Message extends Base {
guild = null;
constructor(data, client) {
super(data.id, client);
this.type = MessageTypes[data.type];
this.timestamp = Date.parse(data.timestamp);
this.channel = this.client.channels.cache.get(data.channel_id);
this.guildID = data.guild_id;
this.tts = data.tts;
this.content = data.content;
this.author =
this.client.users.cache.get(data.author.id) ?? new User(data.author);
if (this.guildID) {
this.guild = this.client.guilds.cache.get(this.guildID);
}
if (data.member && this.guild) {
this.member = this.guild.members.cache.get(data.member.id);
}
if (data.embeds && data.embeds.length) {
this.embeds = data.embeds.map((embed) => new MessageEmbed(embed));
}
}
get link() {
if (!this.channel) return null;
return MESSAGE_LINK(this.guildID ?? "@me", this.channel.id, this.id);
}
};
|
1whatleytay/kara
|
src/interfaces/interfaces.cpp
|
<gh_stars>1-10
#include <interfaces/interfaces.h>
#include <parser/function.h>
#include <parser/literals.h>
#include <parser/type.h>
#include <parser/variable.h>
#include <utils/expression.h>
#include <fmt/printf.h>
using namespace kara;
std::string toTypeString(const hermes::Node *node) {
switch (node->is<parser::Kind>()) {
case parser::Kind::NamedTypename:
return node->as<parser::NamedTypename>()->name;
case parser::Kind::PrimitiveTypename:
switch (node->as<parser::PrimitiveTypename>()->type) {
case utils::PrimitiveType::Any:
return "any";
case utils::PrimitiveType::Null:
return "null";
case utils::PrimitiveType::Nothing:
return "nothing";
case utils::PrimitiveType::Bool:
return "bool";
case utils::PrimitiveType::Byte:
return "byte";
case utils::PrimitiveType::Short:
return "short";
case utils::PrimitiveType::Int:
return "int";
case utils::PrimitiveType::Long:
return "long";
case utils::PrimitiveType::UByte:
return "ubyte";
case utils::PrimitiveType::UShort:
return "ushort";
case utils::PrimitiveType::UInt:
return "uint";
case utils::PrimitiveType::ULong:
return "ulong";
case utils::PrimitiveType::Float:
return "float";
case utils::PrimitiveType::Double:
return "double";
default:
throw;
}
case parser::Kind::OptionalTypename: {
auto e = node->as<parser::OptionalTypename>();
return fmt::format("{}{}", e->bubbles ? "!" : "?", toTypeString(e->body()));
}
case parser::Kind::ReferenceTypename: {
auto e = node->as<parser::ReferenceTypename>();
return fmt::format("&{}{}", e->isMutable ? "var " : "", toTypeString(e->body()));
}
case parser::Kind::ArrayTypename: {
auto e = node->as<parser::ArrayTypename>();
switch (e->type) {
case utils::ArrayKind::VariableSize:
return fmt::format("[{}]", toTypeString(e->body()));
case utils::ArrayKind::FixedSize:
return fmt::format("[{}:{}]", toTypeString(e->body()), std::get<uint64_t>(e->fixedSize()->value));
case utils::ArrayKind::Unbounded:
return fmt::format("[{}:]", toTypeString(e->body()));
case utils::ArrayKind::Iterable:
return fmt::format("[{}::]", toTypeString(e->body()));
default:
throw;
}
}
case parser::Kind::FunctionTypename: {
auto e = node->as<parser::FunctionTypename>();
auto parameters = e->parameters();
std::vector<std::string> text(parameters.size());
std::transform(parameters.begin(), parameters.end(), text.begin(), [](const auto &p) {
return toTypeString(p);
});
auto locked = e->isLocked ? " locked" : "";
const char *flags = "";
switch (e->kind) {
case utils::FunctionKind::Pointer:
flags = " ptr";
case utils::FunctionKind::Regular:
break;
default:
throw;
}
return fmt::format("func{}{}({}) {}", locked, flags, fmt::join(text, ", "), toTypeString(e->returnType()));
}
default:
throw;
}
}
bool verify(const hermes::Node *node) {
for (const auto &c : node->children) {
if (c->parent != node)
return false;
verify(c.get());
}
return true;
}
int main(int count, const char **args) {
auto [state, root] = kara::interfaces::header::create(count, args);
assert(verify(root.get()));
for (const auto &e : root->children) {
switch (e->is<parser::Kind>()) {
case parser::Kind::Function: {
auto f = e->as<parser::Function>();
std::vector<std::string> text;
text.reserve(f->parameterCount);
for (size_t a = 0; a < f->parameterCount; a++) {
auto *v = f->children[a]->as<parser::Variable>();
assert(v->hasFixedType);
text.push_back(fmt::format("{} {}", v->name, toTypeString(v->fixedType())));
}
fmt::print("{}({}) {} external\n", f->name, fmt::join(text, ", "), toTypeString(f->fixedType()));
break;
}
case parser::Kind::Variable: {
auto v = e->as<parser::Variable>();
auto toString = [](const parser::Number *node) -> std::string {
return std::visit([](auto x) { return std::to_string(x); }, node->value);
};
assert(!v->hasInitialValue);
fmt::print("{} {} {}{}{}\n", v->isMutable ? "var" : "let", v->name, toTypeString(v->fixedType()),
v->isExternal ? " external" : "",
v->hasConstantValue ? fmt::format(" = {}", toString(v->constantValue())) : "");
break;
}
case parser::Kind::Type: {
auto t = e->as<parser::Type>();
if (t->isAlias) {
fmt::print("type {} = {}\n", t->name, toTypeString(t->alias()));
} else {
std::vector<std::string> elements;
auto fields = t->fields();
elements.reserve(fields.size());
for (auto field : fields) {
elements.push_back(fmt::format(
"{}{} {}", field->isMutable ? "var " : "", field->name, toTypeString(field->fixedType())));
}
fmt::print("type {} {{\n\t{}\n}}\n", t->name, fmt::join(elements, "\n\t"));
}
break;
}
default:
throw;
}
}
}
|
bjuvensjo/misc
|
js/modularization/3-amd/scripts/app.build.js
|
({
appDir: "../",
baseUrl: "scripts",
dir: "../build",
modules: [
{
name: "main"
}
]
})
|
chyanju/autopandas
|
autopandas_v2/generators/ml/networks/ggnn/ops/select.py
|
import collections
import pickle
from typing import Dict
import numpy as np
import tensorflow as tf
from autopandas_v2.generators.ml.networks.ggnn import utils
from autopandas_v2.generators.ml.networks.ggnn.base import BaseSmartGenGGNN
class ModelSelect(BaseSmartGenGGNN):
def process_raw_graph(self, graph):
processed = super().process_raw_graph(graph)
processed['candidates'] = graph['candidates']
processed['selected_one_hot'] = [int(i == graph.get('selected', -1)) for i in graph['candidates']]
return processed
def define_placeholders(self):
super().define_placeholders()
self.placeholders['candidates'] = tf.placeholder(tf.int32, [None], name='candidates')
self.placeholders['candidates_true'] = tf.placeholder(tf.int32, [None], name='candidates_true')
self.placeholders['cand_graph_nodes_list'] = tf.placeholder(tf.int32, [None], name='candidates')
self.placeholders['select_targets'] = tf.placeholder(tf.int64, [None], name='select_targets')
def per_graph_custom_minibatch_iterator(self, graph_num: int, graph: Dict, node_offset: int) -> Dict:
return {
'candidates': np.array(graph['candidates']) + node_offset,
'candidates_true': np.array(graph['candidates']),
'select_targets': np.array(graph['selected_one_hot']),
'cand_graph_nodes_list': np.full([len(graph['candidates'])], fill_value=graph_num)
}
def final_classifier(self):
# By default, a simple MLP with one hidden layer
return utils.MLP(self.params['hidden_size_node'] * 3, 1,
[self.params['hidden_size_final_mlp']],
self.placeholders['out_layer_dropout_keep_prob'])
def compute_candidate_softmax_and_loss(self, cand_logits):
# The following is softmax-ing over the candidates per graph.
# As the number of candidates varies, we can't just use tf.softmax.
# We implement it with the logsumexp trick:
# Step (1): Obtain shift constant as max of the logits
max_per_graph = tf.unsorted_segment_max(
data=cand_logits,
segment_ids=self.placeholders['cand_graph_nodes_list'],
num_segments=self.placeholders['num_graphs_in_batch']
) # Shape [G]
# # Step (2): Distribute max out to the corresponding logits again, and shift scores:
max_per_cand = tf.gather(params=max_per_graph,
indices=self.placeholders['cand_graph_nodes_list'])
cand_logits_shifted = cand_logits - max_per_cand
# # Step (3): Exp, sum up per target, compute exp(score) / exp(sum) as softmax:
scores_exped = tf.exp(cand_logits_shifted)
scores_sum_per_graph = tf.unsorted_segment_sum(
data=scores_exped,
segment_ids=self.placeholders['cand_graph_nodes_list'],
num_segments=self.placeholders['num_graphs_in_batch']
) # Shape [G]
scores_sum_per_cand = tf.gather(
params=scores_sum_per_graph,
indices=self.placeholders['cand_graph_nodes_list']
)
self.ops['softmax_values'] = scores_exped / (scores_sum_per_cand + utils.SMALL_NUMBER)
self.ops['log_softmax_values'] = cand_logits_shifted - tf.log(scores_sum_per_cand + utils.SMALL_NUMBER)
labels = self.placeholders['select_targets']
flat_loss_values = -tf.cast(labels, "float32") * self.ops['log_softmax_values']
losses = tf.unsorted_segment_sum(
data=flat_loss_values,
segment_ids=self.placeholders['cand_graph_nodes_list'],
num_segments=self.placeholders['num_graphs_in_batch']
)
self.ops['loss'] = tf.reduce_mean(losses)
flat_correct_prediction = tf.cast(tf.equal(cand_logits, max_per_cand), "int64") * self.placeholders[
'select_targets']
correct_prediction = tf.unsorted_segment_max(
data=tf.cast(flat_correct_prediction, "float32"),
segment_ids=self.placeholders['cand_graph_nodes_list'],
num_segments=self.placeholders['num_graphs_in_batch']
)
self.ops['accuracy_task'] = tf.reduce_mean(correct_prediction)
def make_model(self, mode):
super().make_model(mode)
with tf.variable_scope("out_layer"):
self.ops['final_classifier'] = self.final_classifier()
candidates_repr = tf.gather(params=self.ops['final_node_representations'],
indices=self.placeholders['candidates'])
candidates_pooled = tf.unsorted_segment_sum(
data=candidates_repr,
segment_ids=self.placeholders['cand_graph_nodes_list'],
num_segments=self.placeholders['num_graphs_in_batch']
)
pooled_representations = self.prepare_pooled_node_representations()
graph_pooled = pooled_representations - candidates_pooled
graph_pooled_copies = tf.gather(params=graph_pooled,
indices=self.placeholders['graph_nodes_list'])
cand_pooled_copies = tf.gather(params=candidates_pooled,
indices=self.placeholders['graph_nodes_list'])
candidates_graph = tf.gather(params=graph_pooled_copies, indices=self.placeholders['candidates'])
candidates_pooled = tf.gather(params=cand_pooled_copies, indices=self.placeholders['candidates'])
candidates_concat = tf.concat([candidates_repr, candidates_graph, candidates_pooled], -1)
candidates_logits = tf.reshape(self.ops['final_classifier'](candidates_concat), [-1])
self.compute_candidate_softmax_and_loss(candidates_logits)
def save_interface(self, path: str):
from autopandas_v2.generators.ml.networks.ggnn.interfaces import ModelSelectInterface
interface = ModelSelectInterface()
with open(path, 'wb') as f:
pickle.dump(interface, f)
def infer(self, raw_graph_data, **kwargs):
graphs = [self.process_raw_graph(g) for g in raw_graph_data]
batch_iterator = utils.ThreadedIterator(self.make_minibatch_iterator(graphs, is_training=False),
max_queue_size=50)
preds = []
for step, batch_data in enumerate(batch_iterator):
batch_data[self.placeholders['out_layer_dropout_keep_prob']] = 1.0
fetch_list = [self.ops['softmax_values'],
self.placeholders['cand_graph_nodes_list'],
self.placeholders['candidates_true']]
result = self.sess.run(fetch_list, feed_dict=batch_data)
groupings = collections.defaultdict(list)
for probs, graph_id, candidate in zip(*result):
groupings[graph_id].append((probs, candidate))
preds += list(groupings.values())
return preds
def init_analysis(self):
super().init_analysis()
self.correct_indices = []
def finish_analysis(self):
result = super().finish_analysis()
top_k = self.params.args.top_k
for k in range(1, top_k + 1):
acc = sum(1 for i in self.correct_indices if i < k) / self.num_graphs
print("Top-{} Accuracy : {}".format(k, acc))
result['Top-{}'.format(k)] = acc
return result
def get_fetch_list(self):
return super().get_fetch_list() + [self.ops['softmax_values'],
self.placeholders['cand_graph_nodes_list'],
self.placeholders['select_targets']]
def analyze_result(self, num_graphs, result):
super().analyze_result(num_graphs, result)
groupings = collections.defaultdict(list)
for probs, graph_id, correct in zip(*result[1:]):
groupings[graph_id].append((probs, correct))
for graph_id, preds in groupings.items():
preds = sorted(preds, key=lambda x: -x[0])
for idx, (prob, correct) in enumerate(preds):
if correct:
self.correct_indices.append(idx)
break
|
178inaba/stripe-go
|
paymentsource/client.go
|
<gh_stars>1-10
//
//
// File generated from our OpenAPI spec
//
//
// Package paymentsource provides the /customers/{customer}/sources APIs
package paymentsource
import (
"fmt"
"net/http"
stripe "github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/form"
)
// Client is used to invoke /customers/{customer}/sources APIs.
type Client struct {
B stripe.Backend
Key string
}
// New creates a new payment source.
func New(params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
return getC().New(params)
}
// New creates a new payment source.
func (c Client) New(params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
if params == nil {
return nil, fmt.Errorf("params should not be nil")
}
if params.Customer == nil {
return nil, fmt.Errorf("Invalid source params: customer needs to be set")
}
path := stripe.FormatURLPath(
"/v1/customers/%s/sources",
stripe.StringValue(params.Customer),
)
paymentsource := &stripe.PaymentSource{}
err := c.B.Call(http.MethodPost, path, c.Key, params, paymentsource)
return paymentsource, err
}
// Get returns the details of a payment source.
func Get(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
return getC().Get(id, params)
}
// Get returns the details of a payment source.
func (c Client) Get(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
if params == nil {
return nil, fmt.Errorf("params should not be nil")
}
if params.Customer == nil {
return nil, fmt.Errorf("Invalid source params: customer needs to be set")
}
path := stripe.FormatURLPath(
"/v1/customers/%s/sources/%s",
stripe.StringValue(params.Customer),
id,
)
paymentsource := &stripe.PaymentSource{}
err := c.B.Call(http.MethodGet, path, c.Key, params, paymentsource)
return paymentsource, err
}
// Update updates a payment source's properties.
func Update(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
return getC().Update(id, params)
}
// Update updates a payment source's properties.
func (c Client) Update(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
if params == nil {
return nil, fmt.Errorf("params should not be nil")
}
if params.Customer == nil {
return nil, fmt.Errorf("Invalid source params: customer needs to be set")
}
path := stripe.FormatURLPath(
"/v1/customers/%s/sources/%s",
stripe.StringValue(params.Customer),
id,
)
paymentsource := &stripe.PaymentSource{}
err := c.B.Call(http.MethodPost, path, c.Key, params, paymentsource)
return paymentsource, err
}
// Del removes a payment source.
func Del(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
return getC().Del(id, params)
}
// Del removes a payment source.
func (c Client) Del(id string, params *stripe.CustomerSourceParams) (*stripe.PaymentSource, error) {
if params == nil {
return nil, fmt.Errorf("params should not be nil")
}
if params.Customer == nil {
return nil, fmt.Errorf("Invalid source params: customer needs to be set")
}
path := stripe.FormatURLPath(
"/v1/customers/%s/sources/%s",
stripe.StringValue(params.Customer),
id,
)
paymentsource := &stripe.PaymentSource{}
err := c.B.Call(http.MethodDelete, path, c.Key, params, paymentsource)
return paymentsource, err
}
// Verify verifies a source which is used for bank accounts.
func Verify(id string, params *stripe.SourceVerifyParams) (*stripe.PaymentSource, error) {
return getC().Verify(id, params)
}
// Verify verifies a source which is used for bank accounts.
func (c Client) Verify(id string, params *stripe.SourceVerifyParams) (*stripe.PaymentSource, error) {
if params == nil {
return nil, fmt.Errorf("params should not be nil")
}
var path string
if params.Customer != nil {
path = stripe.FormatURLPath("/v1/customers/%s/sources/%s/verify",
stripe.StringValue(params.Customer), id)
} else if len(params.Values) > 0 {
path = stripe.FormatURLPath("/v1/sources/%s/verify", id)
} else {
return nil, fmt.Errorf("Only customer bank accounts or sources can be verified in this manner")
}
source := &stripe.PaymentSource{}
err := c.B.Call(http.MethodPost, path, c.Key, params, source)
return source, err
}
// List returns a list of payment sources.
func List(params *stripe.SourceListParams) *Iter {
return getC().List(params)
}
// List returns a list of payment sources.
func (c Client) List(listParams *stripe.SourceListParams) *Iter {
var outerErr error
var path string
if listParams == nil {
outerErr = fmt.Errorf("params should not be nil")
} else if listParams.Customer == nil {
outerErr = fmt.Errorf("Invalid source params: customer needs to be set")
} else {
path = stripe.FormatURLPath("/v1/customers/%s/sources",
stripe.StringValue(listParams.Customer))
}
return &Iter{
Iter: stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) {
list := &stripe.SourceList{}
if outerErr != nil {
return nil, list, outerErr
}
err := c.B.CallRaw(http.MethodGet, path, c.Key, b, p, list)
ret := make([]interface{}, len(list.Data))
for i, v := range list.Data {
ret[i] = v
}
return ret, list, err
}),
}
}
// Iter is an iterator for payment sources.
type Iter struct {
*stripe.Iter
}
// PaymentSource returns the payment source which the iterator is currently pointing to.
func (i *Iter) PaymentSource() *stripe.PaymentSource {
return i.Current().(*stripe.PaymentSource)
}
// SourceList returns the current list object which the iterator is
// currently using. List objects will change as new API calls are made to
// continue pagination.
func (i *Iter) SourceList() *stripe.SourceList {
return i.List().(*stripe.SourceList)
}
func getC() Client {
return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}
|
thorin/minium
|
minium-core/src/main/java/com/vilt/minium/Async.java
|
<gh_stars>0
/*
* Copyright (C) 2013 The Minium Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vilt.minium;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.openqa.selenium.JavascriptExecutor;
/**
* <p>Minium methods that perform some kind of client asynchronous operation must have
* this annotation. Right now, only methods that <strong>do not return</strong>
* {@link WebElements} are allowed to be marked as asynchronous.</p>
* <p>In pratical terms, instead of calling the method
* {@link JavascriptExecutor#executeScript(String, Object...)} to evaluate a
* Minium expression, the engine will call
* {@link JavascriptExecutor#executeAsyncScript(String, Object...)}.</p>
* <p>Because of that, the javascript function corresponding to the declared method must receive an
* extra argument that will correspond to the <code>callback</code> function, which must
* be used to return this function asynchronously.</p>
*
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
*
* @author rui.figueira
*/
@Retention(RUNTIME)
@Target(ElementType.METHOD)
public @interface Async { }
|
lechium/tvOS10Headers
|
System/Library/Frameworks/CoreSpotlight.framework/_MDIndexExtensionLoader.h
|
<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:03:49 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/Frameworks/CoreSpotlight.framework/CoreSpotlight
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol OS_dispatch_queue;
@class NSObject, NSDictionary;
@interface _MDIndexExtensionLoader : NSObject {
id _matchingContext;
NSObject*<OS_dispatch_queue> _queue;
NSDictionary* _extensionsByBundleId;
}
@property (nonatomic,retain) id matchingContext; //@synthesize matchingContext=_matchingContext - In the implementation block
@property (nonatomic,retain) NSObject*<OS_dispatch_queue> queue; //@synthesize queue=_queue - In the implementation block
@property (nonatomic,retain) NSDictionary * extensionsByBundleId; //@synthesize extensionsByBundleId=_extensionsByBundleId - In the implementation block
+(id)_matchDictionary;
-(id)init;
-(NSObject*<OS_dispatch_queue>)queue;
-(void)setQueue:(NSObject*<OS_dispatch_queue>)arg1 ;
-(NSDictionary *)extensionsByBundleId;
-(id)_filterIndexExtensions:(id)arg1 ;
-(void)setExtensionsByBundleId:(NSDictionary *)arg1 ;
-(void)startLookingForExtensionsWithMatchUpdateHandler:(/*^block*/id)arg1 ;
-(void)stopLookingForExtensions;
-(void)findExtensionsWithCompletionBlock:(/*^block*/id)arg1 ;
-(id)_loadExtensionsSynchronously;
-(id)matchingContext;
-(void)setMatchingContext:(id)arg1 ;
@end
|
timboudreau/netbeans-contrib
|
dtrace/postinstallsrc/dtrace/PostInstall.java
|
<filename>dtrace/postinstallsrc/dtrace/PostInstall.java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s):
*
* Portions Copyrighted 2008 Sun Microsystems, Inc.
*/
package dtrace;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* This is a workaround for an issue related to installation of dtrace.jar.
* This copies the /usr/share/lib/java/dtrace.jar file into the
* <cluster_directory>/modules/ext directory.
*
* @author <NAME> <<EMAIL>>
*
*/
public class PostInstall {
public static void main(String[] args) {
try {
File dtraceJar = new File(File.separator + "usr" + File.separator + //NOI18N
"share" + File.separator + "lib" + //NOI18N
File.separator + "java" + File.separator + //NOI18N
"dtrace.jar"); //NOI18N
URL url = PostInstall.class.getResource("PostInstall.class"); //NOI18N
URI uri = url.toURI();
File currentDir = new File(uri);
File dtracePackageDir = currentDir.getParentFile();
File mainDir = dtracePackageDir.getParentFile();
File updateDir = mainDir.getParentFile();
File clusterDir = updateDir.getParentFile();
File modulesExt = new File (clusterDir.toString() + File.separator +
"modules" + File.separator + "ext" + File.separator + //NOI18N
"dtrace.jar"); //NOI18N
copyFile(dtraceJar, modulesExt);
File sourceZip = new File (clusterDir.toString() +
File.separator + "modules" + File.separator + "ext" + //NOI18N
File.separator + "DTraceScripts.zip"); //NOI18N
String userHome = System.getProperty("user.home"); //NOI18N
File destZip = new File (userHome + File.separator +
"DTraceScripts.zip"); //NOI18N
copyFile(sourceZip, destZip);
ZipFile zipFile = new ZipFile(destZip.toString());
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (entry.isDirectory()) {
(new File(userHome + File.separator + entry.getName())).mkdir();
continue;
}
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(userHome +
File.separator + entry.getName())));
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
Process p = null;
String command = "/bin/chmod -R 755 DTraceScripts"; //NOI18N
try {
File userHomeDirFile = new File(System.getProperty("user.home")); //NOI18N
p = Runtime.getRuntime().exec(command, null, userHomeDirFile);
} catch(IOException ex) {
ex.printStackTrace();
}
int retCode = 0;
try {
retCode = p.waitFor();
} catch (InterruptedException ex) {
// We've interupted the process. Kill it and wait for the process to finish.
p.destroy();
while (retCode < 0) {
try {
retCode= p.waitFor();
} catch (InterruptedException ex1) {
ex1.getStackTrace();
}
}
}
}
/*
* This method copies the /usr/share/lib/java/dtrace.jar file into the
* modules/ext directory.
*/
private static void copyFile(File from, File to) {
try {
BufferedInputStream is = new BufferedInputStream(new FileInputStream(from));
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(to));
byte[] buf = new byte[4096];
int cnt;
while ((cnt = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, cnt);
}
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
}
}
|
TimothyGillespie/lombok-intellij-plugin
|
testData/after/CleanupName.java
|
<reponame>TimothyGillespie/lombok-intellij-plugin
// Generated by delombok at Wed Oct 02 19:12:43 GMT 2019
class CleanupName {
void test() {
Object o = "Hello World!";
try {
System.out.println(o);
} finally {
if (java.util.Collections.singletonList(o).get(0) != null) {
o.toString();
}
}
}
void test2() {
Object o = "Hello World too!";
try {
System.out.println(o);
} finally {
if (java.util.Collections.singletonList(o).get(0) != null) {
o.toString();
}
}
}
}
|
zealoussnow/chromium
|
chrome/test/mini_installer/update_lastrun.py
|
<reponame>zealoussnow/chromium<filename>chrome/test/mini_installer/update_lastrun.py
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Updates Chrome's "lastrun" value for the current user in HKCU."""
import _winreg
import optparse
import sys
import time
def UpdateLastrun(client_state_key_path):
""" Updates Chrome's "lastrun" value in the registry to the current time.
Args:
client_state_key_path: The path to Chrome's ClientState key in the
registry.
"""
# time.time returns seconds since the Unix epoch. Chrome uses microseconds
# since the Windows epoch. Adjust based on values inspired by
# https://support.microsoft.com/en-us/kb/167296, which uses 100-nanosecond
# ticks.
now_us = str(int(time.time() * 1000000 + 11644473600000000L))
try:
with _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, client_state_key_path,
0, _winreg.KEY_SET_VALUE
| _winreg.KEY_WOW64_32KEY) as key:
_winreg.SetValueEx(key, 'lastrun', 0, _winreg.REG_SZ, now_us)
except WindowsError:
raise KeyError('Failed opening registry key HKEY_CURRENT_USER\\%s' %
client_state_key_path)
return 0
def main():
usage = 'usage: %prog client_state_key_path'
parser = optparse.OptionParser(
usage, description='Update Chrome\'s "lastrun" value.')
_, args = parser.parse_args()
if len(args) != 1:
parser.error('Incorrect number of arguments.')
UpdateLastrun(args[0])
return 0
if __name__ == '__main__':
sys.exit(main())
|
Ro5635/Cheddar
|
cheddar/cheddar-tx/src/test/java/com/clicktravel/cheddar/infrastructure/messaging/tx/TransactionalMessageSenderTest.java
|
/*
* Copyright 2014 Click Travel Ltd
*
* 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.clicktravel.cheddar.infrastructure.messaging.tx;
import static com.clicktravel.common.random.Randoms.randomInt;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import org.junit.Test;
import com.clicktravel.cheddar.infrastructure.messaging.MessageSender;
import com.clicktravel.cheddar.infrastructure.messaging.TypedMessage;
import com.clicktravel.cheddar.infrastructure.tx.NestedTransactionException;
import com.clicktravel.cheddar.infrastructure.tx.NonExistentTransactionException;
public class TransactionalMessageSenderTest {
final MessageSender<TypedMessage> mockMessageSender = mock(MessageSender.class);
@Test
public void shouldCreateTransactionalMessageSender_withMessageSender() throws Exception {
// Given
final MessageSender<TypedMessage> messageSender = mock(MessageSender.class);
// When
Exception actualException = null;
try {
new TransactionalMessageSender(messageSender);
} catch (final Exception e) {
actualException = e;
}
// Then
assertNull(actualException);
}
@Test
public void shouldBeginTransaction_withNoExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
// When
Exception actualException = null;
try {
transactionalMessageSender.begin();
} catch (final Exception e) {
actualException = e;
}
// Then
assertNull(actualException);
}
@Test
public void shouldNotBeginTransaction_withExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
transactionalMessageSender.begin();
// When
NestedTransactionException actualException = null;
try {
transactionalMessageSender.begin();
} catch (final NestedTransactionException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
@Test
public void shouldNotCommit_withNoExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
// When
NonExistentTransactionException actualException = null;
try {
transactionalMessageSender.commit();
} catch (final NonExistentTransactionException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
@Test
public void shouldSendMessage_withExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
transactionalMessageSender.begin();
final TypedMessage typedMessage = mock(TypedMessage.class);
// When
NonExistentTransactionException actualException = null;
try {
transactionalMessageSender.send(typedMessage);
} catch (final NonExistentTransactionException e) {
actualException = e;
}
// Then
assertNull(actualException);
verifyZeroInteractions(mockMessageSender);
}
@Test
public void shouldNotSendMessage_withNonExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
final TypedMessage typedMessage = mock(TypedMessage.class);
// When
NonExistentTransactionException actualException = null;
try {
transactionalMessageSender.send(typedMessage);
} catch (final NonExistentTransactionException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
@Test
public void shouldCommitSendMessage_withExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
transactionalMessageSender.begin();
final TypedMessage typedMessage = mock(TypedMessage.class);
transactionalMessageSender.send(typedMessage);
// When
transactionalMessageSender.commit();
// Then
verify(mockMessageSender).send(typedMessage);
}
@Test
public void shouldSendDelayedMessage_withExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
transactionalMessageSender.begin();
final TypedMessage typedMessage = mock(TypedMessage.class);
final int delay = 1 + randomInt(100);
// When
NonExistentTransactionException actualException = null;
try {
transactionalMessageSender.sendDelayedMessage(typedMessage, delay);
} catch (final NonExistentTransactionException e) {
actualException = e;
}
// Then
assertNull(actualException);
verifyZeroInteractions(mockMessageSender);
}
@Test
public void shouldNotSendDelayedMessage_withNonExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
final TypedMessage typedMessage = mock(TypedMessage.class);
final int delay = 1 + randomInt(100);
// When
NonExistentTransactionException actualException = null;
try {
transactionalMessageSender.sendDelayedMessage(typedMessage, delay);
} catch (final NonExistentTransactionException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
@Test
public void shouldCommitSendDelayedMessage_withExistingTransaction() throws Exception {
// Given
final TransactionalMessageSender transactionalMessageSender = new TransactionalMessageSender(mockMessageSender);
transactionalMessageSender.begin();
final TypedMessage typedMessage = mock(TypedMessage.class);
final int delay = 1 + randomInt(100);
transactionalMessageSender.sendDelayedMessage(typedMessage, delay);
// When
transactionalMessageSender.commit();
// Then
verify(mockMessageSender).sendDelayedMessage(typedMessage, delay);
}
}
|
benf1977/j2objc-serialization-example
|
j2objc/include/java/io/Externalizable.h
|
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/java/io/Externalizable.java
//
#ifndef _JavaIoExternalizable_H_
#define _JavaIoExternalizable_H_
#include "J2ObjC_header.h"
#include "java/io/Serializable.h"
@protocol JavaIoObjectInput;
@protocol JavaIoObjectOutput;
/*!
@brief Defines an interface for classes that want to be serializable, but have their
own binary representation.
*/
@protocol JavaIoExternalizable < JavaIoSerializable, NSObject, JavaObject >
/*!
@brief Reads the next object from the ObjectInput <code>input</code>.
@param input
the ObjectInput from which the next object is read.
@throws IOException
if an error occurs attempting to read from <code>input</code>.
@throws ClassNotFoundException
if the class of the instance being loaded cannot be found.
*/
- (void)readExternalWithJavaIoObjectInput:(id<JavaIoObjectInput>)input;
/*!
@brief Writes the receiver to the ObjectOutput <code>output</code>.
@param output
the ObjectOutput to write the object to.
@throws IOException
if an error occurs attempting to write to <code>output</code>.
*/
- (void)writeExternalWithJavaIoObjectOutput:(id<JavaIoObjectOutput>)output;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaIoExternalizable)
J2OBJC_TYPE_LITERAL_HEADER(JavaIoExternalizable)
#endif // _JavaIoExternalizable_H_
|
abhijain-sq/square-java-sdk
|
src/main/java/com/squareup/square/models/LoyaltyProgramRewardTier.java
|
<gh_stars>10-100
package com.squareup.square.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
* This is a model class for LoyaltyProgramRewardTier type.
*/
public class LoyaltyProgramRewardTier {
private final String id;
private final int points;
private final String name;
private final LoyaltyProgramRewardDefinition definition;
private final String createdAt;
@JsonInclude(JsonInclude.Include.NON_NULL)
private final CatalogObjectReference pricingRuleReference;
/**
* Initialization constructor.
* @param id String value for id.
* @param points int value for points.
* @param name String value for name.
* @param definition LoyaltyProgramRewardDefinition value for definition.
* @param createdAt String value for createdAt.
* @param pricingRuleReference CatalogObjectReference value for pricingRuleReference.
*/
@JsonCreator
public LoyaltyProgramRewardTier(
@JsonProperty("id") String id,
@JsonProperty("points") int points,
@JsonProperty("name") String name,
@JsonProperty("definition") LoyaltyProgramRewardDefinition definition,
@JsonProperty("created_at") String createdAt,
@JsonProperty("pricing_rule_reference") CatalogObjectReference pricingRuleReference) {
this.id = id;
this.points = points;
this.name = name;
this.definition = definition;
this.createdAt = createdAt;
this.pricingRuleReference = pricingRuleReference;
}
/**
* Getter for Id.
* The Square-assigned ID of the reward tier.
* @return Returns the String
*/
@JsonGetter("id")
public String getId() {
return id;
}
/**
* Getter for Points.
* The points exchanged for the reward tier.
* @return Returns the int
*/
@JsonGetter("points")
public int getPoints() {
return points;
}
/**
* Getter for Name.
* The name of the reward tier.
* @return Returns the String
*/
@JsonGetter("name")
public String getName() {
return name;
}
/**
* Getter for Definition.
* Provides details about the reward tier discount. DEPRECATED at version 2020-12-16. Discount
* details are now defined using a catalog pricing rule and other catalog objects. For more
* information, see [Get discount details for the
* reward](https://developer.squareup.com/docs/loyalty-api/overview#get-discount-details).
* @return Returns the LoyaltyProgramRewardDefinition
*/
@JsonGetter("definition")
public LoyaltyProgramRewardDefinition getDefinition() {
return definition;
}
/**
* Getter for CreatedAt.
* The timestamp when the reward tier was created, in RFC 3339 format.
* @return Returns the String
*/
@JsonGetter("created_at")
public String getCreatedAt() {
return createdAt;
}
/**
* Getter for PricingRuleReference.
* A reference to a Catalog object at a specific version. In general this is used as an entry
* point into a graph of catalog objects, where the objects exist at a specific version.
* @return Returns the CatalogObjectReference
*/
@JsonGetter("pricing_rule_reference")
public CatalogObjectReference getPricingRuleReference() {
return pricingRuleReference;
}
@Override
public int hashCode() {
return Objects.hash(id, points, name, definition, createdAt, pricingRuleReference);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof LoyaltyProgramRewardTier)) {
return false;
}
LoyaltyProgramRewardTier other = (LoyaltyProgramRewardTier) obj;
return Objects.equals(id, other.id)
&& Objects.equals(points, other.points)
&& Objects.equals(name, other.name)
&& Objects.equals(definition, other.definition)
&& Objects.equals(createdAt, other.createdAt)
&& Objects.equals(pricingRuleReference, other.pricingRuleReference);
}
/**
* Converts this LoyaltyProgramRewardTier into string format.
* @return String representation of this class
*/
@Override
public String toString() {
return "LoyaltyProgramRewardTier [" + "id=" + id + ", points=" + points + ", name=" + name
+ ", definition=" + definition + ", createdAt=" + createdAt
+ ", pricingRuleReference=" + pricingRuleReference + "]";
}
/**
* Builds a new {@link LoyaltyProgramRewardTier.Builder} object.
* Creates the instance with the state of the current model.
* @return a new {@link LoyaltyProgramRewardTier.Builder} object
*/
public Builder toBuilder() {
Builder builder = new Builder(id, points, name, definition, createdAt)
.pricingRuleReference(getPricingRuleReference());
return builder;
}
/**
* Class to build instances of {@link LoyaltyProgramRewardTier}.
*/
public static class Builder {
private String id;
private int points;
private String name;
private LoyaltyProgramRewardDefinition definition;
private String createdAt;
private CatalogObjectReference pricingRuleReference;
/**
* Initialization constructor.
* @param id String value for id.
* @param points int value for points.
* @param name String value for name.
* @param definition LoyaltyProgramRewardDefinition value for definition.
* @param createdAt String value for createdAt.
*/
public Builder(String id, int points, String name,
LoyaltyProgramRewardDefinition definition, String createdAt) {
this.id = id;
this.points = points;
this.name = name;
this.definition = definition;
this.createdAt = createdAt;
}
/**
* Setter for id.
* @param id String value for id.
* @return Builder
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* Setter for points.
* @param points int value for points.
* @return Builder
*/
public Builder points(int points) {
this.points = points;
return this;
}
/**
* Setter for name.
* @param name String value for name.
* @return Builder
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* Setter for definition.
* @param definition LoyaltyProgramRewardDefinition value for definition.
* @return Builder
*/
public Builder definition(LoyaltyProgramRewardDefinition definition) {
this.definition = definition;
return this;
}
/**
* Setter for createdAt.
* @param createdAt String value for createdAt.
* @return Builder
*/
public Builder createdAt(String createdAt) {
this.createdAt = createdAt;
return this;
}
/**
* Setter for pricingRuleReference.
* @param pricingRuleReference CatalogObjectReference value for pricingRuleReference.
* @return Builder
*/
public Builder pricingRuleReference(CatalogObjectReference pricingRuleReference) {
this.pricingRuleReference = pricingRuleReference;
return this;
}
/**
* Builds a new {@link LoyaltyProgramRewardTier} object using the set fields.
* @return {@link LoyaltyProgramRewardTier}
*/
public LoyaltyProgramRewardTier build() {
return new LoyaltyProgramRewardTier(id, points, name, definition, createdAt,
pricingRuleReference);
}
}
}
|
nyx-litenite/never
|
front/param.c
|
/**
* Copyright 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "param.h"
#include "dim.h"
#include "range.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
param * param_new_bool(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_BOOL;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_int(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_INT;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_long(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_LONG;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_float(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_FLOAT;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_double(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_DOUBLE;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_char(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_CHAR;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_string(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_STRING;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_void(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_VOID;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = NULL;
value->line_no = 0;
return value;
}
param * param_new_c_ptr(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_C_PTR;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_dim(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_DIM;
value->const_type = PARAM_CONST_TYPE_CONST;
value->index = -1;
value->id = id;
value->array_dim.array = NULL;
/* TODO: check value->ret = NULL; */
value->line_no = 0;
return value;
}
param * param_new_array(char * id, param_list * dims, param * ret)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_ARRAY;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->array.dims = dims;
value->array.ret = ret;
value->line_no = 0;
if (dims != NULL)
{
param_dim_set_array(value->array.dims, value);
}
return value;
}
param * param_new_range(char * id, range_list * ranges)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_RANGE;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->range.ranges = ranges;
value->line_no = 0;
value->range.ret = param_new_int(NULL);
if (value->range.ranges != NULL)
{
range_dim_set_range(value->range.ranges, value);
}
return value;
}
param * param_new_range_dim(char * id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_RANGE_DIM;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->line_no = 0;
return value;
}
param * param_new_slice(char * id, range_list * ranges, param * ret)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_SLICE;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->slice.ranges = ranges;
value->slice.ret = ret;
value->line_no = 0;
if (value->slice.ranges != NULL)
{
range_dim_set_slice(value->slice.ranges, value);
}
return value;
}
param * param_new_record(char * id, char * record_id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_RECORD;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->record.record_id = record_id;
value->record.module_id = NULL;
value->record.record_value = NULL;
value->line_no = 0;
return value;
}
param * param_new_record_module(char * id, char * record_id, char * module_id)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_RECORD;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->record.record_id = record_id;
value->record.module_id = module_id;
value->record.record_value = NULL;
value->line_no = 0;
return value;
}
param * param_new_func(char * id, param_list * params, param * ret)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_FUNC;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->index = -1;
value->id = id;
value->func.params = params;
value->func.ret = ret;
value->line_no = 0;
return value;
}
param * param_new_touple(char * id, param_list * dims)
{
param * value = (param *)malloc(sizeof(param));
value->type = PARAM_TOUPLE;
value->const_type = PARAM_CONST_TYPE_UNKNOWN;
value->id = id;
value->touple.dims = dims;
value->line_no = 0;
value->touple.cycle = 0;
return value;
}
void param_delete(param * value)
{
if (value->id)
{
free(value->id);
}
switch (value->type)
{
case PARAM_BOOL:
case PARAM_INT:
case PARAM_LONG:
case PARAM_FLOAT:
case PARAM_DOUBLE:
case PARAM_CHAR:
case PARAM_STRING:
case PARAM_VOID:
case PARAM_C_PTR:
case PARAM_DIM:
case PARAM_RANGE_DIM:
case PARAM_SLICE_DIM:
break;
case PARAM_ARRAY:
if (value->array.dims != NULL)
{
param_list_delete(value->array.dims);
}
if (value->array.ret != NULL)
{
param_delete(value->array.ret);
}
break;
case PARAM_RANGE:
if (value->range.ranges != NULL)
{
range_list_delete(value->range.ranges);
}
if (value->array.ret != NULL)
{
param_delete(value->array.ret);
}
break;
case PARAM_SLICE:
if (value->slice.ranges != NULL)
{
range_list_delete(value->slice.ranges);
}
if (value->array.ret != NULL)
{
param_delete(value->array.ret);
}
break;
case PARAM_ENUMTYPE:
case PARAM_RECORD:
if (value->record.record_id)
{
free(value->record.record_id);
}
if (value->record.module_id)
{
free(value->record.module_id);
}
break;
case PARAM_FUNC:
if (value->func.params != NULL)
{
param_list_delete(value->func.params);
}
if (value->func.ret != NULL)
{
param_delete(value->func.ret);
}
break;
case PARAM_TOUPLE:
if (value->touple.dims != NULL)
{
param_list_delete(value->touple.dims);
}
break;
}
free(value);
}
int param_cmp(param * param_one, param * param_two, bool const_cmp)
{
if (param_one == NULL && param_two == NULL)
{
return PARAM_CMP_SUCC;
}
if ((param_one == NULL && param_two != NULL) ||
(param_one != NULL && param_two == NULL))
{
return PARAM_CMP_FAIL;
}
if (const_cmp &&
param_one->const_type != param_two->const_type)
{
return PARAM_CMP_FAIL;
}
if (param_one->type == PARAM_BOOL && param_two->type == PARAM_BOOL)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_INT && param_two->type == PARAM_INT)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_FLOAT && param_two->type == PARAM_FLOAT)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_CHAR && param_two->type == PARAM_CHAR)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_STRING && param_two->type == PARAM_STRING)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_VOID && param_two->type == PARAM_VOID)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_C_PTR && param_two->type == PARAM_C_PTR)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_ARRAY && param_two->type == PARAM_ARRAY)
{
if ((param_one->array.dims->count == param_two->array.dims->count) &&
(param_cmp(param_one->array.ret, param_two->array.ret, false) == PARAM_CMP_SUCC))
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
else if (param_one->type == PARAM_RANGE && param_two->type == PARAM_RANGE)
{
if (param_one->range.ranges->count == param_two->range.ranges->count)
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
else if (param_one->type == PARAM_RANGE_DIM && param_two->type == PARAM_RANGE_DIM)
{
return PARAM_CMP_SUCC;
}
else if (param_one->type == PARAM_SLICE && param_two->type == PARAM_SLICE)
{
if ((param_one->range.ranges->count == param_two->range.ranges->count) &&
(param_cmp(param_one->range.ret, param_two->range.ret, false) == PARAM_CMP_SUCC))
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
else if (param_one->type == PARAM_ENUMTYPE && param_two->type == PARAM_ENUMTYPE)
{
if (param_one->record.enumtype_value == param_two->record.enumtype_value)
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
else if (param_one->type == PARAM_RECORD && param_two->type == PARAM_RECORD)
{
if (param_one->record.record_value == param_two->record.record_value)
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
else if (param_one->type == PARAM_FUNC && param_two->type == PARAM_FUNC)
{
return func_cmp(param_one->func.params, param_one->func.ret,
param_two->func.params, param_one->func.ret, const_cmp);
}
else if (param_one->type == PARAM_TOUPLE && param_two->type == PARAM_TOUPLE)
{
return param_list_cmp(param_one->touple.dims, param_two->touple.dims, false);
}
else
{
return PARAM_CMP_FAIL;
}
}
int param_list_cmp(param_list * param_one, param_list * param_two, bool const_cmp)
{
if (param_one == NULL && param_two == NULL)
{
return PARAM_CMP_SUCC;
}
if ((param_one == NULL && param_two != NULL) ||
(param_one != NULL && param_two == NULL))
{
return PARAM_CMP_FAIL;
}
if (param_one->count != param_two->count)
{
return PARAM_CMP_FAIL;
}
param_list_node * param_one_node = param_one->tail;
param_list_node * param_two_node = param_two->tail;
while (param_one_node != NULL && param_two_node != NULL)
{
param * param_one_value = param_one_node->value;
param * param_two_value = param_two_node->value;
if (param_cmp(param_one_value, param_two_value, const_cmp) == PARAM_CMP_FAIL)
{
return PARAM_CMP_FAIL;
}
param_one_node = param_one_node->next;
param_two_node = param_two_node->next;
}
return PARAM_CMP_SUCC;
}
int func_cmp(param_list * param_list_one, param * ret_one, param_list * param_list_two,
param * ret_two, bool const_cmp)
{
if (param_list_cmp(param_list_one, param_list_two, true) == PARAM_CMP_SUCC &&
param_cmp(ret_one, ret_two, false) == PARAM_CMP_SUCC)
{
return PARAM_CMP_SUCC;
}
else
{
return PARAM_CMP_FAIL;
}
}
param_list_node * param_list_node_new(param * value)
{
param_list_node * node = (param_list_node *)malloc(sizeof(param_list_node));
node->value = value;
node->prev = NULL;
node->next = NULL;
return node;
}
void param_list_node_delete(param_list_node * node)
{
if (node->value)
{
param_delete(node->value);
}
free(node);
}
param_list * param_list_new()
{
param_list * list = (param_list *)malloc(sizeof(param_list));
list->count = 0;
list->head = NULL;
list->tail = NULL;
return list;
}
void param_list_delete(param_list * list)
{
param_list_node * node = list->tail;
while (node != NULL)
{
param_list_node * tmp = node->next;
param_list_node_delete(node);
node = tmp;
}
free(list);
}
void param_list_add_beg(param_list * list, param * value)
{
param_list_node * node = param_list_node_new(value);
list->count++;
if (list->head == NULL && list->tail == NULL)
{
list->head = list->tail = node;
}
else
{
list->tail->prev = node;
node->next = list->tail;
list->tail = node;
}
}
void param_list_add_end(param_list * list, param * value)
{
param_list_node * node = param_list_node_new(value);
list->count++;
if (list->head == NULL && list->tail == NULL)
{
list->head = list->tail = node;
}
else
{
list->head->next = node;
node->prev = list->head;
list->head = node;
}
}
param * param_list_find(param_list * list, char * id)
{
param * ret = NULL;
param_list_node * node = list->tail;
while (node != NULL)
{
param * value = node->value;
if (value != NULL)
{
if (strcmp(value->id, id) == 0)
{
ret = value;
break;
}
}
node = node->next;
}
return ret;
}
param * param_list_get_nth(param_list * list, unsigned int index)
{
if (list == NULL)
{
return NULL;
}
unsigned int i = 0;
param_list_node * node = list->tail;
for (i = 0; node != NULL && i < index; i++)
{
node = node->next;
}
if (node != NULL)
{
return node->value;
}
else
{
return NULL;
}
}
void param_dim_set_array(param_list * dims, param * array)
{
int index = 0;
param_list_node * node = dims->tail;
while (node != NULL)
{
param * value = node->value;
if (value != NULL)
{
value->index = index++;
value->array_dim.array = array;
}
node = node->next;
}
}
void param_print(param * value)
{
if (value == NULL)
return;
printf("param %s %d %s\n", param_type_str(value->type), value->index,
value->id);
}
void param_list_print(param_list * list)
{
param_list_node * node = list->tail;
while (node != NULL)
{
param * value = node->value;
if (value != NULL)
{
param_print(value);
}
node = node->next;
}
}
char * param_type_str(param_type type)
{
switch (type)
{
case PARAM_BOOL:
return "bool";
case PARAM_INT:
return "int";
case PARAM_LONG:
return "long";
case PARAM_FLOAT:
return "float";
case PARAM_DOUBLE:
return "double";
case PARAM_ENUMTYPE:
return "enumtype";
case PARAM_CHAR:
return "char";
case PARAM_STRING:
return "string";
case PARAM_VOID:
return "void";
case PARAM_C_PTR:
return "c_ptr";
case PARAM_RECORD:
return "record";
case PARAM_DIM:
return "dim";
case PARAM_RANGE_DIM:
return "range dim";
case PARAM_ARRAY:
return "array";
case PARAM_RANGE:
return "range";
case PARAM_SLICE:
return "slice";
case PARAM_SLICE_DIM:
return "slice dim";
case PARAM_FUNC:
return "func";
case PARAM_TOUPLE:
return "touple";
}
return "unknown";
}
|
mustafaergul/travis-tasks
|
lib/travis/addons/gdpr/task.rb
|
<filename>lib/travis/addons/gdpr/task.rb<gh_stars>10-100
require 'travis/addons/email/task'
require 'travis/addons/gdpr/mailer/gdpr_mailer'
module Travis
module Addons
module Gdpr
class Task < Travis::Addons::Email::Task
class NoMailType < StandardError; end
private
def send_email
type = params.fetch(:email_type)
case type
when 'export'
Mailer::GdprMailer.export(recipients, params.fetch(:user_name), params.fetch(:url)).deliver
when 'purge'
Mailer::GdprMailer.purge(recipients, params.fetch(:request_date)).deliver
else
raise NoMailType, "#{type} is not a valid email type"
end
emails = recipients.map { |r| 'email=' + obfuscate_email_address(r) }.join(' ')
info "type=#{type} status=sent msg='email sent #{emails}"
end
end
end
end
end
|
L8RMedia/exponent
|
ios/versioned-react-native/ABI11_0_0/Exponent/Modules/Api/Components/ABI11_0_0EXBlurViewManager.h
|
// Copyright 2015-present 650 Industries. All rights reserved.
#import "ABI11_0_0RCTViewManager.h"
@interface ABI11_0_0EXBlurViewManager : ABI11_0_0RCTViewManager
@end
|
m-pa/themis-graphql
|
src/validate-env.js
|
const Joi = require('joi');
const schema = Joi.object().keys({
PORT: Joi.string().alphanum().min(2).max(5),
NODE_ENV: Joi
.string()
.valid([ 'production', 'development', 'test' ]),
LOG_LEVEL: Joi
.string()
.valid([ 'debug', 'warn', 'error', 'info' ]),
GQL_TRACING: Joi
.string()
.valid([ 'true', 'false' ]),
GQL_CACHE_CONTROL: Joi
.string()
.valid([ 'true', 'false' ]),
}).unknown();
module.exports = function validateEnv () {
const { error } = Joi.validate(process.env, schema);
if (error) {
throw new Error(error);
}
};
|
xuesenLi/asset_management
|
renren-admin/src/main/java/io/renren/modules/asset/service/AssetAreaService.java
|
<filename>renren-admin/src/main/java/io/renren/modules/asset/service/AssetAreaService.java<gh_stars>1-10
package io.renren.modules.asset.service;
import com.baomidou.mybatisplus.extension.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.asset.entity.AssetAreaEntity;
import io.renren.modules.asset.vo.ResponseVo;
import java.util.List;
import java.util.Map;
/**
*
*
* @author lxs
* @email <EMAIL>
* @date 2020-04-10 13:59:02
*/
public interface AssetAreaService extends IService<AssetAreaEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
e-amzallag/bricksetapi
|
src/main/java/org/dajlab/bricksetapi/v3/vo/Reviews.java
|
<gh_stars>1-10
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.dajlab.bricksetapi.v3.vo;
import java.util.Calendar;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Reviews {
private String author;
private Calendar datePosted;
private Rating rating;
private String title;
private String review;
@JsonProperty("HTML")
private Boolean html;
/**
* @return the author
*/
public final String getAuthor() {
return author;
}
/**
* @param author
* the author to set
*/
public final void setAuthor(String author) {
this.author = author;
}
/**
* @return the datePosted
*/
public final Calendar getDatePosted() {
return datePosted;
}
/**
* @param datePosted
* the datePosted to set
*/
public final void setDatePosted(Calendar datePosted) {
this.datePosted = datePosted;
}
/**
* @return the rating
*/
public final Rating getRating() {
return rating;
}
/**
* @param rating
* the rating to set
*/
public final void setRating(Rating rating) {
this.rating = rating;
}
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title
* the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* @return the review
*/
public final String getReview() {
return review;
}
/**
* @param review
* the review to set
*/
public final void setReview(String review) {
this.review = review;
}
/**
* @return the html
*/
public final Boolean getHtml() {
return html;
}
/**
* @param html
* the html to set
*/
public final void setHtml(Boolean html) {
this.html = html;
}
}
|
fog/fog-softlayer
|
tests/softlayer/models/compute/flavor_tests.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# © Copyright IBM Corporation 2014.
#
# LICENSE: MIT (http://opensource.org/licenses/MIT)
#
Shindo.tests("Fog::Compute[:softlayer] | Flavor model", ["softlayer"]) do
tests("success") do
@service = Fog::Compute[:softlayer]
tests("#all") do
returns(Fog::Softlayer::Compute::Flavor) { @service.flavors.all.first.class }
end
tests("#get") do
returns(Fog::Softlayer::Compute::Flavor) { @service.flavors.get('m1.tiny').class }
end
end
end
|
trumank/DRG-Mods
|
Source/FSD/Public/ELineCutterProjectileUpgradeType.h
|
<filename>Source/FSD/Public/ELineCutterProjectileUpgradeType.h
#pragma once
#include "CoreMinimal.h"
#include "ELineCutterProjectileUpgradeType.generated.h"
UENUM(BlueprintType)
enum class ELineCutterProjectileUpgradeType : uint8 {
LineSize,
LineSizeMultiplier,
ExplosiveRound,
SetDeployDelay,
AddDeployTime,
ExplodeOnNextProjectile,
DoubleLine,
LineSizeAdd,
SetDeployTime,
RollUntilStop,
Yawing,
PlasmaTrail,
};
|
shanika04/dashbuilder
|
dashbuilder-backend/dashbuilder-dataset-elasticsearch/src/test/java/org/dashbuilder/dataprovider/backend/elasticsearch/suite/ElasticSearchTestSuite.java
|
<reponame>shanika04/dashbuilder
package org.dashbuilder.dataprovider.backend.elasticsearch.suite;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dashbuilder.dataprovider.backend.elasticsearch.*;
import org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClientTest;
import org.elasticsearch.bootstrap.Elasticsearch;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
/**
* Test Suite for integration with an Elastic Search instance that is operated by this test suite and suite classes.
* - It starts and stops an ELS instance at local port tcp 9200. Ensure that it's available at localhost.
* - It populates with default "expensereports" index documents the local ELS instance. @See ElasticSearchDataSetTestBase.class
*
*
* <p>This test suite does:</p>
* <ul>
* <li>Creates a temporary home folder for an ElasticSearch server with required configuration files</li>
* <li>Runs an elastic search server instance, by default at <code>localhost:9200</code> and working at the temporary home folder</li>
* <li>Creates a default example <code>shakespeare</code> index and mappings for it</li>
* <li>Populates the <code>shakespeare</code> index with some documents</li>
* <li>At this point, inherited test classes can perform the requests to the EL server.</li>
* <li>Finally, stops the EL server and deletes the temporary home folder.</li>
* </ul>
*
* <p>The example used consist of the creation of the index <code>expensereports</code></p>
* <p>By default this index wil be available at <code>http://localhost:9200/expensereports</code></p>
*
* <p>Columns for index <code>expensereports</code>:</p>
* <ul>
* <li><code>id</code> - integer</li>
* <li><code>city</code> - string</li>
* <li><code>department</code> - string</li>
* <li><code>employee</code> - string</li>
* <li><code>date</code> - date</li>
* <li><code>amount</code> - float</li>
* </ul>
*
* <p>All indexed documents will have a document type value as <code>expense</code></p>
*
* <p>Another index named <code>expensereports-sensitive</code> can be created and populated too, with same fileds and data as
* the <code>expensereports</code> one but in this index, the field <code>employee</code> is analyzed with a custom tokenizer analyzer to
* provide filtering with case sensitive features.</p>
*
* @since 0.3.0
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
ElasticSearchCommonTests.class,
ElasticSearchJestClientTest.class,
ElasticSearchDataSetCustomColumnsTest.class,
ElasticSearchDataSetTest.class,
ElasticSearchEmptyIntervalsTest.class,
ElasticSearchMultiFieldsTest.class,
ElasticSearchEmptyArgumentsTest.class
})
public class ElasticSearchTestSuite {
@ClassRule
public static TemporaryFolder elHomeFolder = new TemporaryFolder();
static final Logger logger =
LoggerFactory.getLogger(ElasticSearchTestSuite.class);
// NOTE: If you change the host or port in config/elasticsearch.yml, you should modify this value.
public static final String EL_SERVER = "http://localhost:9200/";
// System properties for EL server.
protected static final String EL_PROPERTY_ELASTICSEARCH = "elasticsearch";
protected static final String EL_PROPERTY_HOME = "es.path.home";
protected static final String EL_PROPERTY_FOREGROUND = "es.foreground";
protected static final String EL_PROPERTY_SCRIPT_INLINE = "es.script.inline";
protected static final String EL_PROPERTY_SCRIPT_INDEXED = "es.script.indexed";
// Config files & example data for running EL server.
protected static final String EL_CONFIG_DIR = "config";
protected static final String EL_CONFIG_ELASTICSEARCH = "org/dashbuilder/dataprovider/backend/elasticsearch/server/config/elasticsearch.yml";
protected static final String EL_CONFIG_LOGGING = "org/dashbuilder/dataprovider/backend/elasticsearch/server/config/logging.yml";
protected static final String EL_EXAMPLE_MAPPINGS = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/expensereports-mappings.json";
protected static final String EL_EXAMPLE_DATA = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/expensereports-data.json";
protected static final String EL_EXAMPLE_CSENSITIVE_INDEX = "expensereports-sensitive";
protected static final String EL_EXAMPLE_CSENSITIVE_MAPPINGS = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/expensereports-csensitive-mappings.json";
protected static final String EL_EXAMPLE_CSENSITIVE_DATA = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/expensereports-csensitive-data.json";
protected static final String EL_EXAMPLE_EMPTYINTERVALS_INDEX = "emptyintervals";
protected static final String EL_EXAMPLE_EMPTYINTERVALS_MAPPINGS = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/emptyIntervals-mappings.json";
protected static final String EL_EXAMPLE_EMPTYINTERVALS_DATA = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/emptyIntervals-data.json";
protected static final String EL_EXAMPLE_MULTIFIELDS_INDEX = "multifields";
protected static final String EL_EXAMPLE_MULTIFIELDS_MAPPINGS = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/multifields-mappings.json";
protected static final String EL_EXAMPLE_MULTIFIELDS_DATA = "org/dashbuilder/dataprovider/backend/elasticsearch/server/example-data/multifields-data.json";
// EL remote REST API endpoints & other parameters.
protected static final String EL_REST_BULK = "_bulk";
protected static final String EL_REST_COUNT = "_count";
protected static final int EL_REST_RESPONSE_OK = 200;
protected static final int EL_REST_RESPONSE_CREATED = 201;
// Other constants.
protected static final String HEADER_ACCEPT = "Accept";
protected static final String HEADER_CONTENTTYPE = "content-type";
protected static final String CONTENTTYPE_JSON = "application/json; charset=utf-8";
protected static final String ENCODING = "UTF-8";
protected static final String SYMBOL_SLASH = "/";
@BeforeClass
public static void setUpClass() {
try {
runELServer(elHomeFolder);
createAndPopulateExpenseReportsIndex();
createAndPopulateExpenseReportsCSensitiveIndex();
createAndPopulateEmptyIntervalsIndex();
createAndPopulateMultiFieldsIndex();
} catch (Exception e) {
logger.error("Error starting up the ELS instance.", e);
}
}
@AfterClass
public static void tearDownClass() {
try {
stopELServer(elHomeFolder);
} catch (Exception e) {
logger.error("Error stopping the ELS instance.", e);
}
}
// Not necessary use of @BeforeClass - @see ElasticSearchTestSuite.java.
public static void runELServer(TemporaryFolder elHomeFolder) throws Exception {
// Build a temporary EL home folder. Copy config files to it.
File elHome = elHomeFolder.newFolder("dashbuilder-elasticsearch");
File elHomeConfig = new File(elHome, EL_CONFIG_DIR);
URL configFileUrl = Thread.currentThread().getContextClassLoader().getResource(EL_CONFIG_ELASTICSEARCH);
URL loggingFileUrl = Thread.currentThread().getContextClassLoader().getResource(EL_CONFIG_LOGGING);
File configFile = new File(configFileUrl.getFile());
File loggingFile = new File(loggingFileUrl.getFile());
// Create the configuration files and copy config files.
if (!elHomeConfig.mkdirs()) throw new RuntimeException("Cannot create config directory at [" + elHomeConfig.getAbsolutePath() + "].");
FileUtils.copyFileToDirectory(configFile, elHomeConfig);
FileUtils.copyFileToDirectory(loggingFile, elHomeConfig);
// Set the system properties for running the EL server.
System.setProperty(EL_PROPERTY_ELASTICSEARCH, "");
System.setProperty(EL_PROPERTY_FOREGROUND, "yes");
System.setProperty(EL_PROPERTY_HOME, elHome.getAbsolutePath());
System.setProperty(EL_PROPERTY_SCRIPT_INLINE, "on");
System.setProperty(EL_PROPERTY_SCRIPT_INDEXED, "on");
// Run the EL server.
// ELS_THREAD.setDaemon(true);
// ELS_THREAD.start();
startInstance();
}
public static void createAndPopulateExpenseReportsIndex() throws Exception{
ElasticSearchUrlBuilder urlBuilder = new ElasticSearchUrlBuilder(EL_SERVER, ElasticSearchDataSetTestBase.EL_EXAMPLE_INDEX);
// Create the expensereports example index.
createIndexELServer(urlBuilder, EL_EXAMPLE_MAPPINGS);
// Populate the server with some test content.
populateELServer(urlBuilder, EL_EXAMPLE_DATA);
// Test mappings and document count.
testMappingCreated(urlBuilder);
testDocumentsCount(urlBuilder);
}
public static void createAndPopulateExpenseReportsCSensitiveIndex() throws Exception{
ElasticSearchUrlBuilder urlBuilder = new ElasticSearchUrlBuilder(EL_SERVER, EL_EXAMPLE_CSENSITIVE_INDEX);
// Create the expensereports example index.
createIndexELServer(urlBuilder, EL_EXAMPLE_CSENSITIVE_MAPPINGS);
// Populate the server with some test content.
populateELServer(urlBuilder, EL_EXAMPLE_CSENSITIVE_DATA);
}
public static void createAndPopulateEmptyIntervalsIndex() throws Exception{
ElasticSearchUrlBuilder urlBuilder = new ElasticSearchUrlBuilder(EL_SERVER, EL_EXAMPLE_EMPTYINTERVALS_INDEX);
// Create the expensereports example index.
createIndexELServer(urlBuilder, EL_EXAMPLE_EMPTYINTERVALS_MAPPINGS);
// Populate the server with some test content.
populateELServer(urlBuilder, EL_EXAMPLE_EMPTYINTERVALS_DATA);
}
public static void createAndPopulateMultiFieldsIndex() throws Exception{
ElasticSearchUrlBuilder urlBuilder = new ElasticSearchUrlBuilder(EL_SERVER, EL_EXAMPLE_MULTIFIELDS_INDEX);
// Create the expensereports example index.
createIndexELServer(urlBuilder, EL_EXAMPLE_MULTIFIELDS_MAPPINGS);
// Populate the server with some test content.
populateELServer(urlBuilder, EL_EXAMPLE_MULTIFIELDS_DATA);
}
private static void startInstance() {
Elasticsearch.main(new String[]{});
}
public static void createIndexELServer(ElasticSearchUrlBuilder urlBuilder, String jsonMappingsFile) throws Exception {
// Create an http client
CloseableHttpClient httpclient = HttpClients.createDefault();
// Obtain data to configure & populate the server.
String mappingsContent = getFileAsString(jsonMappingsFile);
// Create an index mappings.
HttpPost httpPost = new HttpPost(urlBuilder.getIndexRoot());
StringEntity inputMappings = new StringEntity(mappingsContent);
inputMappings.setContentType(CONTENTTYPE_JSON);
httpPost.setEntity(inputMappings);
CloseableHttpResponse mappingsResponse = httpclient.execute(httpPost);
if (mappingsResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) {
log("Error response body:");
log(responseAsString(mappingsResponse));
}
Assert.assertEquals(EL_REST_RESPONSE_OK, mappingsResponse.getStatusLine().getStatusCode());
}
public static void populateELServer(ElasticSearchUrlBuilder urlBuilder, String dataFile) throws Exception {
// Insert documents in bulk mode.
CloseableHttpClient httpclient = HttpClients.createDefault();
File dataContentFile = new File(Thread.currentThread().getContextClassLoader().getResource(dataFile).getFile());
addDocuments(httpclient, urlBuilder, dataContentFile);
// Let EL server some time to index all documents...
Thread.sleep(5000);
}
/**
* <p>Index documents in bulk mode into EL server.</p>
*/
protected static void addDocuments(CloseableHttpClient httpClient, ElasticSearchUrlBuilder urlBuilder, File dataContentFile) throws Exception {
HttpPost httpPost2 = new HttpPost(urlBuilder.getBulk());
FileEntity inputData = new FileEntity(dataContentFile);
inputData.setContentType(CONTENTTYPE_JSON);
httpPost2.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON);
httpPost2.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON);
httpPost2.setEntity(inputData);
CloseableHttpResponse dataResponse = httpClient.execute(httpPost2);
if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) {
log("Error response body:");
log(responseAsString(dataResponse));
}
httpPost2.completed();
Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_OK);
}
/**
* <p>Index a single document into EL server.</p>
*/
protected static void addDocument(ElasticSearchUrlBuilder urlBuilder, CloseableHttpClient httpclient, String type, String document) throws Exception {
HttpPost httpPut = new HttpPost(urlBuilder.getIndexRoot() + "/" + type);
StringEntity inputData = new StringEntity(document);
inputData.setContentType(CONTENTTYPE_JSON);
httpPut.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON);
httpPut.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON);
httpPut.setEntity(inputData);
CloseableHttpResponse dataResponse = httpclient.execute(httpPut);
if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_CREATED) {
log("Error response body:");
log(responseAsString(dataResponse));
}
Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_CREATED);
}
// Not necessary use of @AfterClass - @see ElasticSearchTestSuite.java.
public static void stopELServer(TemporaryFolder elHomeFolder) throws Exception {
// Clear the system properties that have been set for running the EL server.
System.clearProperty(EL_PROPERTY_ELASTICSEARCH);
System.clearProperty(EL_PROPERTY_FOREGROUND);
System.clearProperty(EL_PROPERTY_HOME);
System.clearProperty(EL_PROPERTY_SCRIPT_INLINE);
System.clearProperty(EL_PROPERTY_SCRIPT_INDEXED);
// Stop the EL server.
Elasticsearch.close(new String[]{});
// ELS_THREAD.join();
// Delete the working home folder for elasticsearch.
elHomeFolder.delete();
}
public static void testMappingCreated(ElasticSearchUrlBuilder urlBuilder) throws Exception {
Object[] response = doGet(urlBuilder.getIndexRoot());
Assert.assertEquals(response[0], EL_REST_RESPONSE_OK);
log("Mappings for index [" + ElasticSearchDataSetTestBase.EL_EXAMPLE_INDEX + "]:");
log(response[1]);
}
public static void testDocumentsCount(ElasticSearchUrlBuilder urlBuilder) throws Exception {
Object[] response = doGet(urlBuilder.getIndexCount());
Assert.assertEquals(response[0], EL_REST_RESPONSE_OK);
log("Count for index [" + ElasticSearchDataSetTestBase.EL_EXAMPLE_INDEX + "]:");
log(response[1]);
}
protected static String getFileAsString(String file) throws Exception {
InputStream mappingsFileUrl = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
StringWriter writer = null;
String fileContent = null;
try {
writer = new StringWriter();
IOUtils.copy(mappingsFileUrl, writer, ENCODING);
fileContent = writer.toString();
} finally {
if (writer != null) writer.close();
}
// Ensure newline characters meet the HTTP specification formatting requirements.
return fileContent.replaceAll("\n","\r\n");
}
public static class ElasticSearchUrlBuilder {
private String serverUrl;
private String index;
public ElasticSearchUrlBuilder(String serverUrl, String index) {
Assert.assertTrue(serverUrl != null && serverUrl.trim().length() > 0);
Assert.assertTrue(index != null && index.trim().length() > 0 && !index.endsWith(SYMBOL_SLASH));
this.serverUrl = serverUrl;
this.index = index;
if (!this.serverUrl.endsWith(SYMBOL_SLASH)) this.serverUrl = this.serverUrl + SYMBOL_SLASH;
}
public String getRoot() {
return serverUrl;
}
public String getIndexRoot() {
return serverUrl + index;
}
public String getIndexCount() {
return getIndexRoot() + SYMBOL_SLASH + EL_REST_COUNT;
}
public String getBulk() {
return serverUrl + EL_REST_BULK;
}
}
protected static Object[] doGet(String url) throws Exception {
Object[] response = null;
if (url == null || url.trim().length() == 0) return response;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
HttpEntity entity1 = response1.getEntity();
String responseBody = responseAsString(response1);
int responseStatus = response1.getStatusLine().getStatusCode();
response = new Object [] {responseStatus, responseBody};
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
return response;
}
protected static String responseAsString(CloseableHttpResponse response) throws IOException {
return streamAsString(response.getEntity().getContent());
}
protected static String streamAsString(InputStream inputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, ENCODING);
return writer.toString();
}
protected static void log(Object message) {
// System.out.print(message);
if (logger.isDebugEnabled()) {
logger.debug(message.toString());
}
}
}
|
alexchao26/advent-of-code-go
|
2017/day12/main.go
|
<gh_stars>10-100
package main
import (
"flag"
"fmt"
"strings"
"github.com/alexchao26/advent-of-code-go/cast"
"github.com/alexchao26/advent-of-code-go/util"
)
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
var ans int
if part == 1 {
ans = part1(util.ReadFile("./input.txt"))
} else {
ans = part2(util.ReadFile("./input.txt"))
}
fmt.Println("Output:", ans)
}
func part1(input string) int {
graph := makeGraphFromInput(input)
var count int
for k := range graph {
if dfsCanReachTarget(graph, k, 0, map[int]bool{}) {
count++
}
}
return count
}
func part2(input string) int {
graph := makeGraphFromInput(input)
allKeys := []int{}
for k := range graph {
allKeys = append(allKeys, k)
}
var groupCount int
// nodes that have been added to a group (that has been counted)
hasBeenGrouped := map[int]bool{}
for target := range graph {
if !hasBeenGrouped[target] {
// iterate through all graph nodes and check if they can be reached
for k := range graph {
// performance optimization: skip nodes that are already grouped
if k != target && !hasBeenGrouped[k] {
// if this group can reach the target, they're part of that group
if dfsCanReachTarget(graph, k, target, map[int]bool{}) {
hasBeenGrouped[k] = true
}
}
}
groupCount++
}
}
return groupCount
}
func dfsCanReachTarget(graph map[int][]int, entry int, target int, visited map[int]bool) bool {
// break infinite loops
if visited[entry] {
return false
}
visited[entry] = true
for _, child := range graph[entry] {
if child == target || dfsCanReachTarget(graph, child, target, visited) {
return true
}
}
// default to returning false
return false
}
func makeGraphFromInput(input string) map[int][]int {
lines := strings.Split(input, "\n")
graph := make(map[int][]int, len(lines))
for _, l := range lines {
parts := strings.Split(l, " <-> ")
ID := cast.ToInt(parts[0])
for _, child := range strings.Split(parts[1], ", ") {
graph[ID] = append(graph[ID], cast.ToInt(child))
}
}
return graph
}
|
maravichandran/evergreen
|
units/volume_deletion_job.go
|
<reponame>maravichandran/evergreen<gh_stars>0
package units
import (
"context"
"fmt"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/cloud"
"github.com/evergreen-ci/evergreen/model/host"
"github.com/mongodb/amboy"
"github.com/mongodb/amboy/dependency"
"github.com/mongodb/amboy/job"
"github.com/mongodb/amboy/registry"
"github.com/pkg/errors"
)
const (
volumeDeletionName = "volume-deletion"
)
func init() {
registry.AddJobType(volumeDeletionName,
func() amboy.Job { return makeVolumeDeletionJob() })
}
type volumeDeletionJob struct {
job.Base `bson:"job_base" json:"job_base" yaml:"job_base"`
VolumeID string `bson:"volume_id" yaml:"volume_id"`
Provider string `bson:"provider" yaml:"provider"`
volume *host.Volume
env evergreen.Environment
}
func makeVolumeDeletionJob() *volumeDeletionJob {
j := &volumeDeletionJob{
Base: job.Base{
JobType: amboy.JobType{
Name: volumeDeletionName,
Version: 0,
},
},
}
j.SetDependency(dependency.NewAlways())
return j
}
func NewVolumeDeletionJob(ts string, v *host.Volume) amboy.Job {
j := makeVolumeDeletionJob()
j.SetID(fmt.Sprintf("%s.%s", volumeDeletionName, ts))
j.VolumeID = v.ID
j.Provider = evergreen.ProviderNameEc2OnDemand
return j
}
func (j *volumeDeletionJob) Run(ctx context.Context) {
defer j.MarkComplete()
var err error
if j.env == nil {
j.env = evergreen.GetEnvironment()
}
if j.volume == nil {
j.volume, err = host.FindVolumeByID(j.VolumeID)
if err != nil {
j.AddError(errors.Wrapf(err, "error getting volume '%s'", j.VolumeID))
return
}
if j.volume == nil {
j.AddError(errors.Errorf("no volume '%s' exists", j.VolumeID))
return
}
}
mgrOpts := cloud.ManagerOpts{
Provider: j.Provider,
Region: cloud.AztoRegion(j.volume.AvailabilityZone),
}
mgr, err := cloud.GetManager(ctx, j.env, mgrOpts)
if err != nil {
j.AddError(errors.Wrapf(err, "can't get manager for volume '%s'", j.VolumeID))
return
}
if err := mgr.DeleteVolume(ctx, j.volume); err != nil {
j.AddError(errors.Wrapf(err, "can't delete volume '%s'", j.VolumeID))
return
}
return
}
|
galin-kostadinov/Software-Engineering
|
Java/Technology Fundamentals with Java/Exercises Java Code/src/AssociativeArraysMoreExercise/SnowWhite.java
|
package AssociativeArraysMoreExercise;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class SnowWhite {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String, Integer> dwarfs = new LinkedHashMap<>();
String input = "";
while (!"Once upon a time".equals(input = sc.nextLine())) {
String[] token = input.split("\\s*<:>\\s*".trim());
String dwarfName = token[0];
String dwarfHatColor = token[1];
int dwarfPhysics = Integer.parseInt(token[2]);
String id = dwarfHatColor + ":" + dwarfName;
if (!dwarfs.containsKey(id)) {
dwarfs.put(id, dwarfPhysics);
} else {
int currentDwarfPhysics = dwarfs.get(id);
if (dwarfPhysics > currentDwarfPhysics) {
dwarfs.put(id, dwarfPhysics);
}
}
}
dwarfs.entrySet()
.stream()
.sorted((d1, d2) -> {
int firstDwarfPhysics = d1.getValue();
int secondDwarfPhysics = d2.getValue();
int sort = Integer.compare(secondDwarfPhysics, firstDwarfPhysics);
if (sort == 0) {
String firstDwarfsColor = d1.getKey().split(":")[0];
String secondDwarfsColor = d2.getKey().split(":")[0];
long firstCount = dwarfs.entrySet()
.stream()
.filter(e -> e.getKey().split(":")[0].equals(firstDwarfsColor))
.count();
long secondCount = dwarfs.entrySet()
.stream()
.filter(e -> e.getKey().split(":")[0].equals(secondDwarfsColor))
.count();
sort = Long.compare(secondCount, firstCount);
}
return sort;
})
.forEach(e -> {
String hatColor = e.getKey().split(":")[0];
String name = e.getKey().split(":")[1];
int physics = e.getValue();
System.out.printf("(%s) %s <-> %d%n", hatColor, name, physics);
});
}
}
|
amaodou/quickstart-on-springboot
|
jpa/src/main/java/xyz/mdou/springboot/jpa/entity/DepartmentEntity.java
|
<filename>jpa/src/main/java/xyz/mdou/springboot/jpa/entity/DepartmentEntity.java
package xyz.mdou.springboot.jpa.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;
@Data
@Accessors(chain = true)
@Entity
@Table(name = "department")
public class DepartmentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "superior", referencedColumnName = "id")
private DepartmentEntity superior;
private Integer level;
@OneToMany(cascade = {CascadeType.REFRESH, CascadeType.REMOVE}, fetch = FetchType.EAGER,
mappedBy = "superior")
private List<DepartmentEntity> children;
@ManyToMany(mappedBy = "departments")
private List<UserEntity> users;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date", updatable = false)
private Date createDate;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "update_date")
private Date updateDate;
@Override
public String toString() {
return new StringJoiner(", ", DepartmentEntity.class.getSimpleName() + "[", "]")
.add("id=" + id)
.add("name='" + name + "'")
.add("superior='" + Optional.ofNullable(superior).map(DepartmentEntity::getId).orElse(null) + "'")
.add("level=" + level)
.add("children='" + Optional.ofNullable(children).orElse(Collections.emptyList()).stream().map(DepartmentEntity::getId).collect(Collectors.toList()) + "'")
.add("createDate=" + createDate)
.add("updateDate=" + updateDate)
.toString();
}
}
|
UnrealKaraulov/DotaAllstarsHelper_DLL_FOR_DOTA
|
ExampleViewAllySkillPanel_src_backup/DreamUI/Label.h
|
<reponame>UnrealKaraulov/DotaAllstarsHelper_DLL_FOR_DOTA
#ifndef LABEL_H_
#define LABEL_H_
#include "Frame.h"
class Texture;
class UISimpleFontString;
class UISimpleTexture;
static Color LABEL_TEXT_COLOR = Color(0.99f, 0.827f, 0.0705f);
static Color LABEL_SHADOW_COLOR = Color(0.f, 0.f, 0.f, 0.9f);
static Color LABEL_TEXT_DISABLED_COLOR = Color::GREY;
class Label : public Frame
{
public:
Label (
IUIObject *parent,
const char *text,
float textSize,
Color textColor = LABEL_TEXT_COLOR,
Color textDisabledColor = LABEL_TEXT_DISABLED_COLOR,
Color shadowColor = LABEL_SHADOW_COLOR,
const char *fontPath = NULL,
bool withBackground = false
);
Label (
UISimpleFrame *parent,
const char *text,
float textSize,
Color textColor = LABEL_TEXT_COLOR,
Color textDisabledColor = LABEL_TEXT_DISABLED_COLOR,
Color shadowColor = LABEL_SHADOW_COLOR,
const char *fontPath = NULL,
bool withBackground = false
);
virtual ~Label ( );
char* getText ( ) const;
float getTextWidth( ) const;
float getTextHeight( ) const;
void showBackground ( bool flag );
void setFont ( const char *fontPath );
bool setText ( const char *format, ... );
void setTextSize ( float size );
void setTextColor ( Color textColor, Color textDisabledColor = LABEL_TEXT_DISABLED_COLOR, Color shadowColor = LABEL_SHADOW_COLOR );
virtual void setScale ( float scale );
virtual void activate ( bool flag );
virtual void tick ( );
virtual void refresh ( );
private:
UISimpleTexture *lbBackground;
UISimpleFontString *lbText;
UISimpleFontString *lbTextShadow[8];
std::string lbTextContent;
std::string lbTextFontPath;
float lbTextSize;
bool bWantShowBackground;
Color lbTextColor;
Color lbTextDisabledColor;
Color lbTextShadowColor;
bool bWantApplyUpdate;
void initLabel(const char *text, const char *fontPath, bool withBackground, float textSize);
};
#endif
|
vibhatha/dapwc
|
src/main/java/edu/indiana/soic/spidal/dapwc/PlotVizCluster.java
|
<reponame>vibhatha/dapwc
package edu.indiana.soic.spidal.dapwc;
public class PlotVizCluster
{
private int _clusterNumber;
private String _label;
public PlotVizCluster(int clusterNumber, String label)
{
_clusterNumber = clusterNumber;
_label = label;
}
public PlotVizCluster(int clusterNumber)
{
_clusterNumber = clusterNumber;
}
public PlotVizCluster(String label)
{
_label = label;
}
public final int getClusterNumber()
{
return _clusterNumber;
}
public final void setClusterNumber(int value)
{
_clusterNumber = value;
}
public final String getLabel()
{
return _label;
}
public final void setLabel(String value)
{
_label = value;
}
// TODO - fix plotviz cluster
/*public final XElement ToClusterElement(Color color, boolean isDefault, double size)
{
return new XElement("cluster", new XElement("key", _clusterNumber), new XElement("label", _label), new XElement("visible", 1), new XElement("default", isDefault ? 1 : 0), new XElement("color", new XAttribute("r", color.R), new XAttribute("g", color.G), new XAttribute("b", color.B), new XAttribute("a", color.A)), new XElement("size", size));
}*/
}
|
kpchad/mira-unity-sdk
|
Assets/Plugins/iOS/Wikitude/WikitudeMiraSDK.framework/Headers/WTCloudRecognitionService.h
|
//
// WTCloudRecognitionService.h
// WikitudeNativeSDK
//
// Created by <NAME> on 31/10/16.
// Copyright © 2016 Wikitude. All rights reserved.
//
#ifndef WTCloudRecognitionService_h
#define WTCloudRecognitionService_h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
extern NSString * __nonnull const WTCloudRecognitionServiceResponseKey_TargetName;
extern NSString * __nonnull const WTCloudRecognitionServiceResponseKey_TargetRating;
@class WTCloudRecognitionServiceResponse;
/**
* WTCloudRecognitionServiceInitializationHandler represents a block object which is invoked when the cloud recognition service finished its initialization, either successfully, or with an error.
*/
typedef void(^WTCloudRecognitionServiceInitializationHandler)(BOOL success, NSError* _Nullable error);
/**
* WTCloudRecognitionServiceHandler represents a block object which is invoked when the cloud recognition service receives a valid response from the server or an error occurred when communicating with it.
*/
typedef void(^WTCloudRecognitionServiceHandler)(WTCloudRecognitionServiceResponse* _Nullable response, NSError* _Nullable error);
/**
* WTCloudRecognitionServiceHandler represents a block object which is called every time a new cloud recognition request is invoked, but the previous one did not finish yet.
*/
typedef void(^WTContinuousCloudRecognitionServiceInterruptionHandler)(NSTimeInterval suggestedTimeInterval);
/**
* Represents a connection to the Wikitude cloud recognition servers that was initialized with a client token and a target collection id
*
* Cloud recognition services use a cloud target collection which can be created using a REST JavaScript API or the Wikitude Target Manager. Once such a cloud target collection id was created, it can be loaded using a cloud recognitions ervice.
*
* @discussion The cloud recognition service requires a continuous internet connection in order to communicate with the Wikitude cloud recognition server.
*/
@interface WTCloudRecognitionService : NSObject
/**
* @brief Represents the client token that was used to initialize this cloud recognition service and should correspond to the one that is associated with your Wikitude cloud recognition account.
*/
@property (nonatomic, copy, readonly) NSString *clientToken;
/**
* @brief Represents the target collection id that was used to initialize this cloud recognition service and should correspond to the target collection that should be loaded on the Wikitude cloud recognition server.
*/
@property (nonatomic, copy, readonly) NSString *targetCollectionId;
/**
* @brief Represents if the communication with the cloud recognition servers could be initialized or not.
*/
@property (nonatomic, assign, readonly) BOOL initialized;
/**
* @brief Triggers a single device/server communication to find out if a image target occurs in the current camera frame
*
* @discussion This method can be used to trigger a single cloud recognition session. This includes capturing the current camera frame, sending it to the Wikitude cloud recognition server, evaluate the frame and sending back the response. If the server could process the camera frame, the recognitionHandler is called with a nonnull value for the response parameter, independent of the evaluation result. One can use this paramater, of type WTCloudRecognitionServiceResponse, to retrieve more information about the server processing. If no connection to the server could be established or any other problem occured, the first parameter of the recognitionHandler will be nil and the second parameter will contain a valid NSError object with more information about what went wrong.
*
* @param recognitionHandler A block object that handles events regarding the device/server communication
*/
- (void)recognize:(WTCloudRecognitionServiceHandler)recognitionHandler;
/**
* @brief Starts a continuous cloud recognition session
*
* @discussion Calling this method does essentially the same as a single call to -recognize:errorHandler, but repeats this with the given interval. If the given interval is too short and the previous request hasn't finished when the next one should be send, the interruption handler is called with a newly suggested interval. So within the interruption handler, the current continuous recognition session should be stopped and started again with the given interval. If not, requests will be dropped.
*
* @param interval The interval in which new camera frames should be send to the Wikitude cloud recognition server
* @param interruptionHandler A block object that is invoked every time the given interval is to short in order to process one request after the other.
* @param recognitionHandler A block object that handles events regarding the device/server communication
*/
- (void)startContinuousRecognitionWithInterval:(NSTimeInterval)interval interruptionHandler:(nullable WTContinuousCloudRecognitionServiceInterruptionHandler)interruptionHandler responseHandler:(nonnull WTCloudRecognitionServiceHandler)recognitionHandler NS_SWIFT_NAME(startContinuousRecognition(withInterval:interruptionHandler:responseHandler:));
/**
* @brief Stops the current continuous recognition session
*
* Calling this method will immediately stop any new device/server communication but still deliver the result from any, currently ongoing, device/server communication
*/
- (void)stopContinuousRecognition;
@end
NS_ASSUME_NONNULL_END
#endif /* WTCloudRecognitionService_h */
|
lrbInfelink/FelinkAdDemo
|
Pods/FelinkAdSDK/FelinkAdSDK.framework/Headers/FelinkAgInterstitial.h
|
//
// FelinkAgInterstitial.h
// FelinkAdSDK
//
// Created by 刘瑞彬 on 2019/6/21.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "FelinkAdCommon.h"
@class FelinkAgInterstitial;
@protocol FelinkAgInterstitialDelegate <NSObject>
//收到广告
- (void)felinkAgInterstitialDidReceiveAd:(FelinkAgInterstitial *)ad;
//成功展示广告
- (void)felinkAgInterstitialSuccessPresentScreen:(FelinkAgInterstitial *)ad;
//广告失败
- (void)felinkAgInterstitialFail:(FelinkAgInterstitial *)ad error:(NSError *)error;
// 广告被点击
- (void)felinkAgInterstitialClicked:(FelinkAgInterstitial *)ad;
//结束广告
- (void)felinkAgInterstitialDidDismissScreen:(FelinkAgInterstitial *)ad;
//结束广告详细页
- (void)felinkAgInterstitialDidDismissDetail:(FelinkAgInterstitial *)ad;
// 广告跳到用户处理 若开发者处理该事件 返回YES;否则返回 NO,SDK会处理
- (BOOL)felinkAgInterstitialDirectClicked:(FelinkAgInterstitial *)ad data:(NSDictionary *)data;
//用户关闭广告
- (void)felinkAgInterstitialDidClose:(FelinkAgInterstitial *)ad;
@end
@interface FelinkAgInterstitial : NSObject
@property (nonatomic ,weak) id<FelinkAgInterstitialDelegate> delegate;
/**
获取代码位id
*/
@property (nonatomic,readonly,copy) NSString* adPid;
/**
* 广告正在请求中
*/
@property (nonatomic,readonly,assign) BOOL adRequesting;
/**
* hidesBottomBarWhenPushed 等
*只对风灵自己广告有效,对第三方SDK无效
*/
@property (nonatomic, strong) NSDictionary *extraProperties;
/**
初值
@param adPid 广告位
@param timeout 请求数据超时 建议3秒
*/
-(instancetype)initWithAdPid:(NSString *)adPid timeout:(NSTimeInterval)timeout;
/**
* 请求广告
*/
-(void)requestAd;
/**
* 展示广告,在调用之前 请先调用isAdValid
*/
-(void)showFromViewController:(UIViewController *)vc;
/**
* 插屏广告预加载是否完成
*/
@property (nonatomic, readonly) BOOL isAdValid;
/*
* 收到广告后
* 1.获取直投定制信息
*/
-(NSDictionary *)getCurrentAdExtInfo;
@end
|
adryanefernandes/Labex
|
src/hooks/useRequestDataAuth.js
|
import axios from "axios"
import { useEffect, useState } from "react"
import { urlApi } from '../apiConfig/axiosConfig'
const useRequestDataAuth = (urlFinal, initialState) => {
const [data, setData] = useState(initialState)
useEffect(() => {
axios.get(`${urlApi}${urlFinal}`, {
headers: {
auth: window.localStorage.getItem('token')
}
})
.then((res) => setData(res.data))
.catch((err) => console.log(err))
}, [urlFinal, data])
return data
}
export default useRequestDataAuth
|
swanandmehta/all-my-chat
|
backend/src/main/java/com/liberty/chat/modal/Message.java
|
<filename>backend/src/main/java/com/liberty/chat/modal/Message.java
/**
*
*/
package com.liberty.chat.modal;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import com.liberty.chat.enums.Role;
/**
* @author Swanand
*
*/
@Entity
@Table(name = "message")
public class Message implements IEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "uuid", nullable = false)
private String uuid;
@Column(name = "timestamp", nullable = false, updatable = false)
private LocalDateTime timestamp;
@Column(name = "topicId", nullable = false, updatable = false)
private String topicId;
@Column(name = "content", nullable = false, updatable = false)
private String content;
@Enumerated(EnumType.STRING)
@Column(name = "role", nullable = false, updatable = false)
private Role role;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public String getTopicId() {
return topicId;
}
public void setTopicId(String topicId) {
this.topicId = topicId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
|
persona-id/blockscore-ruby
|
spec/unit/block_score/util_spec.rb
|
<filename>spec/unit/block_score/util_spec.rb
RSpec.describe BlockScore::Util, vcr: true do
shared_context 'a transform' do
subject(:actual) { described_class.send(method, input) }
it { should eql(output) }
end
describe '.to_plural' do
shared_context 'to_plural' do
let(:method) { :to_plural }
include_context 'a transform'
end
context 'candidate' do
let(:input) { 'candidate' }
let(:output) { 'candidates' }
it_behaves_like 'to_plural'
end
context 'question_set' do
let(:input) { 'question_set' }
let(:output) { 'question_sets' }
it_behaves_like 'to_plural'
end
context 'company' do
let(:input) { 'company' }
let(:output) { 'companies' }
it_behaves_like 'to_plural'
end
context 'person' do
let(:input) { 'person' }
let(:output) { 'people' }
it_behaves_like 'to_plural'
end
context 'watchlist_hit' do
let(:input) { 'watchlist_hit' }
let(:output) { 'watchlist_hits' }
it_behaves_like 'to_plural'
end
end
describe '.to_camelcase' do
shared_context 'to_camelcase' do
let(:method) { :to_camelcase }
include_context 'a transform'
end
context 'screaming_snake_case' do
let(:input) { 'screaming_snake_case' }
let(:output) { 'ScreamingSnakeCase' }
it_behaves_like 'to_camelcase'
end
context 'snake_case' do
let(:input) { 'snake_case' }
let(:output) { 'SnakeCase' }
it_behaves_like 'to_camelcase'
end
context 'foo' do
let(:input) { 'foo' }
let(:output) { 'Foo' }
it_behaves_like 'to_camelcase'
end
context 'empty string' do
let(:input) { '' }
let(:output) { '' }
it_behaves_like 'to_camelcase'
end
end
describe '.parse_json' do
shared_context 'parse_json' do
let(:method) { :parse_json }
include_context 'a transform'
end
context 'valid input' do
let(:input) { output.to_json }
let(:output) { { foo: 'bar', baz: 'bat' } }
it_behaves_like 'parse_json'
end
context 'translates errors' do
let(:error) do
'An error has occurred. ' \
'If this problem persists, please message <EMAIL>.'
end
let(:input) { '{{' }
subject(:parse_attempt) { described_class.parse_json(input) }
it 'raises an error when the json fails to parse' do
expect { subject }.to raise_error do |err|
expect(err).to be_an_instance_of(BlockScore::Error)
expect(err.message).to eql(error)
end
end
end
end
end
|
Spongebobgao/fitness-tracker
|
client/src/store/store.js
|
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
// import MyFriends from '../components/MyFriends'
Vue.use(Vuex)
export default new Vuex.Store({
strict: true,
state: {
token: null,
user: null,
isUserLoggedIn: false,
redirectRoute: {
name: null,
params: {
id: null
}
}
},
mutations: {
setToken (state, token) {
state.token = token
if (token) {
state.isUserLoggedIn = true
} else {
state.isUserLoggedIn = false
}
},
setUser (state, user) {
state.user = user
},
setRedirectRoute (state, redirectRoute) {
state.redirectRoute = redirectRoute
}
},
actions: {
setToken ({ commit }, token) {
commit('setToken', token)
},
setUser ({ commit }, user) {
commit('setUser', user)
},
setRedirectRoute ({ commit }, redirectRoute) {
commit('setRedirectRoute', redirectRoute)
}
},
/* modules: {
MyFriends: MyFriends
}, */
plugins: [createPersistedState()]
})
|
jacokoo/sleetjs
|
lib/ast/attribute.js
|
<reponame>jacokoo/sleetjs<filename>lib/ast/attribute.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Attribute = exports.Attribute = function () {
function Attribute(name, value, namespace) {
_classCallCheck(this, Attribute);
this._name = name;
this._value = value;
this._namespace = namespace || '';
}
_createClass(Attribute, [{
key: 'type',
get: function get() {
return 'attribute';
}
}, {
key: 'name',
get: function get() {
return this._name;
}
}, {
key: 'value',
get: function get() {
return this._value;
}
}, {
key: 'namespace',
get: function get() {
return this._namespace;
}
}, {
key: 'minor',
get: function get() {
if (!this._name && this._value.length === 1 && this._value[0].minor === 'identifier') {
return this._value[0].value;
}
return null;
}
}, {
key: 'major',
set: function set(m) {
this._major = m;
this._value.forEach(function (v) {
return v.major = m;
}); // eslint-disable-line no-param-reassign
},
get: function get() {
return this._major;
}
}]);
return Attribute;
}();
var AttributeContainer = function () {
function AttributeContainer(attributes, major) {
_classCallCheck(this, AttributeContainer);
this._attributes = attributes;
attributes.forEach(function (attr) {
return attr.major = major;
}); // eslint-disable-line no-param-reassign
}
_createClass(AttributeContainer, [{
key: 'attributes',
get: function get() {
return this._attributes;
}
}]);
return AttributeContainer;
}();
Attribute.Setting = function (_AttributeContainer) {
_inherits(Settings, _AttributeContainer);
function Settings(name, attributes) {
_classCallCheck(this, Settings);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Settings).call(this, attributes, 'setting'));
_this._name = name;
return _this;
}
_createClass(Settings, [{
key: 'type',
get: function get() {
return 'setting';
}
}, {
key: 'name',
get: function get() {
return this._name;
}
}]);
return Settings;
}(AttributeContainer);
function _merge(target, source) {
source.forEach(function (item) {
var attr = target.find(function (i) {
return i.name && i.name === item.name;
});
attr ? attr._value = attr._value.concat(item._value) : target.push(item);
});
return target;
}
Attribute.Group = function (_AttributeContainer2) {
_inherits(Group, _AttributeContainer2);
function Group(attributes, setting) {
_classCallCheck(this, Group);
var _this2 = _possibleConstructorReturn(this, Object.getPrototypeOf(Group).call(this, _merge([], attributes)));
_this2._setting = setting;
return _this2;
}
_createClass(Group, [{
key: 'merge',
value: function merge(group) {
if (group.setting) return false;
_merge(this._attributes, group._attributes);
return true;
}
}, {
key: 'type',
get: function get() {
return 'group';
}
}, {
key: 'setting',
get: function get() {
return this._setting;
}
}]);
return Group;
}(AttributeContainer);
var Value = function () {
function Value() {
_classCallCheck(this, Value);
}
_createClass(Value, [{
key: 'type',
get: function get() {
return 'value';
}
}, {
key: 'minor',
get: function get() {
return this._minor;
}
}, {
key: 'value',
get: function get() {
return this._value;
}
}, {
key: 'major',
get: function get() {
return this._major;
},
set: function set(m) {
this._major = m;
}
}]);
return Value;
}();
Attribute.Quoted = function (_Value) {
_inherits(Quoted, _Value);
function Quoted(value) {
_classCallCheck(this, Quoted);
var _this3 = _possibleConstructorReturn(this, Object.getPrototypeOf(Quoted).call(this));
_this3._value = value;
_this3._minor = 'quoted';
return _this3;
}
return Quoted;
}(Value);
Attribute.Number = function (_Value2) {
_inherits(Number, _Value2);
function Number(value) {
_classCallCheck(this, Number);
var _this4 = _possibleConstructorReturn(this, Object.getPrototypeOf(Number).call(this));
_this4._value = value;
_this4._minor = 'number';
return _this4;
}
return Number;
}(Value);
Attribute.Boolean = function (_Value3) {
_inherits(Boolean, _Value3);
function Boolean(value) {
_classCallCheck(this, Boolean);
var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(Boolean).call(this));
_this5._value = value;
_this5._minor = 'boolean';
return _this5;
}
return Boolean;
}(Value);
Attribute.Identifier = function (_Value4) {
_inherits(Identifier, _Value4);
function Identifier(value) {
_classCallCheck(this, Identifier);
var _this6 = _possibleConstructorReturn(this, Object.getPrototypeOf(Identifier).call(this));
_this6._value = value;
_this6._minor = 'identifier';
return _this6;
}
return Identifier;
}(Value);
Attribute.Helper = function (_Value5) {
_inherits(Helper, _Value5);
function Helper(name, attributes) {
_classCallCheck(this, Helper);
var _this7 = _possibleConstructorReturn(this, Object.getPrototypeOf(Helper).call(this));
_this7._value = '';
_this7._attributes = attributes;
_this7._minor = 'helper';
_this7._name = name;
attributes.forEach(function (attr) {
return attr.major = 'helper';
}); // eslint-disable-line no-param-reassign
return _this7;
}
_createClass(Helper, [{
key: 'name',
get: function get() {
return this._name;
}
}, {
key: 'attributes',
get: function get() {
return this._attributes;
}
}]);
return Helper;
}(Value);
|
IniZio/py-skygear
|
skygear/settings/tests/test_parser.py
|
<filename>skygear/settings/tests/test_parser.py
# Copyright 2015 Oursky Ltd.
#
# 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 os
import unittest
from unittest.mock import patch
from .. import Namespace, SettingsParser
class TestSettingsParser(unittest.TestCase):
def setUp(self):
self.parser = SettingsParser('PARSER_PREFIX')
def tearDown(self):
self.parser = None
@patch.dict(os.environ, {'TEST_VAR': 'yes'})
def test_var(self):
self.parser.add_setting('test_var')
assert self.parser.parse_settings().test_var == 'yes'
def test_var_with_default(self):
self.parser.add_setting('test_var', default='yes')
assert self.parser.parse_settings().test_var == 'yes'
def test_var_unspecified(self):
self.parser.add_setting('test_var')
with self.assertRaises(Exception):
self.parser.parse_settings().test_var
def test_var_unspecified_ignored(self):
self.parser.add_setting('test_var', required=False)
assert self.parser.parse_settings().test_var is None
@patch.dict(os.environ, {'ANOTHER_VAR': 'yes'})
def test_var_explicit(self):
self.parser.add_setting('test_var', env_var='ANOTHER_VAR')
assert self.parser.parse_settings().test_var == 'yes'
@patch.dict(os.environ, {'PARSER_PREFIX_TEST_VAR': 'no',
'TEST_VAR': 'yes'})
def test_var_correct_resolve(self):
self.parser.add_setting('test_var')
assert self.parser.parse_settings().test_var == 'no'
@patch.dict(os.environ, {'TEST_VAR': 'yes'})
def test_var_unresolved(self):
self.parser.add_setting('test_var', resolve=False)
with self.assertRaises(Exception):
self.parser.parse_settings().test_var
@patch.dict(os.environ, {'TEST_VAR': '42'})
def test_var_int(self):
self.parser.add_setting('test_var', atype=int)
assert self.parser.parse_settings().test_var == 42
def test_var_existing_namespace(self):
self.parser.add_setting('test_var', default='yes')
ns = Namespace()
setattr(ns, 'existing', 'no')
assert self.parser.parse_settings(ns) is ns
assert ns.existing == 'no'
assert ns.test_var == 'yes'
|
KEP-SERVDEV-FRONT/svelte-linda
|
node_modules/snowpack/lib/commands/dev.js
|
"use strict";
/**
* This license applies to parts of this file originating from the
* https://github.com/lukejacksonn/servor repository:
*
* MIT License
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.command = exports.startDevServer = void 0;
const cacache_1 = __importDefault(require("cacache"));
const compressible_1 = __importDefault(require("compressible"));
const deepmerge_1 = __importDefault(require("deepmerge"));
const etag_1 = __importDefault(require("etag"));
const events_1 = require("events");
const fs_1 = require("fs");
const http_1 = __importDefault(require("http"));
const http_proxy_1 = __importDefault(require("http-proxy"));
const http2_1 = __importDefault(require("http2"));
const https_1 = __importDefault(require("https"));
const colors = __importStar(require("kleur/colors"));
const mime_types_1 = __importDefault(require("mime-types"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const perf_hooks_1 = require("perf_hooks");
const signal_exit_1 = __importDefault(require("signal-exit"));
const stream_1 = __importDefault(require("stream"));
const url_1 = __importDefault(require("url"));
const util_1 = __importDefault(require("util"));
const zlib_1 = __importDefault(require("zlib"));
const build_import_proxy_1 = require("../build/build-import-proxy");
const build_pipeline_1 = require("../build/build-pipeline");
const import_resolver_1 = require("../build/import-resolver");
const file_urls_1 = require("../build/file-urls");
const hmr_server_engine_1 = require("../hmr-server-engine");
const logger_1 = require("../logger");
const rewrite_imports_1 = require("../rewrite-imports");
const scan_imports_1 = require("../scan-imports");
const util_2 = require("../util");
const install_1 = require("./install");
const paint_1 = require("./paint");
const isbinaryfile_1 = require("isbinaryfile");
const FILE_BUILD_RESULT_ERROR = `Build Result Error: There was a problem with a file build result.`;
/**
* If encoding is defined, return a string. Otherwise, return a Buffer.
*/
function encodeResponse(response, encoding) {
if (encoding === undefined) {
return response;
}
if (encoding) {
if (typeof response === 'string') {
return response;
}
else {
return response.toString(encoding);
}
}
if (typeof response === 'string') {
return Buffer.from(response);
}
else {
return response;
}
}
function getCacheKey(fileLoc, { isSSR, env }) {
return `${fileLoc}?env=${env}&isSSR=${isSSR ? '1' : '0'}`;
}
const DEFAULT_PROXY_ERROR_HANDLER = (err, req, res) => {
const reqUrl = req.url;
logger_1.logger.error(`✘ ${reqUrl}\n${err.message}`);
sendResponseError(req, res, 502);
};
/**
* A helper class for "Not Found" errors, storing data about what file lookups were attempted.
*/
class NotFoundError extends Error {
constructor(lookups) {
super('NOT_FOUND');
this.lookups = lookups;
}
}
/**
* Install dependencies needed in "dev" mode. Generally speaking, this scans
* your entire source app for dependency install targets, installs them,
* and then updates the "hash" file used to check node_modules freshness.
*/
async function installDependencies(commandOptions) {
const { config } = commandOptions;
const installTargets = await install_1.getInstallTargets(config);
if (installTargets.length === 0) {
logger_1.logger.info('Nothing to install.');
return;
}
// 2. Install dependencies, based on the scan of your final build.
const installResult = await install_1.run({
...commandOptions,
installTargets,
config,
shouldPrintStats: true,
shouldWriteLockfile: false,
});
await util_2.updateLockfileHash(util_2.DEV_DEPENDENCIES_DIR);
return installResult;
}
function shouldProxy(pathPrefix, reqUrl) {
const reqPath = decodeURI(url_1.default.parse(reqUrl).pathname);
return reqPath.startsWith(pathPrefix);
}
function sendResponseFile(req, res, { contents, originalFileLoc, responseFileName }) {
var _a;
const body = Buffer.from(contents);
const ETag = etag_1.default(body, { weak: true });
const contentType = mime_types_1.default.contentType(responseFileName);
const headers = {
'Accept-Ranges': 'bytes',
'Access-Control-Allow-Origin': '*',
'Content-Type': contentType || 'application/octet-stream',
ETag,
Vary: 'Accept-Encoding',
};
if (req.headers['if-none-match'] === ETag) {
res.writeHead(304, headers);
res.end();
return;
}
let acceptEncoding = req.headers['accept-encoding'] || '';
if (((_a = req.headers['cache-control']) === null || _a === void 0 ? void 0 : _a.includes('no-transform')) ||
['HEAD', 'OPTIONS'].includes(req.method) ||
!contentType ||
!compressible_1.default(contentType)) {
acceptEncoding = '';
}
// Handle gzip compression
if (/\bgzip\b/.test(acceptEncoding) && stream_1.default.Readable.from) {
const bodyStream = stream_1.default.Readable.from([body]);
headers['Content-Encoding'] = 'gzip';
res.writeHead(200, headers);
stream_1.default.pipeline(bodyStream, zlib_1.default.createGzip(), res, function onError(err) {
if (err) {
res.end();
logger_1.logger.error(`✘ An error occurred serving ${colors.bold(req.url)}`);
logger_1.logger.error(typeof err !== 'string' ? err.toString() : err);
}
});
return;
}
// Handle partial requests
// TODO: This throws out a lot of hard work, and ignores any build. Improve.
const { range } = req.headers;
if (range) {
if (!originalFileLoc) {
throw new Error('Virtual files do not support partial requests');
}
const { size: fileSize } = fs_1.statSync(originalFileLoc);
const [rangeStart, rangeEnd] = range.replace(/bytes=/, '').split('-');
const start = parseInt(rangeStart, 10);
const end = rangeEnd ? parseInt(rangeEnd, 10) : fileSize - 1;
const chunkSize = end - start + 1;
const fileStream = fs_1.createReadStream(originalFileLoc, { start, end });
res.writeHead(206, {
...headers,
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Content-Length': chunkSize,
});
fileStream.pipe(res);
return;
}
res.writeHead(200, headers);
res.write(body);
res.end();
}
function sendResponseError(req, res, status) {
const contentType = mime_types_1.default.contentType(path_1.default.extname(req.url) || '.html');
const headers = {
'Access-Control-Allow-Origin': '*',
'Accept-Ranges': 'bytes',
'Content-Type': contentType || 'application/octet-stream',
Vary: 'Accept-Encoding',
};
res.writeHead(status, headers);
res.end();
}
function handleResponseError(req, res, err) {
var _a;
if (err instanceof NotFoundError) {
// Don't log favicon "Not Found" errors. Browsers automatically request a favicon.ico file
// from the server, which creates annoying errors for new apps / first experiences.
if (req.path !== '/favicon.ico') {
const attemptedFilesMessage = err.lookups.map((loc) => ' ✘ ' + loc).join('\n');
logger_1.logger.error(`[404] ${req.url}\n${attemptedFilesMessage}`);
}
sendResponseError(req, res, 404);
return;
}
logger_1.logger.error(err.toString());
logger_1.logger.error(`[500] ${req.url}`, {
// @ts-ignore
name: (_a = err.__snowpackBuildDetails) === null || _a === void 0 ? void 0 : _a.name,
});
sendResponseError(req, res, 500);
return;
}
async function startDevServer(commandOptions) {
// Start the startup timer!
let serverStart = perf_hooks_1.performance.now();
const { cwd, config } = commandOptions;
const { port: defaultPort, hostname, open } = config.devOptions;
const messageBus = new events_1.EventEmitter();
const port = await paint_1.getPort(defaultPort);
// Reset the clock if we had to wait for the user prompt to select a new port.
if (port !== defaultPort) {
serverStart = perf_hooks_1.performance.now();
}
// Fill in any command-specific plugin methods.
for (const p of config.plugins) {
p.markChanged = (fileLoc) => {
knownETags.clear();
onWatchEvent(fileLoc);
};
}
if (config.devOptions.output === 'dashboard') {
// "dashboard": Pipe console methods to the logger, and then start the dashboard.
logger_1.logger.debug(`attaching console.log listeners`);
console.log = (...args) => {
logger_1.logger.info(util_1.default.format(...args));
};
console.warn = (...args) => {
logger_1.logger.warn(util_1.default.format(...args));
};
console.error = (...args) => {
logger_1.logger.error(util_1.default.format(...args));
};
paint_1.paintDashboard(messageBus, config.plugins.map((p) => p.name));
logger_1.logger.debug(`dashboard started`);
}
else {
// "stream": Log relevent events to the console.
messageBus.on(paint_1.paintEvent.WORKER_MSG, ({ id, msg }) => {
logger_1.logger.info(msg.trim(), { name: id });
});
messageBus.on(paint_1.paintEvent.SERVER_START, (info) => {
console.log(paint_1.getServerInfoMessage(info));
});
}
const inMemoryBuildCache = new Map();
const filesBeingDeleted = new Set();
const filesBeingBuilt = new Map();
logger_1.logger.debug(`Using in-memory cache.`);
logger_1.logger.debug(`Mounting directories:`, {
task: () => {
for (const [mountKey, mountEntry] of Object.entries(config.mount)) {
logger_1.logger.debug(` -> '${mountKey}' as URL '${mountEntry.url}'`);
}
},
});
// Set the proper install options, in case an install is needed.
const dependencyImportMapLoc = path_1.default.join(util_2.DEV_DEPENDENCIES_DIR, 'import-map.json');
logger_1.logger.debug(`Using cache folder: ${path_1.default.relative(cwd, util_2.DEV_DEPENDENCIES_DIR)}`);
const installCommandOptions = deepmerge_1.default(commandOptions, {
config: {
installOptions: {
dest: util_2.DEV_DEPENDENCIES_DIR,
env: { NODE_ENV: process.env.NODE_ENV || 'development' },
treeshake: false,
},
},
});
// Start with a fresh install of your dependencies, if needed.
let dependencyImportMap = { imports: {} };
try {
dependencyImportMap = JSON.parse(await fs_1.promises.readFile(dependencyImportMapLoc, { encoding: 'utf-8' }));
}
catch (err) {
// no import-map found, safe to ignore
}
if (!(await util_2.checkLockfileHash(util_2.DEV_DEPENDENCIES_DIR)) || !fs_1.existsSync(dependencyImportMapLoc)) {
logger_1.logger.debug('Cache out of date or missing. Updating...');
const installResult = await installDependencies(installCommandOptions);
dependencyImportMap = (installResult === null || installResult === void 0 ? void 0 : installResult.importMap) || dependencyImportMap;
}
else {
logger_1.logger.debug(`Cache up-to-date. Using existing cache`);
}
const devProxies = {};
config.proxy.forEach(([pathPrefix, proxyOptions]) => {
const proxyServer = (devProxies[pathPrefix] = http_proxy_1.default.createProxyServer(proxyOptions));
for (const [onEventName, eventHandler] of Object.entries(proxyOptions.on)) {
proxyServer.on(onEventName, eventHandler);
}
if (!proxyOptions.on.error) {
proxyServer.on('error', DEFAULT_PROXY_ERROR_HANDLER);
}
logger_1.logger.info(`Proxy created: ${pathPrefix} -> ${proxyOptions.target || proxyOptions.forward}`);
});
const readCredentials = async (cwd) => {
const [cert, key] = await Promise.all([
fs_1.promises.readFile(path_1.default.join(cwd, 'snowpack.crt')),
fs_1.promises.readFile(path_1.default.join(cwd, 'snowpack.key')),
]);
return {
cert,
key,
};
};
let credentials;
if (config.devOptions.secure) {
try {
logger_1.logger.debug(`reading credentials`);
credentials = await readCredentials(cwd);
}
catch (e) {
logger_1.logger.error(`✘ No HTTPS credentials found! Missing Files: ${colors.bold('snowpack.crt')}, ${colors.bold('snowpack.key')}`);
logger_1.logger.info(`You can automatically generate credentials for your project via either:
- ${colors.cyan('devcert')}: ${colors.yellow('npx devcert-cli generate localhost')}
https://github.com/davewasmer/devcert-cli (no install required)
- ${colors.cyan('mkcert')}: ${colors.yellow('mkcert -install && mkcert -key-file snowpack.key -cert-file snowpack.crt localhost')}
https://github.com/FiloSottile/mkcert (install required)`);
process.exit(1);
}
}
for (const runPlugin of config.plugins) {
if (runPlugin.run) {
logger_1.logger.debug(`starting ${runPlugin.name} run() in watch/isDev mode`);
runPlugin
.run({
isDev: true,
// @deprecated: no longer accurate when using the JS API
isHmrEnabled: typeof config.devOptions.hmr !== 'undefined' ? config.devOptions.hmr : true,
// @ts-ignore: internal API only
log: (msg, data) => {
if (msg === 'CONSOLE_INFO') {
logger_1.logger.info(data.msg, { name: runPlugin.name });
}
else {
messageBus.emit(msg, { ...data, id: runPlugin.name });
}
},
})
.then(() => {
logger_1.logger.info('Command completed.', { name: runPlugin.name });
})
.catch((err) => {
logger_1.logger.error(`Command exited with error code: ${err}`, { name: runPlugin.name });
process.exit(1);
});
}
}
async function loadUrl(reqUrl, { isSSR: _isSSR, isHMR: _isHMR, allowStale: _allowStale, encoding: _encoding, } = {}) {
var _a;
const isSSR = _isSSR !== null && _isSSR !== void 0 ? _isSSR : false;
// Default to HMR on, but disable HMR if SSR mode is enabled.
const isHMR = _isHMR !== null && _isHMR !== void 0 ? _isHMR : (((_a = config.devOptions.hmr) !== null && _a !== void 0 ? _a : true) && !isSSR);
const allowStale = _allowStale !== null && _allowStale !== void 0 ? _allowStale : false;
const encoding = _encoding !== null && _encoding !== void 0 ? _encoding : null;
const reqUrlHmrParam = reqUrl.includes('?mtime=') && reqUrl.split('?')[1];
let reqPath = decodeURI(url_1.default.parse(reqUrl).pathname);
const originalReqPath = reqPath;
let isProxyModule = false;
let isSourceMap = false;
if (reqPath.endsWith('.proxy.js')) {
isProxyModule = true;
reqPath = util_2.replaceExt(reqPath, '.proxy.js', '');
}
else if (reqPath.endsWith('.map')) {
isSourceMap = true;
reqPath = util_2.replaceExt(reqPath, '.map', '');
}
if (reqPath === build_import_proxy_1.getMetaUrlPath('/hmr-client.js', config)) {
return {
contents: encodeResponse(util_2.HMR_CLIENT_CODE, encoding),
originalFileLoc: null,
responseFileName: 'hmr-client.js',
};
}
if (reqPath === build_import_proxy_1.getMetaUrlPath('/hmr-error-overlay.js', config)) {
return {
contents: encodeResponse(util_2.HMR_OVERLAY_CODE, encoding),
originalFileLoc: null,
responseFileName: 'hmr-error-overlay.js',
};
}
if (reqPath === build_import_proxy_1.getMetaUrlPath('/env.js', config)) {
return {
contents: encodeResponse(build_import_proxy_1.generateEnvModule({ mode: 'development', isSSR }), encoding),
originalFileLoc: null,
responseFileName: 'env.js',
};
}
const attemptedFileLoads = [];
function attemptLoadFile(requestedFile) {
if (attemptedFileLoads.includes(requestedFile)) {
return Promise.resolve(null);
}
attemptedFileLoads.push(requestedFile);
return fs_1.promises
.stat(requestedFile)
.then((stat) => (stat.isFile() ? requestedFile : null))
.catch(() => null /* ignore */);
}
let requestedFile = path_1.default.parse(reqPath);
let requestedFileExt = requestedFile.ext.toLowerCase();
let responseFileExt = requestedFileExt;
let isRoute = !requestedFileExt || requestedFileExt === '.html';
async function getFileFromUrl(reqPath) {
if (reqPath.startsWith(config.buildOptions.webModulesUrl)) {
const dependencyFileLoc = reqPath.replace(config.buildOptions.webModulesUrl, util_2.DEV_DEPENDENCIES_DIR) +
(isSourceMap ? '.map' : '');
const foundFile = await attemptLoadFile(dependencyFileLoc);
if (foundFile) {
return { fileLoc: foundFile, isStatic: true, isResolve: false };
}
}
for (const [mountKey, mountEntry] of Object.entries(config.mount)) {
let requestedFile;
if (mountEntry.url === '/') {
requestedFile = path_1.default.join(mountKey, reqPath);
}
else if (reqPath.startsWith(mountEntry.url)) {
requestedFile = path_1.default.join(mountKey, reqPath.replace(mountEntry.url, './'));
}
else {
continue;
}
const fileLocExact = await attemptLoadFile(requestedFile);
if (fileLocExact) {
return {
fileLoc: fileLocExact,
isStatic: mountEntry.static,
isResolve: mountEntry.resolve,
};
}
if (!mountEntry.static) {
for (const potentialSourceFile of build_pipeline_1.getInputsFromOutput(requestedFile, config.plugins)) {
const fileLoc = await attemptLoadFile(potentialSourceFile);
if (fileLoc) {
return { fileLoc, isStatic: mountEntry.static, isResolve: mountEntry.resolve };
}
}
}
}
return null;
}
async function getFileFromRoute(reqPath) {
for (const [mountKey, mountEntry] of Object.entries(config.mount)) {
let requestedFile;
if (mountEntry.url === '/') {
requestedFile = path_1.default.join(mountKey, reqPath);
}
else if (reqPath.startsWith(mountEntry.url)) {
requestedFile = path_1.default.join(mountKey, reqPath.replace(mountEntry.url, './'));
}
else {
continue;
}
let fileLoc = (await attemptLoadFile(requestedFile + '.html')) ||
(await attemptLoadFile(requestedFile + 'index.html')) ||
(await attemptLoadFile(requestedFile + '/index.html'));
if (fileLoc) {
requestedFileExt = '.html';
responseFileExt = '.html';
return { fileLoc, isStatic: mountEntry.static, isResolve: mountEntry.resolve };
}
}
return null;
}
async function getFileFromFallback() {
if (!config.devOptions.fallback) {
return null;
}
for (const [mountKey, mountEntry] of Object.entries(config.mount)) {
if (mountEntry.url !== '/') {
continue;
}
const fallbackFile = path_1.default.join(mountKey, config.devOptions.fallback);
const fileLoc = await attemptLoadFile(fallbackFile);
if (fileLoc) {
requestedFileExt = '.html';
responseFileExt = '.html';
return { fileLoc, isStatic: mountEntry.static, isResolve: mountEntry.resolve };
}
}
return null;
}
let foundFile = await getFileFromUrl(reqPath);
if (!foundFile && isRoute) {
foundFile = (await getFileFromRoute(reqPath)) || (await getFileFromFallback());
}
if (!foundFile) {
throw new NotFoundError(attemptedFileLoads);
}
const { fileLoc, isStatic, isResolve } = foundFile;
/**
* Given a file, build it. Building a file sends it through our internal
* file builder pipeline, and outputs a build map representing the final
* build. A Build Map is used because one source file can result in multiple
* built files (Example: .svelte -> .js & .css).
*/
async function buildFile(fileLoc) {
const existingBuilderPromise = filesBeingBuilt.get(fileLoc);
if (existingBuilderPromise) {
return existingBuilderPromise;
}
const fileBuilderPromise = (async () => {
const builtFileOutput = await build_pipeline_1.buildFile(fileLoc, {
plugins: config.plugins,
isDev: true,
isSSR,
isHmrEnabled: isHMR,
sourceMaps: config.buildOptions.sourceMaps,
});
inMemoryBuildCache.set(getCacheKey(fileLoc, { isSSR, env: process.env.NODE_ENV }), builtFileOutput);
return builtFileOutput;
})();
filesBeingBuilt.set(fileLoc, fileBuilderPromise);
try {
messageBus.emit(paint_1.paintEvent.BUILD_FILE, { id: fileLoc, isBuilding: true });
return await fileBuilderPromise;
}
finally {
filesBeingBuilt.delete(fileLoc);
messageBus.emit(paint_1.paintEvent.BUILD_FILE, { id: fileLoc, isBuilding: false });
}
}
/**
* Wrap Response: The same build result can be expressed in different ways
* based on the URL. For example, "App.css" should return CSS but
* "App.css.proxy.js" should return a JS representation of that CSS. This is
* handled in the wrap step.
*/
async function wrapResponse(code, { sourceMap, sourceMappingURL, }) {
// transform special requests
if (isRoute) {
code = build_import_proxy_1.wrapHtmlResponse({
code: code,
hmr: isHMR,
hmrPort: hmrEngine.port !== port ? hmrEngine.port : undefined,
isDev: true,
config,
mode: 'development',
});
}
else if (isProxyModule) {
responseFileExt = '.js';
}
else if (isSourceMap && sourceMap) {
responseFileExt = '.map';
code = sourceMap;
}
// transform other files
switch (responseFileExt) {
case '.css': {
if (sourceMap)
code = util_2.cssSourceMappingURL(code, sourceMappingURL);
break;
}
case '.js': {
if (isProxyModule) {
code = await build_import_proxy_1.wrapImportProxy({ url: reqPath, code, hmr: isHMR, config });
}
else {
code = build_import_proxy_1.wrapImportMeta({ code: code, env: true, hmr: isHMR, config });
}
// source mapping
if (sourceMap)
code = util_2.jsSourceMappingURL(code, sourceMappingURL);
break;
}
}
// by default, return file from disk
return code;
}
/**
* Resolve Imports: Resolved imports are based on the state of the file
* system, so they can't be cached long-term with the build.
*/
async function resolveResponseImports(fileLoc, responseExt, wrappedResponse, retryMissing = true) {
let missingPackages = [];
const resolveImportSpecifier = import_resolver_1.createImportResolver({
fileLoc,
dependencyImportMap,
config,
});
wrappedResponse = await rewrite_imports_1.transformFileImports({
locOnDisk: fileLoc,
contents: wrappedResponse,
baseExt: responseExt,
expandedExt: util_2.getExt(fileLoc).expandedExt,
}, (spec) => {
var _a;
// Try to resolve the specifier to a known URL in the project
let resolvedImportUrl = resolveImportSpecifier(spec);
// Handle an import that couldn't be resolved
if (!resolvedImportUrl) {
missingPackages.push(spec);
return spec;
}
// Ignore "http://*" imports
if (url_1.default.parse(resolvedImportUrl).protocol) {
return spec;
}
// Ignore packages marked as external
if ((_a = config.installOptions.externalPackage) === null || _a === void 0 ? void 0 : _a.includes(resolvedImportUrl)) {
return spec;
}
// Handle normal "./" & "../" import specifiers
const importExtName = path_1.default.posix.extname(resolvedImportUrl);
const isProxyImport = importExtName &&
(responseExt === '.js' || responseExt === '.html') &&
importExtName !== '.js';
const isAbsoluteUrlPath = path_1.default.posix.isAbsolute(resolvedImportUrl);
if (isProxyImport) {
resolvedImportUrl = resolvedImportUrl + '.proxy.js';
}
// When dealing with an absolute import path, we need to honor the baseUrl
// proxy modules may attach code to the root HTML (like style) so don't resolve
if (isAbsoluteUrlPath && !isProxyModule) {
resolvedImportUrl = util_2.relativeURL(path_1.default.posix.dirname(reqPath), resolvedImportUrl);
}
// Make sure that a relative URL always starts with "./"
if (!resolvedImportUrl.startsWith('.') && !resolvedImportUrl.startsWith('/')) {
resolvedImportUrl = './' + resolvedImportUrl;
}
return resolvedImportUrl;
});
// A missing package is a broken import, so we need to recover instantly if possible.
if (missingPackages.length > 0) {
// if retryMissing is true, do a fresh dependency install and then retry.
// Only retry once, to prevent an infinite loop when a package doesn't actually exist.
if (retryMissing) {
try {
logger_1.logger.info(colors.yellow('Dependency cache out of date. Updating...'));
const installResult = await installDependencies(installCommandOptions);
dependencyImportMap = (installResult === null || installResult === void 0 ? void 0 : installResult.importMap) || dependencyImportMap;
return resolveResponseImports(fileLoc, responseExt, wrappedResponse, false);
}
catch (err) {
const errorTitle = `Dependency Install Error`;
const errorMessage = err.message;
logger_1.logger.error(`${errorTitle}: ${errorMessage}`);
hmrEngine.broadcastMessage({
type: 'error',
title: errorTitle,
errorMessage,
fileLoc,
});
return wrappedResponse;
}
}
// Otherwise, we need to send an error to the user, telling them about this issue.
// A failed retry usually means that Snowpack couldn't detect the import that the browser
// eventually saw post-build. In that case, you need to add it manually.
const errorTitle = `Error: Import "${missingPackages[0]}" could not be resolved.`;
const errorMessage = `If this import doesn't exist in the source file, add ${colors.bold(`"install": ["${missingPackages[0]}"]`)} to your Snowpack config file.`;
logger_1.logger.error(`${errorTitle}\n${errorMessage}`);
hmrEngine.broadcastMessage({
type: 'error',
title: errorTitle,
errorMessage,
fileLoc,
});
}
let code = wrappedResponse;
if (responseFileExt === '.js' && reqUrlHmrParam)
code = await rewrite_imports_1.transformEsmImports(code, (imp) => {
const importUrl = path_1.default.posix.resolve(path_1.default.posix.dirname(reqPath), imp);
const node = hmrEngine.getEntry(importUrl);
if (node && node.needsReplacement) {
hmrEngine.markEntryForReplacement(node, false);
return `${imp}?${reqUrlHmrParam}`;
}
return imp;
});
if (responseFileExt === '.js') {
const isHmrEnabled = code.includes('import.meta.hot');
const rawImports = await rewrite_imports_1.scanCodeImportsExports(code);
const resolvedImports = rawImports.map((imp) => {
let spec = code.substring(imp.s, imp.e);
if (imp.d > -1) {
spec = scan_imports_1.matchDynamicImportValue(spec) || '';
}
spec = spec.replace(/\?mtime=[0-9]+$/, '');
return path_1.default.posix.resolve(path_1.default.posix.dirname(reqPath), spec);
});
hmrEngine.setEntry(originalReqPath, resolvedImports, isHmrEnabled);
}
wrappedResponse = code;
return wrappedResponse;
}
/**
* Given a build, finalize it for the response. This involves running
* individual steps needed to go from build result to sever response,
* including:
* - wrapResponse(): Wrap responses
* - resolveResponseImports(): Resolve all ESM imports
*/
async function finalizeResponse(fileLoc, requestedFileExt, output) {
// Verify that the requested file exists in the build output map.
if (!output[requestedFileExt] || !Object.keys(output)) {
return null;
}
const { code, map } = output[requestedFileExt];
let finalResponse = code;
// Handle attached CSS.
if (requestedFileExt === '.js' && output['.css']) {
finalResponse =
`import './${path_1.default.basename(reqPath).replace(/.js$/, '.css.proxy.js')}';\n` +
finalResponse;
}
// Resolve imports.
if (requestedFileExt === '.js' ||
requestedFileExt === '.html' ||
requestedFileExt === '.css') {
finalResponse = await resolveResponseImports(fileLoc, requestedFileExt, finalResponse);
}
// Wrap the response.
finalResponse = await wrapResponse(finalResponse, {
sourceMap: map,
sourceMappingURL: path_1.default.basename(requestedFile.base) + '.map',
});
// Return the finalized response.
return finalResponse;
}
// 1. Check the hot build cache. If it's already found, then just serve it.
let hotCachedResponse = inMemoryBuildCache.get(getCacheKey(fileLoc, { isSSR, env: process.env.NODE_ENV }));
if (hotCachedResponse) {
let responseContent;
try {
responseContent = await finalizeResponse(fileLoc, requestedFileExt, hotCachedResponse);
}
catch (err) {
logger_1.logger.error(FILE_BUILD_RESULT_ERROR);
hmrEngine.broadcastMessage({
type: 'error',
title: FILE_BUILD_RESULT_ERROR,
errorMessage: err.toString(),
fileLoc,
errorStackTrace: err.stack,
});
throw err;
}
if (!responseContent) {
throw new NotFoundError([fileLoc]);
}
return {
contents: encodeResponse(responseContent, encoding),
originalFileLoc: fileLoc,
responseFileName: util_2.replaceExt(path_1.default.basename(fileLoc), path_1.default.extname(fileLoc), responseFileExt),
};
}
// 2. Load the file from disk. We'll need it to check the cold cache or build from scratch.
const fileContents = await util_2.readFile(fileLoc);
// 3. Send static files directly, since they were already build & resolved at install time.
if (!isProxyModule && isStatic) {
// If no resolution needed, just send the file directly.
if (!isResolve) {
return {
contents: encodeResponse(fileContents, encoding),
originalFileLoc: fileLoc,
responseFileName: util_2.replaceExt(path_1.default.basename(fileLoc), path_1.default.extname(fileLoc), responseFileExt),
};
}
// Otherwise, finalize the response (where resolution happens) before sending.
let responseContent;
try {
responseContent = await finalizeResponse(fileLoc, requestedFileExt, {
[requestedFileExt]: { code: fileContents },
});
}
catch (err) {
logger_1.logger.error(FILE_BUILD_RESULT_ERROR);
hmrEngine.broadcastMessage({
type: 'error',
title: FILE_BUILD_RESULT_ERROR,
errorMessage: err.toString(),
fileLoc,
errorStackTrace: err.stack,
});
throw err;
}
if (!responseContent) {
throw new NotFoundError([fileLoc]);
}
return {
contents: encodeResponse(responseContent, encoding),
originalFileLoc: fileLoc,
responseFileName: util_2.replaceExt(path_1.default.basename(fileLoc), path_1.default.extname(fileLoc), responseFileExt),
};
}
// 4. Check the persistent cache. If found, serve it via a
// "trust-but-verify" strategy. Build it after sending, and if it no longer
// matches then assume the entire cache is suspect. In that case, clear the
// persistent cache and then force a live-reload of the page.
const cachedBuildData = allowStale &&
process.env.NODE_ENV !== 'test' &&
!filesBeingDeleted.has(fileLoc) &&
!(await isbinaryfile_1.isBinaryFile(fileLoc)) &&
(await cacache_1.default
.get(util_2.BUILD_CACHE, getCacheKey(fileLoc, { isSSR, env: process.env.NODE_ENV }))
.catch(() => null));
if (cachedBuildData) {
const { originalFileHash } = cachedBuildData.metadata;
const newFileHash = etag_1.default(fileContents);
if (originalFileHash === newFileHash) {
// IF THIS FAILS TS CHECK: If you are changing the structure of
// SnowpackBuildMap, be sure to also update `BUILD_CACHE` in util.ts to
// a new unique name, to guarantee a clean cache for our users.
const coldCachedResponse = JSON.parse(cachedBuildData.data.toString());
inMemoryBuildCache.set(getCacheKey(fileLoc, { isSSR, env: process.env.NODE_ENV }), coldCachedResponse);
const wrappedResponse = await finalizeResponse(fileLoc, requestedFileExt, coldCachedResponse);
if (!wrappedResponse) {
throw new NotFoundError([fileLoc]);
}
// Trust...
return {
contents: encodeResponse(wrappedResponse, encoding),
originalFileLoc: fileLoc,
responseFileName: util_2.replaceExt(path_1.default.basename(fileLoc), path_1.default.extname(fileLoc), responseFileExt),
// ...but verify.
checkStale: async () => {
let checkFinalBuildResult = null;
try {
checkFinalBuildResult = await buildFile(fileLoc);
}
catch (err) {
// safe to ignore, it will be surfaced later anyway
}
finally {
if (!checkFinalBuildResult ||
!cachedBuildData.data.equals(Buffer.from(JSON.stringify(checkFinalBuildResult)))) {
inMemoryBuildCache.clear();
await cacache_1.default.rm.all(util_2.BUILD_CACHE);
hmrEngine.broadcastMessage({ type: 'reload' });
}
}
return;
},
};
}
}
// 5. Final option: build the file, serve it, and cache it.
let responseContent;
let responseOutput;
try {
responseOutput = await buildFile(fileLoc);
}
catch (err) {
hmrEngine.broadcastMessage({
type: 'error',
title: `Build Error` +
(err.__snowpackBuildDetails ? `: ${err.__snowpackBuildDetails.name}` : ''),
errorMessage: err.toString(),
fileLoc,
errorStackTrace: err.stack,
});
throw err;
}
try {
responseContent = await finalizeResponse(fileLoc, requestedFileExt, responseOutput);
}
catch (err) {
logger_1.logger.error(FILE_BUILD_RESULT_ERROR);
hmrEngine.broadcastMessage({
type: 'error',
title: FILE_BUILD_RESULT_ERROR,
errorMessage: err.toString(),
fileLoc,
errorStackTrace: err.stack,
});
throw err;
}
if (!responseContent) {
throw new NotFoundError([fileLoc]);
}
// Save the file to the cold cache for reuse across restarts.
cacache_1.default
.put(util_2.BUILD_CACHE, getCacheKey(fileLoc, { isSSR, env: process.env.NODE_ENV }), Buffer.from(JSON.stringify(responseOutput)), {
metadata: { originalFileHash: etag_1.default(fileContents) },
})
.catch((err) => {
logger_1.logger.error(`Cache Error: ${err.toString()}`);
});
return {
contents: encodeResponse(responseContent, encoding),
originalFileLoc: fileLoc,
responseFileName: util_2.replaceExt(path_1.default.basename(fileLoc), path_1.default.extname(fileLoc), responseFileExt),
};
}
function getRequestProxy(reqUrl) {
for (const [pathPrefix] of config.proxy) {
if (!shouldProxy(pathPrefix, reqUrl)) {
continue;
}
return (req, res) => devProxies[pathPrefix].web(req, res);
}
}
/**
* A simple map to optimize the speed of our 304 responses. If an ETag check is
* sent in the request, check if it matches the last known etag for tat file.
*
* Remember: This is just a nice-to-have! If we get this logic wrong, it can mean
* stale files in the user's cache. Feel free to clear aggressively, as needed.
*/
const knownETags = new Map();
/**
* Fully handle the response for a given request. This is used internally for
* every response that the dev server sends, but it can also be used via the
* JS API to handle most boilerplate around request handling.
*/
async function handleRequest(req, res, { handleError } = {}) {
const reqUrl = req.url;
// Check if a configured proxy matches the request.
const requestProxy = getRequestProxy(reqUrl);
if (requestProxy) {
return requestProxy(req, res);
}
// Check if we can send back an optimized 304 response
const quickETagCheck = req.headers['if-none-match'];
if (quickETagCheck && quickETagCheck === knownETags.get(reqUrl)) {
logger_1.logger.debug(`optimized etag! sending 304...`);
res.writeHead(304, { 'Access-Control-Allow-Origin': '*' });
res.end();
return;
}
// Otherwise, load the file and respond if successful.
try {
const result = await loadUrl(reqUrl, { allowStale: true, encoding: null });
sendResponseFile(req, res, result);
if (result.checkStale) {
await result.checkStale();
}
if (result.contents) {
const tag = etag_1.default(result.contents, { weak: true });
const reqPath = decodeURI(url_1.default.parse(reqUrl).pathname);
knownETags.set(reqPath, tag);
}
return;
}
catch (err) {
// Some consumers may want to handle/ignore errors themselves.
if (handleError === false) {
throw err;
}
handleResponseError(req, res, err);
}
}
const createServer = (responseHandler) => {
if (credentials && config.proxy.length === 0) {
return http2_1.default.createSecureServer({ ...credentials, allowHTTP1: true }, responseHandler);
}
else if (credentials) {
return https_1.default.createServer(credentials, handleRequest);
}
return http_1.default.createServer(handleRequest);
};
const server = createServer(async (req, res) => {
// Attach a request logger.
res.on('finish', () => {
const { method, url } = req;
const { statusCode } = res;
logger_1.logger.debug(`[${statusCode}] ${method} ${url}`);
});
// If custom "app" is given, pass requests through there first.
if (config.experiments.app) {
config.experiments.app(req, res, async (err) => {
if (err) {
handleResponseError(req, res, err);
return;
}
handleRequest(req, res);
});
return;
}
// Otherwise, pass requests directly to Snowpack's request handler.
handleRequest(req, res);
})
.on('error', (err) => {
logger_1.logger.error(colors.red(` ✘ Failed to start server at port ${colors.bold(port)}.`), err);
server.close();
process.exit(1);
})
.on('upgrade', (req, socket, head) => {
config.proxy.forEach(([pathPrefix, proxyOptions]) => {
var _a;
const isWebSocket = proxyOptions.ws || ((_a = proxyOptions.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws'));
if (isWebSocket && shouldProxy(pathPrefix, req.url)) {
devProxies[pathPrefix].ws(req, socket, head);
logger_1.logger.info('Upgrading to WebSocket');
}
});
})
.listen(port);
const { hmrDelay } = config.devOptions;
const hmrEngineOptions = Object.assign({ delay: hmrDelay }, config.devOptions.hmrPort ? { port: config.devOptions.hmrPort } : { server, port });
const hmrEngine = new hmr_server_engine_1.EsmHmrEngine(hmrEngineOptions);
signal_exit_1.default(() => {
hmrEngine.disconnectAllClients();
});
// Live Reload + File System Watching
let isLiveReloadPaused = false;
function updateOrBubble(url, visited) {
if (visited.has(url)) {
return;
}
const node = hmrEngine.getEntry(url);
const isBubbled = visited.size > 0;
if (node && node.isHmrEnabled) {
hmrEngine.broadcastMessage({ type: 'update', url, bubbled: isBubbled });
}
visited.add(url);
if (node && node.isHmrAccepted) {
// Found a boundary, no bubbling needed
}
else if (node && node.dependents.size > 0) {
node.dependents.forEach((dep) => {
hmrEngine.markEntryForReplacement(node, true);
updateOrBubble(dep, visited);
});
}
else {
// We've reached the top, trigger a full page refresh
hmrEngine.broadcastMessage({ type: 'reload' });
}
}
function handleHmrUpdate(fileLoc, updatedUrl) {
if (isLiveReloadPaused) {
return;
}
// Append ".proxy.js" to Non-JS files to match their registered URL in the
// client app.
if (!updatedUrl.endsWith('.js')) {
updatedUrl += '.proxy.js';
}
// Check if a virtual file exists in the resource cache (ex: CSS from a
// Svelte file) If it does, mark it for HMR replacement but DONT trigger a
// separate HMR update event. This is because a virtual resource doesn't
// actually exist on disk, so we need the main resource (the JS) to load
// first. Only after that happens will the CSS exist.
const virtualCssFileUrl = updatedUrl.replace(/.js$/, '.css');
const virtualNode = hmrEngine.getEntry(`${virtualCssFileUrl}.proxy.js`);
if (virtualNode) {
hmrEngine.markEntryForReplacement(virtualNode, true);
}
// If the changed file exists on the page, trigger a new HMR update.
if (hmrEngine.getEntry(updatedUrl)) {
updateOrBubble(updatedUrl, new Set());
return;
}
// Otherwise, reload the page if the file exists in our hot cache (which
// means that the file likely exists on the current page, but is not
// supported by HMR (HTML, image, etc)).
if (inMemoryBuildCache.has(getCacheKey(fileLoc, { isSSR: false, env: process.env.NODE_ENV }))) {
hmrEngine.broadcastMessage({ type: 'reload' });
return;
}
}
// Announce server has started
const ips = Object.values(os_1.default.networkInterfaces())
.reduce((every, i) => [...every, ...(i || [])], [])
.filter((i) => i.family === 'IPv4' && i.internal === false)
.map((i) => i.address);
const protocol = config.devOptions.secure ? 'https:' : 'http:';
messageBus.emit(paint_1.paintEvent.SERVER_START, {
protocol,
hostname,
port,
ips,
startTimeMs: Math.round(perf_hooks_1.performance.now() - serverStart),
});
// Open the user's browser (ignore if failed)
if (open !== 'none') {
await util_2.openInBrowser(protocol, hostname, port, open).catch((err) => {
logger_1.logger.debug(`Browser open error: ${err}`);
});
}
// Start watching the file system.
// Defer "chokidar" loading to here, to reduce impact on overall startup time
const chokidar = await Promise.resolve().then(() => __importStar(require('chokidar')));
// Allow the user to hook into this callback, if they like (noop by default)
let onFileChangeCallback = () => { };
// Watch src files
async function onWatchEvent(fileLoc) {
logger_1.logger.info(colors.cyan('File changed...'));
onFileChangeCallback({ filePath: fileLoc });
const updatedUrl = file_urls_1.getUrlForFile(fileLoc, config);
if (updatedUrl) {
handleHmrUpdate(fileLoc, updatedUrl);
knownETags.delete(updatedUrl);
knownETags.delete(updatedUrl + '.proxy.js');
}
inMemoryBuildCache.delete(getCacheKey(fileLoc, { isSSR: true, env: process.env.NODE_ENV }));
inMemoryBuildCache.delete(getCacheKey(fileLoc, { isSSR: false, env: process.env.NODE_ENV }));
filesBeingDeleted.add(fileLoc);
await cacache_1.default.rm.entry(util_2.BUILD_CACHE, getCacheKey(fileLoc, { isSSR: true, env: process.env.NODE_ENV }));
await cacache_1.default.rm.entry(util_2.BUILD_CACHE, getCacheKey(fileLoc, { isSSR: false, env: process.env.NODE_ENV }));
for (const plugin of config.plugins) {
plugin.onChange && plugin.onChange({ filePath: fileLoc });
}
filesBeingDeleted.delete(fileLoc);
}
const watcher = chokidar.watch(Object.keys(config.mount), {
ignored: config.exclude,
persistent: true,
ignoreInitial: true,
disableGlobbing: false,
});
watcher.on('add', (fileLoc) => {
knownETags.clear();
onWatchEvent(fileLoc);
});
watcher.on('unlink', (fileLoc) => {
knownETags.clear();
onWatchEvent(fileLoc);
});
watcher.on('change', (fileLoc) => {
onWatchEvent(fileLoc);
});
// Watch node_modules & rerun snowpack install if symlinked dep updates
const symlinkedFileLocs = new Set(Object.keys(dependencyImportMap.imports)
.map((specifier) => {
const [packageName] = util_2.parsePackageImportSpecifier(specifier);
return util_2.resolveDependencyManifest(packageName, cwd);
}) // resolve symlink src location
.filter(([_, packageManifest]) => packageManifest && !packageManifest['_id']) // only watch symlinked deps for now
.map(([fileLoc]) => `${path_1.default.dirname(fileLoc)}/**`));
function onDepWatchEvent() {
hmrEngine.broadcastMessage({ type: 'reload' });
}
const depWatcher = chokidar.watch([...symlinkedFileLocs], {
cwd: '/',
persistent: true,
ignoreInitial: true,
disableGlobbing: false,
});
depWatcher.on('add', onDepWatchEvent);
depWatcher.on('change', onDepWatchEvent);
depWatcher.on('unlink', onDepWatchEvent);
return {
port,
loadUrl,
handleRequest,
sendResponseFile,
sendResponseError,
onFileChange: (callback) => (onFileChangeCallback = callback),
async shutdown() {
await watcher.close();
server.close();
},
};
}
exports.startDevServer = startDevServer;
async function command(commandOptions) {
try {
await startDevServer(commandOptions);
}
catch (err) {
logger_1.logger.error(err.message);
logger_1.logger.debug(err.stack);
process.exit(1);
}
return new Promise(() => { });
}
exports.command = command;
//# sourceMappingURL=dev.js.map
|
areese/fluent-bit
|
tests/internal/fuzzers/local_test.c
|
<reponame>areese/fluent-bit<filename>tests/internal/fuzzers/local_test.c
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019-2020 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data 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.
*/
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_log.h>
#include <fluent-bit/flb_mem.h>
#include <monkey/mk_core.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
/* declare external function test */
int LLVMFuzzerTestOneInput(unsigned char *data, size_t size);
int main(int argc, char **argv)
{
int i;
int ret;
FILE *fp;
char *buffer;
long bytes;
struct stat st;
if (argc < 2) {
flb_error("usage: %s TESTCASE_FILE", argv[0]);
exit(EXIT_FAILURE);
}
/* Validate the file */
ret = stat(argv[1], &st);
if (ret == -1) {
flb_errno();
flb_error("cannot stat(2) testcase file '%s'", argv[1]);
exit(EXIT_FAILURE);
}
if (!(fp = fopen(argv[1], "rb"))) {
flb_errno();
flb_error("cannot fopen(2) testcase file '%s'", argv[1]);
return -1;
}
buffer = flb_malloc(st.st_size);
if (!buffer) {
flb_errno();
return -1;
}
bytes = fread(buffer, st.st_size, 1, fp);
if (bytes < 1) {
fclose(fp);
flb_free(buffer);
return -1;
}
fclose(fp);
/* Invoke the fuzzer entry-point function */
for (i = 0; i < 100; i++) {
ret = LLVMFuzzerTestOneInput((unsigned char *) buffer, st.st_size);
}
flb_free(buffer);
return 0;
}
|
hhhHanqing/bias
|
src/backend/spin/node_map_utils.hpp
|
#ifdef WITH_SPIN
#ifndef NODE_MAP_UTILS_HPP
#define NODE_MAP_UTILS_HPP
#include <string>
#include <vector>
#include <map>
#include <cstdint>
#include "SpinnakerC.h"
namespace bias
{
size_t getNumberOfNodes(spinNodeMapHandle &hNodeMap);
std::string getNodeTypeString(spinNodeType nodeType);
std::vector<std::string> getNodeNames(spinNodeMapHandle &hNodeMap);
std::map<std::string, spinNodeType> getNodeNameToTypeMap(spinNodeMapHandle &hNodeMap);
std::map<std::string, std::string> getStringNodeNameToValueMap(spinNodeMapHandle &hNodeMap);
std::vector<std::string> getEnumerationNodeEntryNames(spinNodeMapHandle &hNodeMap, std::string nodeName);
} // namespace bias
#endif
#endif
|
lefevre-fraser/openmeta-mms
|
src/CyPhy2Desert/CyPhy2Desert.cpp
|
#ifndef CYPHY2DESERT_CPP
#define CYPHY2DESERT_CPP
#include "uml.h"
#include <objbase.h>
#include "UmlExt.h"
#include "UdmUtil.h"
#include "CyPhy2Desert.h"
#include <cmath>
#include<math.h>
#include <stdio.h>
#include "DesertFormulaUtil.h"
#include "UdmGme.h"
#include <sstream>
#include <string.h>
#include <iterator>
#include <algorithm>
#include <regex>
using namespace CyPhyML;
using namespace DesertIface;
std::string checkInvalidName(std::string name)
{
if (name.empty())
return "";
std::string badtoken = " ;.,#:'\"?<>-+=*&^$!";
std::string converted;
// Spaces and '-' are translated to '_'.
for( std::string::const_iterator i= name.begin(); i!= name.end(); ++i)
{
if(badtoken.find(*i)!=std::string::npos)
//if ( (*i== '-') || (*i==' '))
converted+= '_';
else
converted+= *i;
}
return converted;
};
set<CyPhyML::DesignEntity> allOptions;
typedef map<CyPhyML::DesignEntity, std::unique_ptr<set<CyPhyML::DesignEntity> > > GroupOptions;
GroupOptions allGroupOptions;
const char* mmGroupsFilename = "groups_list.txt";
const char* mmOptionsFilename = "options_list.txt";
FILE* mmfd1 = 0;
FILE* mmfd2 = 0;
bool morphMatrixInitialized2 = false;
void morphMatrixInitialize2() {
if(morphMatrixInitialized2)
return;
// MorphMatrix initialize
allGroupOptions.clear();
allOptions.clear();
mmfd1 = fopen(mmGroupsFilename, "w+");
mmfd2 = fopen(mmOptionsFilename, "w+");
morphMatrixInitialized2 = true;
}
void morphMatrixFinalize2() {
if(!morphMatrixInitialized2)
return;
morphMatrixInitialized2 = false;
// MorphMatrix finalize
for(GroupOptions::iterator mmPos = allGroupOptions.begin(); mmPos != allGroupOptions.end(); ++mmPos) {
GroupOptions::value_type& mmRow = *mmPos;
CyPhyML::DesignEntity group = mmRow.first;
auto& groupOptions = mmRow.second;
string groupName = group.name();
long groupID = group.ID();
CyPhyML::DesignContainer groupContainer = CyPhyML::DesignContainer::Cast(group);
string groupType = groupContainer.ContainerType();
fprintf(mmfd1, "%s\t%ld\t%s", groupName.c_str(), groupID, groupType.c_str());
for(set<CyPhyML::DesignEntity>::iterator aePos = groupOptions->begin(); aePos != groupOptions->end(); ++aePos) {
CyPhyML::DesignEntity e = *aePos;
string optionName = e.name();
long optionID = e.ID();
fprintf(mmfd1, "\t%s\t%ld", optionName.c_str(), optionID);
}
fprintf(mmfd1, "\n");
}
fprintf(mmfd2, "Option_ID\tOption_Name\n");
for(set<CyPhyML::DesignEntity>::iterator aePos = allOptions.begin(); aePos != allOptions.end(); ++aePos) {
CyPhyML::DesignEntity e = *aePos;
string eName = e.name();
long eID = e.ID();
fprintf(mmfd2, "%ld\t%s\n", eID, eName.c_str());
}
fflush(mmfd1);
fflush(mmfd2);
fclose(mmfd1);
fclose(mmfd2);
mmfd1 = 0;
mmfd2 = 0;
allGroupOptions.clear();
allOptions.clear();
}
int CyPhy2Desert::domainId = 0;
DesertIface::ConstraintSet CyPhy2Desert::constraintSet;
DesertIface::FormulaSet CyPhy2Desert::formulaSet;
set<CyPhyML::Parameter> CyPhy2Desert::invalidParameters;
set<CyPhyML::CustomFormula> CyPhy2Desert::invalidCustomFormulas;
set<CyPhyML::DecisionGroup> CyPhy2Desert::invalidGroups;
set<CyPhyML::ComponentRef> CyPhy2Desert::nullComponentRefs;
map<CyPhyML::DesignEntity, int> CyPhy2Desert::originalIDs;
map<Udm::Object, std::string> CyPhy2Desert::originalNames;
map<std::string, int> CyPhy2Desert::connectorDefMap;
map<std::string, set<int> > CyPhy2Desert::connectorDefWildCardMap;
std::string CyPhy2Desert::errorMsg = "";
CyPhy2Desert::CyPhy2Desert(DesertIface::DesertSystem &desert_top) : dsystem(desert_top),groupCount(0)
{
// morphMatrixInitialize2();
}
CyPhy2Desert::~CyPhy2Desert()
{
// morphMatrixFinalize2();
}
void CyPhy2Desert::generateDesert(const CyPhyML::RootFolder &cyphy_rf)
{
init();
// initSITWildCardMap();
initConnectorDefMap(cyphy_rf);
initConnectorDefWildCardMap();
const set<CyPhyML::DesignSpace> &dss = cyphy_rf.DesignSpace_kind_children();
for(set<CyPhyML::DesignSpace>::const_iterator i=dss.begin();i!=dss.end();++i)
{
CyPhyML::DesignSpace ds = *i;
traverseDesignSpace(ds, space);
}
postprocessParameters();
}
void CyPhy2Desert::generateDesert(const CyPhyML::DesignSpace &cyphy_ds)
{
init();
// initSITWildCardMap();
initConnectorDefMap(cyphy_ds);
initConnectorDefWildCardMap();
traverseDesignSpace(cyphy_ds, space);
postprocessParameters();
}
void CyPhy2Desert::generateDesert(const CyPhyML::DesignContainer &cyphy_dc)
{
rootDC = cyphy_dc;
set<int> ids;
std::string path;
if(!checkDesignElementLoop(rootDC, ids, path))
{
errorMsg = "The cyclic reference loop is found: <br>"+path;
throw udm_exception("The cyclic reference loop is found. Please see the details in console window.");
}
init();
initConnectorDefMap(cyphy_dc);
initConnectorDefWildCardMap();
traverseContainer(cyphy_dc, space, CyPhyML::DesignEntity::Cast(cyphy_dc));
postprocessParameters();
}
void CyPhy2Desert::getCom2ElemMap(map<CyPhyML::DesignEntity, DesertIface::Element> &retMap)
{
retMap = com2elemMap;
}
void CyPhy2Desert::getConstraintMap(map<DesertIface::Constraint, CyPhyML::ConstraintBase> &retMap)
{
retMap = constraintMap;
}
_int64 string2int(const std::string &value)
{
double num = atof(value.c_str());
return (_int64)ceil(num);
}
void CyPhy2Desert::init()
{
space = DesertIface::Space::Create(dsystem);
space.name() = "DesignSpace";
space.id() = 1000;
space.externalID() = 1000;
space.decomposition() = true;
constraintSet = DesertIface::ConstraintSet::Create(dsystem);
constraintSet.name() = "constraints";
constraintSet.id() = 1003;
constraintSet.externalID() = 1003;
formulaSet = DesertIface::FormulaSet::Create(dsystem);
formulaSet.name() = "formulaSet";
formulaSet.id() = 1005;
formulaSet.externalID() = 1005;
domainId = 1004;
domainMap.clear();
parameterNameMap.clear();
invalidParameters.clear();
invalidCustomFormulas.clear();
nullComponentRefs.clear();
invalidGroups.clear();
originalIDs.clear();
//structuralInterfaceTypeMap.clear();
//sitWildCardMap.clear();
//structuralInterfaceTypeMap["88888888"] = 0;
originalNames.clear();
}
//void CyPhy2Desert::initSITWildCardMap()
//{
// map<std::string, set<int> > tmp_sitWildCardMap;
// for(auto pos=sitWildCardMap.begin(); pos!=sitWildCardMap.end(); ++pos)
// {
// std::string si_wc = (*pos).first;
// set<int> vals = (*pos).second;
// int length = si_wc.size();
// for(auto pos1=structuralInterfaceTypeMap.begin(); pos1!=structuralInterfaceTypeMap.end(); ++pos1)
// {
// std::string this_si = (*pos1).first;
// if(this_si.size()!=length)
// continue;
// bool ismatch = true;
// for(std::string::size_type i = 0; i<length; ++i)
// {
// if(si_wc[i]=='*')
// continue;
// else if(si_wc[i]!=this_si[i])
// {
// ismatch = false;
// break;
// }
// }
//
// if(ismatch)
// vals.insert((*pos1).second);
// }
// if(!vals.empty())
// tmp_sitWildCardMap[si_wc] = vals;
// else
// {
// int si_val = structuralInterfaceTypeMap.size()+1;
// structuralInterfaceTypeMap[si_wc] = si_val;
// }
// }
//
// sitWildCardMap.clear();
// sitWildCardMap.insert(tmp_sitWildCardMap.begin(), tmp_sitWildCardMap.end());
//}
void CyPhy2Desert::initConnectorDefMap(const CyPhyML::RootFolder &rf)
{
const set<CyPhyML::DesignSpace> &dsfdrs = rf.DesignSpace_kind_children();
for(set<CyPhyML::DesignSpace>::const_iterator di=dsfdrs.begin();di!=dsfdrs.end();++di)
{
initConnectorDefMap(*di);
}
}
void CyPhy2Desert::initConnectorDefMap(const CyPhyML::DesignSpace &ds)
{
const set<CyPhyML::DesignSpace> &dsfdrs = ds.DesignSpace_kind_children();
for(set<CyPhyML::DesignSpace>::const_iterator di=dsfdrs.begin();di!=dsfdrs.end();++di)
{
initConnectorDefMap(*di);
}
const set<CyPhyML::DesignContainer> &containers = ds.DesignContainer_kind_children();
for(set<CyPhyML::DesignContainer>::const_iterator ci=containers.begin();ci!=containers.end();++ci)
{
initConnectorDefMap(*ci);
}
}
void CyPhy2Desert::initConnectorDefMap(const CyPhyML::DesignContainer &dc)
{
set<CyPhyML::DesignContainer> dcs = dc.DesignContainer_kind_children();
for(auto it_dc=dcs.begin(); it_dc!=dcs.end(); ++it_dc)
initConnectorDefMap(*it_dc);
set<CyPhyML::ComponentRef> comrefs = dc.ComponentRef_kind_children();
for(auto it_ref=comrefs.begin(); it_ref!=comrefs.end(); ++it_ref)
{
CyPhyML::ComponentRef comref = *it_ref;
CyPhyML::DesignElement de = comref.ref();
if(de!=Udm::null)
initConnectorDefMap(de);
else
{
nullComponentRefs.insert(comref);
}
}
set<CyPhyML::ComponentAssembly> cas = dc.ComponentAssembly_kind_children();
for(auto it_ca=cas.begin(); it_ca!=cas.end(); ++it_ca)
initConnectorDefMap(*it_ca);
set<CyPhyML::Component> coms = dc.Component_kind_children();
for(auto it_com=coms.begin(); it_com!=coms.end(); ++it_com)
initConnectorDefMap(*it_com);
}
void CyPhy2Desert::initConnectorDefMap(const CyPhyML::DesignElement &de)
{
set<CyPhyML::Connector> connectors = de.Connector_kind_children();
for(auto it_si=connectors.begin(); it_si!=connectors.end(); ++it_si)
{
CyPhyML::Connector si = *it_si;
std::string def = si.Definition();
if(def.find("*")==std::string::npos) //non-wildcard
{
map<std::string, int>::iterator map_pos = connectorDefMap.find(def);
if(map_pos == connectorDefMap.end())
{
int def_val = connectorDefMap.size()+1;
connectorDefMap[def] = def_val;
}
}
else //wildcard
{
map<std::string, set<int> >::iterator map_pos1 = connectorDefWildCardMap.find(def);
if(map_pos1 == connectorDefWildCardMap.end())
{
set<int> tmp;
connectorDefWildCardMap[def] = tmp;
}
}
}
if(Uml::IsDerivedFrom(de.type(), CyPhyML::ComponentAssembly::meta))
{
CyPhyML::ComponentAssembly ca = CyPhyML::ComponentAssembly::Cast(de);
set<CyPhyML::DesignElement> des = ca.DesignElement_kind_children();
for(auto it_de = des.begin();it_de!=des.end();++it_de)
{
initConnectorDefMap(*it_de);
}
set<CyPhyML::ComponentRef> comrefs = ca.ComponentRef_kind_children();
for(auto it_ref=comrefs.begin();it_ref!=comrefs.end();++it_ref)
{
const CyPhyML::DesignElement ref_de = (*it_ref).ref();
if(ref_de!=Udm::null)
initConnectorDefMap(ref_de);
}
}
}
void CyPhy2Desert::initConnectorDefWildCardMap()
{
map<std::string, set<int> > tmp_defWildCardMap;
for(auto pos=connectorDefWildCardMap.begin(); pos!=connectorDefWildCardMap.end(); ++pos)
{
std::string si_wc = (*pos).first;
set<int> vals = (*pos).second;
std::string::size_type length = si_wc.size();
for(auto pos1=connectorDefMap.begin(); pos1!=connectorDefMap.end(); ++pos1)
{
std::string this_si = (*pos1).first;
if(this_si.size()!=length)
continue;
bool ismatch = true;
for(std::string::size_type i = 0; i<length; ++i)
{
if(si_wc[i]=='*')
continue;
else if(si_wc[i]!=this_si[i])
{
ismatch = false;
break;
}
}
if(ismatch)
vals.insert((*pos1).second);
}
if(!vals.empty())
tmp_defWildCardMap[si_wc] = vals;
else
{
int si_val = connectorDefMap.size()+1;
connectorDefMap[si_wc] = si_val;
}
}
connectorDefWildCardMap.clear();
connectorDefWildCardMap.insert(tmp_defWildCardMap.begin(), tmp_defWildCardMap.end());
}
DesertIface::NaturalDomain CyPhy2Desert::generateNaturalDomain(DesertIface::DesertSystem dsys, const std::string &dname, _int64 min, _int64 max)
{
domainId++;
DesertIface::NaturalDomain ndomain = DesertIface::NaturalDomain::Create(dsys);
ndomain.name() = dname;
ndomain.id() = ndomain.externalID() = domainId;
ndomain.minimum() = min;
ndomain.maximum() = max;
domainMap[dname] = ndomain;
naturalParameters.insert(dname);
return ndomain;
}
DesertIface::CustomDomain CyPhy2Desert::generateCustomDomain(const std::string &dname)
{
domainId++;
DesertIface::CustomDomain cdomain = DesertIface::CustomDomain::Create(dsystem);
cdomain.name() = dname+"s";
cdomain.id() = cdomain.externalID() = domainId;
cdomain.decomposition() = true;
domainMap[dname] = cdomain;
customParameters.insert(dname);
return cdomain;
}
template <class T> void CyPhy2Desert::traverseDesignSpace(const CyPhyML::DesignSpace &ds, T &element_parent)
{
Element element = Element::Create(element_parent);
element.name() = ds.name();
element.id() = element.externalID() = ds.uniqueId();
element.decomposition() = true;
const set<CyPhyML::DesignSpace> &dsfdrs = ds.DesignSpace_kind_children();
for(set<CyPhyML::DesignSpace>::const_iterator di=dsfdrs.begin();di!=dsfdrs.end();++di)
{
traverseDesignSpace(*di, element);
DOEVENTS();
}
const set<CyPhyML::DesignContainer> &containers = ds.DesignContainer_kind_children();
if(containers.empty()) return;
// rootContainer = *(containers.begin());
for(set<CyPhyML::DesignContainer>::const_iterator ci=containers.begin();ci!=containers.end();++ci)
{
rootDC = *ci;
set<int> ids;
std::string path;
if(!checkDesignElementLoop(rootDC, ids, path))
throw udm_exception("The cyclic reference loop is found: \\n"+path);
traverseContainer(*ci, element, CyPhyML::DesignEntity::Cast(*ci));
DOEVENTS();
}
}
void CyPhy2Desert::addGroup(CyPhyML::DesignContainer& currentGroup)
{
CyPhyML::DesignContainer groupBaseType = currentGroup;
if(currentGroup.isInstance() || currentGroup.isSubtype()) {
groupBaseType = currentGroup.Archetype();
while(groupBaseType.isInstance() || groupBaseType.isSubtype()) {
groupBaseType =groupBaseType.Archetype();
}
}
allOptions.insert(groupBaseType);
GroupOptions::iterator goItr = allGroupOptions.find(groupBaseType);
if(goItr == allGroupOptions.end()) {
// New group
auto groupOptions = new set<CyPhyML::DesignEntity>();
allGroupOptions.emplace(groupBaseType, unique_ptr<set<CyPhyML::DesignEntity> >(groupOptions));
set<CyPhyML::DesignEntity> groupChildren = groupBaseType.DesignEntity_kind_children();
for(set<CyPhyML::DesignEntity>::iterator it = groupChildren.begin(); it != groupChildren.end(); ++it) {
CyPhyML::DesignEntity aChild = *it;
allOptions.insert(aChild);
groupOptions->insert(aChild);
mgroupMap[aChild.ID()] = groupBaseType;
moptionMap[aChild.ID()] = aChild;
}
moptionMap[groupBaseType.ID()] = groupBaseType;
mgroupMap[groupBaseType.ID()] = groupBaseType;
}
}
void CyPhy2Desert::processConstants(const set<CyPhyML::Constant> &constants, const CyPhyML::DesignEntity &celem, DesertIface::Element &delem)
{
for(set<CyPhyML::Constant>::iterator i=constants.begin();i!=constants.end();++i)
{
CyPhyML::Constant constant = *i;
std::string cname = constant.name();
double value = constant.ConstantValue();
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
if(!getDomainWithMember(cname, domain, value, member))
throw udm_exception("Constant: "+cname+" is not NaturalDomain.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(delem);
updatevpMap(vp, constant, celem);
vp.parametric() = false;
vp.name() = vp.CUSTName() = cname;
vp.id() = vp.externalID() = celem.ID()+5000;
vp.PCM_STR() = "PCM_NONE";
vp.Max() = 100000;
vp.domain() =domain;
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(delem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
}
}
void CyPhy2Desert::processProperties(const set<CyPhyML::Property> &properties, const CyPhyML::DesignContainer &celem,
DesertIface::Element &delem, set<CyPhyML::ValueFlowTarget>& alt_vfends)
{
for(set<CyPhyML::Property>::iterator i=properties.begin();i!=properties.end();++i)
{
CyPhyML::Property propty = *i;
if(propty.Disable()) continue;
std::string pname = propty.name();
set<CyPhyML::ValueFlow> src_vfs = propty.srcValueFlow();
checkSourceValueFlows(src_vfs, celem);
if(!src_vfs.empty()) //this property is parametric
{
processProperty(celem, delem, propty, src_vfs, alt_vfends);
} //for non-parametric property
else
{
if((std::string)propty.ComputationType()!="Cust")
{
double value = getPropertyNumberValue(propty);
processProperty(celem,delem,pname,value,propty.ComputationType(),propty,(src_vfs.empty()||Uml::IsDerivedFrom(celem.type(), CyPhyML::ComponentAssembly::meta)));
}
}
}
}
void CyPhy2Desert::processParameters(const set<CyPhyML::Parameter> ¶meters, const CyPhyML::DesignContainer &celem, DesertIface::Element &delem, bool isAlt, set<CyPhyML::ValueFlowTarget>& alt_vfends)
{
for(set<CyPhyML::Parameter>::iterator pi=parameters.begin();pi!=parameters.end();++pi)
{
CyPhyML::Parameter parameter = *pi;
std::string pname = parameter.name();
if(!parameter.Disable() && !isAlt)
generateConstraint(parameter, delem);
set<CyPhyML::ValueFlow> src_vfs = parameter.srcValueFlow();
checkSourceValueFlows(src_vfs, celem);
if(!src_vfs.empty())
{
processProperty(celem, delem, parameter, src_vfs, alt_vfends);
}
else
{
if((std::string)parameter.ComputationType()!="Cust")
{
double value = getPropertyNumberValue(parameter);
processProperty(celem,delem,pname,value,parameter.ComputationType(),parameter,(src_vfs.empty()||Uml::IsDerivedFrom(celem.type(), CyPhyML::ComponentAssembly::meta)));
}
}
}
}
std::string CyPhy2Desert::generateParameterConstraint(const CyPhyML::Parameter ¶meter, const std::string &newParamName)
{
std::string range = parameter.Range();
return generateParameterConstraint(range, newParamName, parameter);
}
std::string CyPhy2Desert::generateParameterConstraint(const std::string &range, const std::string &newParamName, CyPhyML::Parameter parameter)
{
/*
Syntax: 0..2
or -inf..inf
or -inf..2
Ranges are inclusive
*/
if(range.empty())
return "";
size_t not_pos = range.find_first_not_of(" [(-0123456789infINF]).,");
if(not_pos!=std::string::npos)
{
if (parameter) {
invalidParameters.insert(parameter);
}
return "";
}
if(range.find("-inf..inf")!=std::string::npos)
return "";
if(range.find("-inf,inf")!=std::string::npos) // compatibility
return "";
std::string cleanRange;
std::copy_if(range.begin(), range.end(), std::back_inserter(cleanRange), [](std::string::value_type ch) { return strchr("[]() ", ch) == NULL; }); // compatibility
cleanRange = std::regex_replace(cleanRange, std::regex(","), std::string(".."));
size_t dots;
dots = cleanRange.rfind("..");
if (dots == std::string::npos)
{
if (parameter) {
invalidParameters.insert(parameter);
}
return "";
}
std::string lower;
if (dots > 0) {
lower = cleanRange.substr(0, dots);
}
std::string upper = cleanRange.substr(dots + 2);
std::string expr;
expr = "(";
if (lower.empty() == false && lower != "-inf")
{
expr = expr + "(" + newParamName + "() >= " + lower + ")";
}
if (upper.empty() == false && upper != "inf")
{
if (expr != "(")
expr += " and ";
expr = expr + "(" + newParamName + "() <= " + upper + ")";
}
expr += ")";
if (expr == "()") {
expr.clear();
}
return expr;
}
void CyPhy2Desert::generateConstraint(const CyPhyML::Parameter ¶meter, DesertIface::Element &delem)
{
std::string expr = generateParameterConstraint(parameter, parameter.name());
if(expr=="()")
return;
if(expr.empty()) return;
std::string pname = parameter.name();
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
//int pid = parameter.uniqueId();
//char buffer[65];
//_itoa(pid, buffer, 10);
std::string pcon_name = pname+"_"+increaseCounter()+"_constraint";
dsConstraint.name() = pcon_name;
dsConstraint.expression() = "constraint "+ pcon_name+"() {\n" + expr+"\n}";
dsConstraint.context() = delem;
return;
}
std::string CyPhy2Desert::getFirstNumber(std::string &str)
{
std::string ret;
string tokens = "[(-0123456789infINF])";
size_t pos = str.find_first_of(tokens);
str.erase(0, pos);
pos = 0;
size_t end_pos = str.length();
size_t pos2 = str.find("..");
if(pos2!=std::string::npos)
end_pos = pos2;
else
{
pos2 = str.find_first_of(",");
if(pos2!=std::string::npos)
end_pos = pos2;
}
ret = str.substr(pos, end_pos-pos);
str.erase(0, end_pos);
return ret;
}
void CyPhy2Desert::processAlternativeValueFlowEnds(const set<CyPhyML::ValueFlowTarget>& alt_vfends) {
map<CyPhyML::DesignEntity, DesertIface::Element>::iterator pos;
for(set<CyPhyML::ValueFlowTarget>::iterator it=alt_vfends.begin();it!=alt_vfends.end();++it)
{
CyPhyML::ValueFlowTarget vfend = *it;
if(Uml::IsDerivedFrom(vfend.type(), CyPhyML::ValueFormula::meta))
continue;
set<CyPhyML::ValueFlow> src_vfs = vfend.srcValueFlow();
if(src_vfs.empty())
continue;
Udm::Object vfend_owner =vfend.GetParent();
ASSERT(Uml::IsDerivedFrom(vfend_owner.type(), CyPhyML::DesignEntity::meta));
CyPhyML::DesignEntity celem = CyPhyML::DesignEntity::Cast(vfend_owner);
DesertIface::Element delem;
pos = com2elemMap.find(celem);
if(pos!=com2elemMap.end())
delem = (*pos).second;
else
continue;
DesertIface::SimpleFormula dsf = DesertIface::SimpleFormula::Create(formulaSet);
dsf.ComputationType() = "PCM_OR";
dsf.context() = delem;
dsf.name() = "SimpleFormula";
dsf.id() = dsf.externalID() = vfend.uniqueId();
DesertIface::VariableProperty dvp = getVariableProperty(vfend,celem);
if(dvp == Udm::null)
{
dvp = DesertIface::VariableProperty::Create(delem);
updatevpMap(dvp, vfend, celem);
dvp.name() = dvp.CUSTName() = UdmUtil::ExtractName(vfend);
dvp.id() = dvp.externalID() = celem.ID()+5000;
}
dvp.parametric() = true;
dvp.PCM_STR() = "";
dsf.property_end() += dvp;
for(set<CyPhyML::ValueFlow>::iterator it_vf=src_vfs.begin();it_vf!=src_vfs.end();++it_vf)
{
CyPhyML::ValueFlowTarget src_end = (*it_vf).srcValueFlow_end();
if (Uml::IsDerivedFrom(src_end.type(), CyPhyML::Parameter::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Property::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Constant::meta)
)
{
Udm::Object src_end_parent = (*it_vf).srcValueFlow_refport_parent();
if(src_end_parent==Udm::null)
src_end_parent = src_end.GetParent();
if(!Uml::IsDerivedFrom(src_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
CyPhyML::DesignEntity src_parent = CyPhyML::DesignEntity::Cast(src_end_parent);
DesertIface::VariableProperty src_dvp = getVariableProperty(src_end, src_parent);
// std::string src_parent_name = src_parent.name();
// std::string src_end_name = src_end.name();
if(src_dvp==Udm::null)
{
DesertIface::Element vpParent;
pos = com2elemMap.find(src_parent);
if(pos!=com2elemMap.end())
vpParent = (*pos).second;
else
continue;
src_dvp = DesertIface::VariableProperty::Create(vpParent);
updatevpMap(src_dvp, src_end, src_parent);
int uid = src_end.uniqueId();
// char buffer[65];
// _itoa(uid, buffer, 10);
src_dvp.id() = src_dvp.externalID() = src_end.uniqueId()+5000;
}
dsf.srcProperty() += src_dvp;
}
}
}
}
DesertIface::Element CyPhy2Desert::getDesertElement(const CyPhyML::DesignEntity &obj)
{
DesertIface::Element ret;
map<CyPhyML::DesignEntity, DesertIface::Element>::iterator pos = com2elemMap.find(obj);
if(pos!=com2elemMap.end())
ret = (*pos).second;
return ret;
}
template <class T> void CyPhy2Desert::traverseContainer(const CyPhyML::DesignEntity &cyphy_elem, T &element_parent, CyPhyML::DesignEntity& currentGroup,bool isAlt)
{
DOEVENTS();
std::string tmp = cyphy_elem.getPath2();
addGroup(CyPhyML::DesignContainer::Cast(currentGroup));
Element element = Element::Create(element_parent);
com2elemMap[cyphy_elem] = element;
element.name() = cyphy_elem.name();
originalIDs[cyphy_elem] = (int)cyphy_elem.ID(); //reverse it back later
cyphy_elem.ID() = cyphy_elem.uniqueId(); //using uniqueID to avoid negative integer(maybe caused by overflow)
int elemID = (int)cyphy_elem.ID();
element.id() = element.externalID() = elemID;
if(!Uml::IsDerivedFrom(cyphy_elem.type(), DesignContainer::meta))
{
flatternComponent(cyphy_elem, element, isAlt);
}
else //DesignContainer
{
DesignContainer container = DesignContainer::Cast(cyphy_elem);
set<CyPhyML::ValueFlowTarget> alt_vfends;
// First make sure that the design container contains at least 1 design element in it (as per the designed/supported use-case)
set<DesignEntity> childrenDesignEntities = container.DesignEntity_kind_children();
if(childrenDesignEntities.empty()) {
int errConId = container.uniqueId();
std::stringstream ss;
ss << "The design container doesn't contain any design element in it:" << std::endl;
ss << "Name: " << container.name() << std::endl;
ss << "ID: " << UdmGme::UdmId2GmeId(errConId) << std::endl;
throw udm_exception(ss.str());
}
preprocessParameters(container);
bool dcAlt = ((std::string)container.ContainerType() != "Compound");
bool procSF = true;
const set<CyPhyML::Property> properties = container.Property_kind_children();
processProperties(properties, container, element, alt_vfends);
set<CyPhyML::Parameter> parameters = container.Parameter_kind_children();
processParameters(parameters, container, element, false, alt_vfends);
const set<CyPhyML::Constant> constants = container.Constant_kind_children();
processConstants(constants, container, element);
//const set<CyPhyML::SimpleFormula> sfs = container.SimpleFormula_kind_children();
//processSimpleFormulas(sfs, container, element);
const set<CyPhyML::ValueFormula> formulas = container.ValueFormula_kind_children();
pre_processValueFormulas(formulas, container, element);
if(!dcAlt)
element.decomposition() = true;
else
{
set<CyPhyML::ValueFlowTarget> alt_vfends;
element.decomposition() = false;
if(container.ContainerType() == "Optional")
{
Element nullelem = Element::Create(element);
nullelem.name() = "null";
//nullelem.id() = 0;
nullelem.id() = nullelem.externalID() = -1*container.ID();
//processProperties
{
for(set<CyPhyML::Property>::iterator nit=properties.begin();nit!=properties.end();++nit)
{
CyPhyML::Property propty = *nit;
set<CyPhyML::ValueFlow> dstvfs = propty.dstValueFlow();
if(dstvfs.empty()) continue;
CyPhyML::SimpleFormula sf;
for(set<CyPhyML::ValueFlow>::iterator vf_it=dstvfs.begin();vf_it!=dstvfs.end();++vf_it)
{
CyPhyML::ValueFlowTarget vftarget = (*vf_it).dstValueFlow_end();
if(Uml::IsDerivedFrom(vftarget.type(), CyPhyML::SimpleFormula::meta))
{
sf = CyPhyML::SimpleFormula::Cast(vftarget);
break;
}
}
double nullVal = 0;
if(sf!=Udm::null)
{
std::string method = sf.Method();
if(method=="Multiplication")
nullVal = 1;
else if(method=="Maximum")
nullVal = 0;
else if(method=="Minimum")
nullVal = 214748000;
else if(method=="GeometricMean")
nullVal = 1;
}
std::string pname = propty.name();
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
getDomainWithMember(pname, domain, nullVal, member);
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(nullelem);
vp.parametric() = false;
vp.name() = vp.CUSTName() = pname;
vp.id() = vp.externalID() = container.ID()+5100;
vp.PCM_STR() = "PCM_NONE";
vp.domain() =domain;
vp.Max() = 214748000;
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(nullelem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
}
}
}
}
processConstraints(container, element);
// Update Morph Matrix
// Add this container as an option to current group (if there is one)
// allOptions.insert(container);
// addGroup(CyPhyML::DesignContainer::Cast(currentGroup));
// Add this container as a new group (if not already there) before iterating over its children
addGroup(container);
set<CyPhyML::DesignEntity> entities = container.DesignEntity_kind_children();
for(set<CyPhyML::DesignEntity>::iterator i=entities.begin();i!=entities.end();++i)
traverseContainer(*i, element, container,dcAlt);
processAlternativeValueFlowEnds(alt_vfends);
for(auto it_f=formulas.begin();it_f!=formulas.end();++it_f)
{
CyPhyML::ValueFormula formula = *it_f;
//processSimpleFormulas
if(Uml::IsDerivedFrom(formula.type(), CyPhyML::SimpleFormula::meta))
processSimpleFormula(CyPhyML::SimpleFormula::Cast(formula), element);
else if(Uml::IsDerivedFrom(formula.type(), CyPhyML::CustomFormula::meta))
processCustomFormula(CyPhyML::CustomFormula::Cast(formula), element, isAlt);
}
processConnectors(container, element);
if(dcAlt)
processAlternativeParameters(container);
}
}
void CyPhy2Desert::processConnectors(const CyPhyML::DesignContainer &dc,DesertIface::Element &delem)
{
bool isAlt = ((std::string)dc.ContainerType() != "Compound");
set<CyPhyML::ConnectorComposition> ccs = dc.ConnectorComposition_kind_children();
set<CyPhyML::Connector> connectors = dc.Connector_kind_children();
set<std::string> uniqueConnectorNames;
for(auto it_sp=connectors.begin();it_sp!=connectors.end();++it_sp)
{
CyPhyML::Connector connector = *it_sp;
std::string c_name = connector.name();
std::string c_valid_name = checkInvalidName(c_name);
if(uniqueConnectorNames.find(c_valid_name)!=uniqueConnectorNames.end())
{
int cnt = uniqueConnectorNames.size();
char buffer[65];
_itoa_s(cnt, buffer, 10);
c_valid_name = c_valid_name+"_"+(std::string)buffer;
}
uniqueConnectorNames.insert(c_valid_name);
if(c_valid_name!=c_name)
{
connector.name() = c_valid_name;
CyPhy2Desert::originalNames[connector] = c_name;
}
set<CyPhyUtil::ComponentPort> connectedPorts;
set<CyPhyML::ConnectorComposition> src_ccs =connector.srcConnectorComposition();
for(auto it_src=src_ccs.begin();it_src!=src_ccs.end();++it_src)
{
CyPhyML::ConnectorComposition src_cc = *it_src;
if(ccs.find(src_cc)!=ccs.end())
{
CyPhyUtil::ComponentPort src_port;
src_port.port = src_cc.srcConnectorComposition_end();
src_port.port_ref_parent = src_cc.srcConnectorComposition_refport_parent();
connectedPorts.insert(src_port);
ccs.erase(src_cc);
}
}
set<CyPhyML::ConnectorComposition> dst_ccs = connector.dstConnectorComposition();
for(auto it_dst=dst_ccs.begin();it_dst!=dst_ccs.end();++it_dst)
{
CyPhyML::ConnectorComposition dst_cc = *it_dst;
if(ccs.find(dst_cc)!=ccs.end())
{
CyPhyUtil::ComponentPort dst_port;
dst_port.port = dst_cc.dstConnectorComposition_end();
dst_port.port_ref_parent = dst_cc.dstConnectorComposition_refport_parent();
connectedPorts.insert(dst_port);
ccs.erase(dst_cc);
}
}
}
if(isAlt) return;
for(auto it_js=ccs.begin();it_js!=ccs.end();++it_js)
{
CyPhyML::ConnectorComposition js = *it_js;
CyPhyUtil::ComponentPort src_port, dst_port;
src_port.port = js.srcConnectorComposition_end();
src_port.port_ref_parent = js.srcConnectorComposition_refport_parent();
dst_port.port = js.dstConnectorComposition_end();
dst_port.port_ref_parent = js.dstConnectorComposition_refport_parent();
Udm::Object src_port_parent = src_port.port.GetParent();
if(isAltPort(src_port, CyPhyML::ConnectorComposition::meta, "srcConnectorComposition", "dstConnectorComposition")
|| isAltPort(dst_port, CyPhyML::ConnectorComposition::meta, "srcConnectorComposition", "dstConnectorComposition"))
generateConstraint(src_port, dst_port, dc);
}
}
bool CyPhy2Desert::isAltPort(const CyPhyUtil::ComponentPort &port, const Uml::Class &objType, std::string srcRoleName, std::string dstRoleName)
{
Udm::Object port_parent;
if(port.port_ref_parent)
{
if(Uml::IsDerivedFrom(port.port_ref_parent.type(), CyPhyML::ComponentRef::meta))
port_parent = CyPhyML::ComponentRef::Cast(port.port_ref_parent).ref();
}
else
port_parent = port.port.GetParent();
if(!port_parent)
return false;
if(Uml::IsDerivedFrom(port_parent.type(), CyPhyML::DesignElement::meta))
return false;
if(Uml::IsDerivedFrom(port_parent.type(), CyPhyML::DesignContainer::meta))
{
CyPhyML::DesignContainer dc = CyPhyML::DesignContainer::Cast(port_parent);
if((std::string)dc.ContainerType()!="Compound")
return true;
Udm::Object::AssociationInfo assocInfo1(objType);
assocInfo1.strSrcRoleName = srcRoleName;
assocInfo1.strDstRoleName = dstRoleName;
set<Udm::Object> assocs = Udm::Object(port.port).GetAssociationClassObjects(NULL, assocInfo1);
assocInfo1.strSrcRoleName = dstRoleName;
assocInfo1.strDstRoleName = srcRoleName;
set<Udm::Object> assocs1 = Udm::Object(port.port).GetAssociationClassObjects(NULL, assocInfo1);
assocs.insert(assocs1.begin(), assocs1.end());
for(auto it=assocs.begin();it!=assocs.end();++it)
{
Udm::Object assoc = *it;
Udm::Object assoc_parent = assoc.GetParent();
if(assoc_parent!=dc)
continue;
CyPhyUtil::ComponentPortPair endpair = CyPhyUtil::getConnectionEnds(objType, assoc);
CyPhyUtil::ComponentPort peer_port = endpair.src == port? endpair.dst : endpair.src;
if(isAltPort(peer_port, objType, srcRoleName, dstRoleName))
return true;
}
}
return false;
}
bool CyPhy2Desert::isConnectedToAltPort(const CyPhyUtil::ComponentPort &port, const CyPhyML::DesignContainer &dc,
const Uml::Class &objType, std::string srcRoleName, std::string dstRoleName)
{
std::string tmp1=port.port.getPath2();
std::string tmp2=dc.getPath2();
if((std::string)dc.ContainerType()!="Compound")
return true;
Udm::Object port_parent;
if(port.port_ref_parent)
{
if(Uml::IsDerivedFrom(port.port_ref_parent.type(), CyPhyML::ComponentRef::meta))
port_parent = CyPhyML::ComponentRef::Cast(port.port_ref_parent).ref();
}
else
port_parent = port.port.GetParent();
if(!port_parent)
return false;
if(Uml::IsDerivedFrom(port_parent.type(), CyPhyML::DesignElement::meta))
return false;
if(!Uml::IsDerivedFrom(port_parent.type(), CyPhyML::DesignContainer::meta))
return false;
if(port_parent!=dc)
return isAltPort(port, objType, srcRoleName, dstRoleName);
CyPhyML::DesignContainer dc_parent;
Udm::Object dc_parent_obj = port_parent.GetParent();
if (Uml::IsDerivedFrom(dc_parent_obj.type(), CyPhyML::DesignContainer::meta))
dc_parent = CyPhyML::DesignContainer::Cast(dc_parent_obj);
else
return false;
Udm::Object::AssociationInfo assocInfo1(objType);
assocInfo1.strSrcRoleName = srcRoleName;
assocInfo1.strDstRoleName = dstRoleName;
set<Udm::Object> assocs = Udm::Object(port.port).GetAssociationClassObjects(NULL, assocInfo1);
assocInfo1.strSrcRoleName = dstRoleName;
assocInfo1.strDstRoleName = srcRoleName;
set<Udm::Object> assocs1 = Udm::Object(port.port).GetAssociationClassObjects(NULL, assocInfo1);
assocs.insert(assocs1.begin(), assocs1.end());
for(auto it=assocs.begin();it!=assocs.end();++it)
{
Udm::Object assoc = *it;
Udm::Object assoc_parent = assoc.GetParent();
CyPhyUtil::ComponentPortPair endpair = CyPhyUtil::getConnectionEnds(objType, assoc);
CyPhyUtil::ComponentPort peer_port = endpair.src == port? endpair.dst : endpair.src;
if(assoc_parent==dc_parent)
{
if(isConnectedToAltPort(peer_port, dc_parent, objType, srcRoleName, dstRoleName))
return true;
}
else if(assoc_parent==dc)
{
if(isAltPort(peer_port,objType, srcRoleName, dstRoleName))
return true;
}
}
return false;
}
DesertIface::VariableProperty CyPhy2Desert::createDesertVP_PCMNONE(DesertIface::Element &delem, std::string name, double value)
{
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
if(!getDomainWithMember(name, domain, value, member))
throw udm_exception("Property/Parameter: "+name+" of component: "+(std::string)delem.name()+" is not NaturalDomain. Please check the ComputationType.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(delem);
// updatevpMap(vp, cyphyProp, cyphy_com);
vp.parametric() = false;
vp.name() = vp.CUSTName() = name;
vp.id() = vp.externalID() = delem.externalID()+5000;
vp.PCM_STR() = "PCM_NONE";
vp.Max() = 10000000000000;
vp.domain() =domain;
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(delem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
return vp;
}
void CyPhy2Desert::generateConstraint(CyPhyUtil::ComponentPort &port1, CyPhyUtil::ComponentPort &port2, const CyPhyML::DesignEntity &celem,bool isdefault)
{
DesertIface::Element delem = getDesertElement(celem);
if(!delem)
throw udm_exception(std::string(celem.name())+" cannot find the desert element.");
Udm::Object port1_parent = port1.port_ref_parent;
if(!port1_parent)
port1_parent = port1.port.GetParent();
if(!Uml::IsDerivedFrom(port1_parent.type(), CyPhyML::DesignEntity::meta))
return;
DesertIface::VariableProperty dvp1 = getVariableProperty(port1.port, CyPhyML::DesignEntity::Cast(port1_parent));
if(!dvp1) return;
Udm::Object port2_parent = port2.port_ref_parent;
if(!port2_parent)
port2_parent = port2.port.GetParent();
if(!Uml::IsDerivedFrom(port2_parent.type(), CyPhyML::DesignEntity::meta))
return;
DesertIface::VariableProperty dvp2 = getVariableProperty(port2.port, CyPhyML::DesignEntity::Cast(port2_parent));
if(!dvp2) return;
std::string port1_path = DFUtil::getRelativePath((Udm::Object)port1.port, port1_parent, celem)+UdmUtil::ExtractName(port1.port);
std::string port2_path = DFUtil::getRelativePath((Udm::Object)port2.port, port2_parent, celem)+UdmUtil::ExtractName(port2.port);
std::string expr ="("+ port1_path+"()="+port2_path+"()"+")";
expr += ("\nor\n("+port1_path+"()=0)");
expr += ("\nor\n("+port2_path+"()=0)");
DesertIface::Constraint dconstraint = DesertIface::Constraint::Create(constraintSet);
std::string con_name = UdmUtil::ExtractName(port1.port)+"_"+UdmUtil::ExtractName(port2.port)+CyPhy2Desert::increaseCounter()+"_constraint";
dconstraint.name() = con_name;
dconstraint.context() = delem;
dconstraint.expression() = "constraint "+ con_name+"() {\n" + expr+"\n}";
if(isdefault)
{
defaultConstraints.insert(con_name);
}
}
bool CyPhy2Desert::isConstantProperty(set<CyPhyML::ValueFlow> &src_vfs)
{
bool ret = true;
for(set<CyPhyML::ValueFlow>::iterator i=src_vfs.begin();i!=src_vfs.end();++i)
{
CyPhyML::ValueFlowTarget src_vf = (*i).srcValueFlow_end();
set<CyPhyML::ValueFlow> in_vfs = src_vf.srcValueFlow();
//need filter out the componentref
if (Uml::IsDerivedFrom(src_vf.type(), CyPhyML::Parameter::meta) || Uml::IsDerivedFrom(src_vf.type(), CyPhyML::Property::meta))
{
if(!in_vfs.empty())
return false;
}
else
if(!isConstantProperty(in_vfs)) return false;
}
return ret;
}
//process Parametric Property(direct valueflow, dst of Customformula/SimpleFormula)
void CyPhy2Desert::processProperty(const CyPhyML::DesignEntity &cyphy_com, DesertIface::Element &desert_elem, Udm::Object &prop,set<CyPhyML::ValueFlow> &src_vfs,
set<CyPhyML::ValueFlowTarget>& alt_vfends)
{
if(cyphy_com.type()==CyPhyML::DesignContainer::meta)
{
CyPhyML::DesignContainer dc = CyPhyML::DesignContainer::Cast(cyphy_com);
if((std::string)dc.ContainerType()!="Compound" && src_vfs.size()>1)
{
if(Uml::IsDerivedFrom(prop.type(), CyPhyML::ValueFlowTarget::meta))
alt_vfends.insert(CyPhyML::ValueFlowTarget::Cast(prop));
return;
}
}
std::string propname = UdmUtil::ExtractName(prop);
if (src_vfs.size()>1)
throw udm_exception("<a href=\"mga:" + UdmGme::UdmId2GmeId(prop.uniqueId()) + "\">" + propname + "</a> cannot have more than one source ValueFlow if it has one end of Property/Parameter.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(desert_elem);
updatevpMap(vp, prop, cyphy_com);
vp.parametric() = true;
vp.name() = vp.CUSTName() = propname;
vp.id() = vp.externalID() = cyphy_com.ID()+5000;
CyPhyML::ValueFlow src_vf = *(src_vfs.begin());
CyPhyML::ValueFlowTarget src_vf_end = src_vf.srcValueFlow_end();
Udm::Object src_vf_end_parent = src_vf.srcValueFlow_refport_parent();
if(src_vf_end_parent==Udm::null)
src_vf_end_parent = src_vf_end.parent();
//for direct ValueFlow
if (Uml::IsDerivedFrom(src_vf_end.type(), CyPhyML::Parameter::meta)
|| Uml::IsDerivedFrom(src_vf_end.type(), CyPhyML::Property::meta)
|| Uml::IsDerivedFrom(src_vf_end.type(), CyPhyML::Constant::meta)
)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(formulaSet);
dcf.name() = propname;
std::string expr = "constraint formula_" + increaseCounter() + "_" + propname + " () {"
+ DFUtil::getRelativePath(src_vf_end, src_vf_end_parent, cyphy_com) + std::string(src_vf_end.name()) + "()";
if (src_vf.GetParent().type() == CyPhyML::DesignContainer::meta)
{
CyPhyML::DesignContainer dc = CyPhyML::DesignContainer::Cast(src_vf.GetParent());
if ((std::string)dc.ContainerType() == "Optional") {
expr += " or " +
DFUtil::getRelativePath(src_vf_end, src_vf_end_parent.GetParent(), cyphy_com) +
std::string("children(\"null\").") + std::string(src_vf_end.name()) + "()";
}
else if ((std::string)dc.ContainerType() == "Alternative") {
// FIXME tbd
}
}
expr += "}";
dcf.expression() = expr;
dcf.property_end() += vp;
dcf.context() = desert_elem;
}
//if the property is the dst end of CustomFormula/SimpleFormula, it will be processed in processCustomFormula/processSimpleformula
}
//process non-parametric Parameter(natual number)
void CyPhy2Desert::processProperty(const CyPhyML::DesignEntity &cyphy_com, DesertIface::Element &desert_elem,
const std::string &pname, double value, const std::string &compType, Udm::Object cyphyProp, bool assignValue)
{
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
if(!getDomainWithMember(pname, domain, value, member))
throw udm_exception("Property/Parameter: "+pname+" of component: "+(std::string)cyphy_com.name()+" is not NaturalDomain. Please check the ComputationType.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(desert_elem);
updatevpMap(vp, cyphyProp, cyphy_com);
vp.parametric() = false;
vp.name() = vp.CUSTName() = pname;
vp.id() = vp.externalID() = cyphy_com.ID()+5000;
vp.PCM_STR() = "PCM_NONE";
if(isAlternativeContainer(CyPhyML::DesignEntity(cyphy_com)) && Uml::IsDerivedFrom(cyphyProp.type(), CyPhyML::ValueFlowTarget::meta))
{
CyPhyML::ValueFlowTarget vftarget = CyPhyML::ValueFlowTarget::Cast(cyphyProp);
set<CyPhyML::ValueFlow> srcvfs = vftarget.srcValueFlow();
set<CyPhyML::ValueFlow> dstvfs = vftarget.dstValueFlow();
if(srcvfs.empty() && dstvfs.empty())
vp.PCM_STR() = "PCM_ADD";
else if(!srcvfs.empty())
{
CyPhyML::ValueFlow vf = *(srcvfs.begin());
Udm::Object vf_parent = vf.parent();
if(vf_parent==cyphy_com)
vp.PCM_STR() = "PCM_ADD";
}
else if(!dstvfs.empty())
{
for(set<CyPhyML::ValueFlow>::iterator it=dstvfs.begin();it!=dstvfs.end();++it)
{
CyPhyML::ValueFlow dstvf = *it;
Udm::Object vf_parent = dstvf.parent();
if(vf_parent!=cyphy_com)
{
vp.PCM_STR() = "PCM_ADD";
break;
}
}
}
}
vp.Max() = 100000;
vp.domain() =domain;
if(assignValue)
{
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(desert_elem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
}
}
//process non-parametric Parameter(string type value)
void CyPhy2Desert::processProperty(const CyPhyML::DesignEntity &cyphy_com, DesertIface::Element &desert_elem,
const std::string &pname, const std::string &value)
{
DesertIface::CustomDomain domain;
DesertIface::CustomMember member;
if(!getDomainWithMember(pname,domain,value,member))
throw udm_exception("Property/Parameter: "+pname+" of component: "+(std::string)cyphy_com.name()+" is not CustomDomain. Please check the ComputationType.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(desert_elem);
vp.parametric() = false;
vp.name() = vp.CUSTName() = pname;
vp.id() = vp.externalID() = cyphy_com.uniqueId()+1;
vp.PCM_STR() = "PCM_NOP";
vp.domain() = domain;
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(desert_elem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
}
double CyPhy2Desert::getPropertyNumberValue(CyPhyML::ValueFlowTarget &vft)
{
if(vft.type()!=CyPhyML::Property::meta && vft.type()!=CyPhyML::Parameter::meta)
return 0;
double ret = 0;
set<CyPhyML::ValueFlow> srcfs = vft.srcValueFlow();
set<CyPhyML::SimpleFormula> sfs;
for(set<CyPhyML::ValueFlow>::iterator i=srcfs.begin();i!=srcfs.end();++i)
{
CyPhyML::ValueFlowTarget dvft = (*i).srcValueFlow_end();
if(dvft.type()==CyPhyML::SimpleFormula::meta)
sfs.insert(CyPhyML::SimpleFormula::Cast(dvft));
}
if(srcfs.empty() || sfs.empty())
{
std::string svalue;
if(vft.type()==CyPhyML::Property::meta)
svalue = (CyPhyML::Property::Cast(vft)).Value();
else if(vft.type()==CyPhyML::Parameter::meta)
svalue = (CyPhyML::Parameter::Cast(vft)).Value();
ret = atof(svalue.c_str());
return ret;
}
if(sfs.size()>1)
return 0;
CyPhyML::SimpleFormula sf = *(sfs.begin());
std::string method = sf.Method();
double dret;
vector<double> args;
set<CyPhyML::ValueFlow> sf_srcs = sf.srcValueFlow();
for(set<CyPhyML::ValueFlow>::iterator si=sf_srcs.begin();si!=sf_srcs.end();++si)
{
CyPhyML::ValueFlowTarget src_arg = (*si).srcValueFlow_end();
if(src_arg.type()!=CyPhyML::Property::meta && src_arg.type()!=CyPhyML::Parameter::meta)
continue;
std::string strval;
if(src_arg.type()==CyPhyML::Property::meta)
{
CyPhyML::Property cprop = CyPhyML::Property::Cast(src_arg);
std::string ct = cprop.ComputationType();
//if(ct=="None" || ct=="Custom")
if(ct=="Custom")
continue;
strval= cprop.Value();
}
else
{
CyPhyML::Parameter cpara = CyPhyML::Parameter::Cast(src_arg);
std::string ct = cpara.ComputationType();
//if(ct=="None" || ct=="Custom")
if(ct=="Custom")
continue;
strval= cpara.Value();
}
args.push_back(atof(strval.c_str()));
}
if(method=="Addition")
dret = getAdditionValue(args);
else if(method=="Multiplication")
dret = getMultiplicationValue(args);
else if(method=="Maximum")
dret = getMaximumValue(args);
else if(method=="Minimum")
dret = getMinimumValue(args);
else if(method=="ArithmeticMean")
dret = getArithMeanValue(args);
else if(method=="GeometricMean")
dret = getGeometriMeanValue(args);
return dret;
}
bool CyPhy2Desert::getDomainWithMember(const std::string &dname, DesertIface::NaturalDomain &domain,
double value, DesertIface::NaturalMember &member)
{
map<std::string, DesertIface::Domain>::iterator pos = domainMap.find(dname);
if(pos==domainMap.end())
{
domain = generateNaturalDomain(dsystem, dname);
domainMap[dname] = domain;
}
else
{
DesertIface::Domain domain_base = (*pos).second;
if(domain_base.type()!=DesertIface::NaturalDomain::meta)
return false; //this error may be cuased by its parent container which also contains this property/parameter, but incorrect computationType
domain = DesertIface::NaturalDomain::Cast(domain_base);
}
if(domain.maximum()<value)
domain.maximum() = value+1;
if(domain.minimum()>value)
domain.minimum() = value-1;
map<double, DesertIface::NaturalMember> memberMap;
map<DesertIface::NaturalDomain, map<double, DesertIface::NaturalMember> >::iterator mpos = natureMemberMap.find(domain);
if(mpos != natureMemberMap.end())
{
memberMap = (*mpos).second;
}
map<double, DesertIface::NaturalMember>::iterator mempos = memberMap.find(value);
if(mempos==memberMap.end())
{
static int memberId = 0;
member = DesertIface::NaturalMember::Create(domain);
member.id() = member.externalID() = memberId;
memberId++;
member.value() = value;
memberMap[value] = member;
natureMemberMap[domain] = memberMap;
}
else
member = (*mempos).second;
return true;
}
bool CyPhy2Desert::getDomainWithMember(const std::string &dname, DesertIface::CustomDomain &domain,
const std::string &value, DesertIface::CustomMember &member)
{
map<std::string, DesertIface::Domain>::iterator pos = domainMap.find(dname);
if(pos==domainMap.end())
{
domain = generateCustomDomain(dname);
domainMap[dname] = domain;
}
else
{
DesertIface::Domain domain_base = (*pos).second;
if(domain_base.type()!=DesertIface::CustomDomain::meta)
return false;
domain = DesertIface::CustomDomain::Cast(domain_base);
}
map<std::string, DesertIface::CustomMember> memberMap;
map<DesertIface::CustomDomain, map<std::string, DesertIface::CustomMember> >::iterator mpos = custMemberMap.find(domain);
if(mpos != custMemberMap.end())
{
memberMap = (*mpos).second;
}
map<std::string, DesertIface::CustomMember>::iterator mempos = memberMap.find(value);
if(mempos==memberMap.end())
{
static int memberId = 0;
member = DesertIface::CustomMember::Create(domain);
member.id() = member.externalID() = memberId;
memberId++;
member.name() = value;
memberMap[value] = member;
custMemberMap[domain] = memberMap;
}
else
member = (*mempos).second;
return true;
}
void CyPhy2Desert::processConstraints(const CyPhyML::DesignContainer &cyphy_container, DesertIface::Element &desert_elem)
{
DOEVENTS();
const set<CyPhyML::Constraint> constraints = cyphy_container.Constraint_kind_children();
for(set<CyPhyML::Constraint>::iterator ci=constraints.begin();ci!=constraints.end();++ci)
{
CyPhyML::Constraint constraint = *ci;
if(constraint.Inactive()) continue;
if(std::string(constraint.Context()).empty()) continue;
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
dsConstraint.name() = constraint.name();
dsConstraint.id() = dsConstraint.externalID() = constraint.ID();
dsConstraint.expression() = constraint.Context();
dsConstraint.context() = desert_elem;
constraintMap[dsConstraint] = constraint;
}
const set<CyPhyML::VisualConstraint> vcons = cyphy_container.VisualConstraint_kind_children();
for(set<CyPhyML::VisualConstraint>::iterator vci=vcons.begin();vci!=vcons.end();++vci)
{
CyPhyML::VisualConstraint vcon = *vci;
if(vcon.Inactive()) continue;
std::string expr = generateVisualConstraint(cyphy_container, vcon);
if(expr.empty()) continue;
//create the constraint in desert
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
std::string name = vcon.name();
dsConstraint.name() = name;
dsConstraint.id() = dsConstraint.externalID() = vcon.ID();
dsConstraint.expression() = "constraint "+ (std::string)vcon.name()+"() {\n" + expr+"\n}";
dsConstraint.context() = desert_elem;
constraintMap[dsConstraint] = vcon;
}
const set<CyPhyML::DecisionGroup> groups = cyphy_container.DecisionGroup_kind_children();
for(set<CyPhyML::DecisionGroup>::iterator git=groups.begin();git!=groups.end();++git)
{
CyPhyML::DecisionGroup group = *git;
const set<CyPhyML::DesignEntityRef> refs = group.DesignEntityRef_kind_children();
set<CyPhyML::DesignContainer> groupContainers;
for(set<CyPhyML::DesignEntityRef>::iterator ref_it=refs.begin();ref_it!=refs.end();++ref_it)
{
CyPhyML::DesignEntity dentiti = (*ref_it).ref();
if (!dentiti)
{
throw udm_exception("Invalid Decision Group reference " + ref_it->getPath("/", false, false));
}
if(Uml::IsDerivedFrom(dentiti.type(), CyPhyML::DesignContainer::meta))
{
CyPhyML::DesignContainer container = CyPhyML::DesignContainer::Cast(dentiti);
if((std::string)container.ContainerType()!="Compound")
groupContainers.insert(container);
}
}
if(groupContainers.size()>1)
{
// map<std::string, list<CyPhyML::DesignEntity> > groups;
// if((std::string)group.DecisionCriteria()=="SameName")
// gatherGroupBasedOnName(groupContainers, groups);
// else
// gatherGroupBasedOnArchType(groupContainers, groups);
//generateConstraint(groups, cyphy_container, desert_elem);
map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> > groups;
gatherGroupBasedOnRef(groupContainers, groups);
if(!generateConstraint(groups, cyphy_container, desert_elem))
invalidGroups.insert(group);
}
}
const set<CyPhyML::PropertyConstraint> pcons = cyphy_container.PropertyConstraint_kind_children();
for(set<CyPhyML::PropertyConstraint>::iterator pit=pcons.begin();pit!=pcons.end();++pit)
{
CyPhyML::PropertyConstraint pcon = *pit;
if(pcon.Inactive()) continue;
set<CyPhyML::PropertyConstraintRef> pcon_refs = pcon.referedbyPropertyConstraintRef();
if(!pcon_refs.empty()) continue;
std::string expr;
std::string rtype = pcon.TargetType();
if(rtype == "Must Exceed")
expr = " > ";
else if(rtype == "Must Not Exceed")
expr = " <= ";
else if(rtype == "Must Equal")
expr = " = ";
else if(rtype == "Must Equal or Exceed")
expr = " >= ";
else if(rtype == "Must Be Less Than")
expr = " < ";
char limit[64];
double dv = pcon.TargetValue();
sprintf_s(limit,"%.17g",dv);
expr += (std::string)limit;
set<CyPhyML::PropertyConstraintBinding> bindings = pcon.dstPropertyConstraintBinding();
for(set<CyPhyML::PropertyConstraintBinding>::iterator bit=bindings.begin();bit!=bindings.end();++bit)
{
std::string currExpr;
CyPhyML::Property propertCon = (*bit).dstPropertyConstraintBinding_end();
//create the constraint in desert
std::string dsconName = (std::string)cyphy_container.name()+"_"+(std::string)pcon.name()+"_constraint";
Udm::Object propParent = propertCon.parent();
if(cyphy_container == propParent)
currExpr = (std::string)propertCon.name() + "()" + expr;
else
currExpr = "children(\""+UdmUtil::ExtractName(propParent)+"\")."+(std::string)propertCon.name() + "()" + expr;
if (Uml::IsDerivedFrom(cyphy_container.type(), CyPhyML::DesignContainer::meta))
{
auto dc = CyPhyML::DesignContainer::Cast(cyphy_container);
if (dc.ContainerType() == "Optional")
{
// if optional is not selected, constraint doesn't matter
currExpr = std::string("implementedBy() = children(\"null\") or ") + currExpr;
}
}
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
dsConstraint.name() = dsconName;
dsConstraint.id() = dsConstraint.externalID() = pcon.ID();
dsConstraint.expression() = "constraint "+ dsconName+"() {\n" + currExpr+"\n}";
dsConstraint.context() = desert_elem;
constraintMap[dsConstraint] = pcon;
}
}
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::ImpliesEnd &iend, const Udm::Object &container)
{
if(Uml::IsDerivedFrom(iend.type(), CyPhyML::And_Or::meta))
return generateConstraint(CyPhyML::And_Or::Cast(iend), container);
else if(Uml::IsDerivedFrom(iend.type(), CyPhyML::DesignEntityRef::meta))
return generateConstraint(CyPhyML::DesignEntityRef::Cast(iend), container);
else if(Uml::IsDerivedFrom(iend.type(), CyPhyML::NullOptionRef::meta))
return generateConstraint(CyPhyML::NullOptionRef::Cast(iend), container);
else if(Uml::IsDerivedFrom(iend.type(), CyPhyML::PropertyConstraintRef::meta))
return generateConstraint(CyPhyML::PropertyConstraintRef::Cast(iend), container);
return "";
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::And_Or &and_or, const Udm::Object &container)
{
std::string ret;
std::string op;
op = Uml::IsDerivedFrom(and_or.type(), CyPhyML::Or_operator::meta) ? " or " : " and "; //for or_operator: or; for and and not operator: and
set<CyPhyML::ImpliesEnd> implyends = and_or.ImpliesEnd_kind_children();
bool mul = implyends.size()>1 ? true : false;
set<CyPhyML::ImpliesEnd>::iterator i=implyends.begin();
while(i!=implyends.end())
{
CyPhyML::ImpliesEnd currend = *i;
std::string context;
if(Uml::IsDerivedFrom(currend.type(), CyPhyML::DesignEntityRef::meta))
context = generateConstraint(CyPhyML::DesignEntityRef::Cast(currend), container);
else if(Uml::IsDerivedFrom(currend.type(), CyPhyML::And_Or::meta))
context = generateConstraint(CyPhyML::And_Or::Cast(currend), container);
else if(Uml::IsDerivedFrom(currend.type(), CyPhyML::NullOptionRef::meta))
context = generateConstraint(CyPhyML::NullOptionRef::Cast(currend), container);
else if(Uml::IsDerivedFrom(currend.type(), CyPhyML::PropertyConstraintRef::meta))
context = generateConstraint(CyPhyML::PropertyConstraintRef::Cast(currend), container);
if(Uml::IsDerivedFrom(and_or.type(), CyPhyML::Not_operator::meta))
context = "not("+context+")";
ret += context;
i++;
if(mul && i!=implyends.end())
ret = ret + "\n" + op + "\n";
}
if(!ret.empty())
ret = "(" + ret + ")\n";
return ret;
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::DesignEntityRef &elem_ref, const Udm::Object &container)
{
CyPhyML::DesignEntity entity = CyPhyML::DesignEntity::Cast(elem_ref.ref());
return generateConstraint(entity, container);
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::NullOptionRef &null_ref, const Udm::Object &container)
{
CyPhyML::DesignContainer optionCon = null_ref.ref();
if(optionCon==Udm::null) return "";
return generateImplConstraint(optionCon, container, "null");
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::PropertyConstraintRef &pcon_ref, const Udm::Object &container)
{
CyPhyML::PropertyConstraint pcon = pcon_ref.ref();
if(pcon==Udm::null) return "";
return generateConstraint(pcon, container);
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::PropertyConstraint &pcon, const Udm::Object &container)
{
set<CyPhyML::PropertyConstraintBinding> bindings = pcon.dstPropertyConstraintBinding();
if(bindings.empty()) return "";
std::string ret;
std::string expr;
std::string rtype = pcon.TargetType();
if(rtype == "Must Exceed")
expr = " > ";
else if(rtype == "Must Not Exceed")
expr = " <= ";
else if(rtype == "Must Equal")
expr = " = ";
else if(rtype == "Must Equal or Exceed")
expr = " >= ";
else if(rtype == "Must Be Less Than")
expr = " < ";
char limit[64];
double dv = pcon.TargetValue();
sprintf_s(limit,"%.17g",dv);
expr += (std::string)limit;
set<CyPhyML::PropertyConstraintBinding>::iterator bit;
while(!bindings.empty())
{
bit = bindings.begin();
CyPhyML::Property prop = (*bit).dstPropertyConstraintBinding_end();
Udm::Object propParent = prop.parent();
std::string path = getPath(propParent, container);
ret = ret + "("+path+(std::string)prop.name() + "()" + expr+")";
bindings.erase(bit);
if(!bindings.empty())
ret += " and ";
}
return ret;
}
std::string CyPhy2Desert::getPath(const Udm::Object &obj, const Udm::Object &container)
{
std::string path("self.");
Udm::Object pobj = obj;
list<Udm::Object> childrenlist;
while(pobj!=container && Uml::IsDerivedFrom(pobj.type(), CyPhyML::DesignContainer::meta))
{
childrenlist.push_front(pobj);
pobj = pobj.GetParent();
}
if(pobj == container)
{
for(list<Udm::Object>::iterator i=childrenlist.begin();i!=childrenlist.end();++i)
{
path = path+"children(\""+UdmUtil::ExtractName(*i)+"\").";
}
}
else if(Uml::IsDerivedFrom(pobj.type(), CyPhyML::RootFolder::meta) || Uml::IsDerivedFrom(pobj.type(), CyPhyML::DesignSpace::meta))
{
pobj = container.GetParent();
int cnt = 1;
bool found = false;
list<Udm::Object>::iterator i;
while(Uml::IsDerivedFrom(pobj.type(), CyPhyML::DesignContainer::meta))
{
for(i=childrenlist.begin();i!=childrenlist.end();++i)
{
if(*i == pobj)
{
found = true;
break;
}
}
if(!found)
{
pobj = pobj.GetParent();
cnt++;
}
else
{
if(i==childrenlist.begin())
childrenlist.erase(childrenlist.begin());
else
childrenlist.erase(childrenlist.begin(),i);
break;
}
}
for(int t=0;t<cnt;++t)
path += "parent().";
for(i=childrenlist.begin();i!=childrenlist.end();++i)
path = path+"children(\""+UdmUtil::ExtractName(*i)+"\").";
}
return path;
}
std::string CyPhy2Desert::generateImplConstraint(Udm::Object &pobj, const Udm::Object &container, const std::string &impl)
{
std::string ret;
std::string path = getPath(pobj, container);
ret = path + "implementedBy() = " + path+"children(\""+impl+"\")";
if(!ret.empty())
ret = "(" + ret + ")\n";
return ret;
}
std::string CyPhy2Desert::generateConstraint(const CyPhyML::DesignEntity &entity, const Udm::Object &container)
{
if(entity==Udm::null) return "";
Udm::Object pobj = entity.parent();
return generateImplConstraint(pobj, container, (std::string)entity.name());
}
set<std::string> CyPhy2Desert::getNatualParameters()
{
return naturalParameters;
}
set<std::string> CyPhy2Desert::getCustomParameters()
{
return customParameters;
}
set<std::string> CyPhy2Desert::getGroupConstraits()
{
return defaultConstraints;
}
set<std::string> CyPhy2Desert::getDefaultConstraits()
{
return defaultConstraints;
}
double CyPhy2Desert::getAdditionValue(vector<double> args)
{
double ret = 0;
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
ret += *i;
}
return ret;
}
double CyPhy2Desert::getMultiplicationValue(vector<double> args)
{
double ret = 1;
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
ret *= *i; //for temporary use, because the model integer is too large
}
return ret;
}
double CyPhy2Desert::getMaximumValue(vector<double> args)
{
if(args.empty()) return 0;
double ret = *(args.begin());
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
if(*i > ret) ret = *i;
}
return ret;
}
double CyPhy2Desert::getMinimumValue(vector<double> args)
{
if(args.empty()) return 0;
double ret = *(args.begin());
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
if(*i < ret) ret = *i;
}
return ret;
}
double CyPhy2Desert::getArithMeanValue(vector<double> args)
{
double ret = 0;
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
ret += *i;
}
if(!args.empty())
ret = ret / (args.size());
return ret;
}
double CyPhy2Desert::getGeometriMeanValue(vector<double> args)
{
double ret = 1;
for(vector<double>::iterator i=args.begin();i!=args.end();++i)
{
ret *= *i;
}
if(!args.empty())
{
double x = 1/args.size();
ret = pow(ret, x);
}
return ret;
}
void CyPhy2Desert::gatherGroupBasedOnName(set<CyPhyML::DesignContainer> &containers, map<std::string, list<CyPhyML::DesignEntity> > &groups)
{
for(set<CyPhyML::DesignContainer>::iterator it=containers.begin();it!=containers.end();++it)
{
set<CyPhyML::DesignEntity> entities = (*it).DesignEntity_kind_children();
for(set<CyPhyML::DesignEntity>::iterator eit=entities.begin();eit!=entities.end();++eit)
{
std::string ename = (*eit).name();
list<CyPhyML::DesignEntity> tmp;
map<std::string, list<CyPhyML::DesignEntity> >::iterator pos = groups.find(ename);
if(pos!=groups.end())
tmp = (*pos).second;
tmp.push_back(*eit);
groups[ename] = tmp;
}
}
}
void CyPhy2Desert::gatherGroupBasedOnRef(set<CyPhyML::DesignContainer> &containers, map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> > &groups)
{
for(set<CyPhyML::DesignContainer>::iterator it=containers.begin();it!=containers.end();++it)
{
set<CyPhyML::DesignEntity> entities = (*it).DesignEntity_kind_children();
for(set<CyPhyML::DesignEntity>::iterator eit=entities.begin();eit!=entities.end();++eit)
{
CyPhyML::DesignEntity curr_entity = *eit;
if(Uml::IsDerivedFrom(curr_entity.type(), CyPhyML::ComponentRef::meta))
{
CyPhyML::DesignElement de = (CyPhyML::ComponentRef::Cast(curr_entity)).ref();
if(de==Udm::null)
{
nullComponentRefs.insert(CyPhyML::ComponentRef::Cast(curr_entity));
continue;
}
list<CyPhyML::DesignEntity> tmp;
map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> >::iterator pos = groups.find(de);
if(pos!=groups.end())
tmp = (*pos).second;
tmp.push_back(curr_entity);
groups[de] = tmp;
}
}
}
}
void CyPhy2Desert::gatherGroupBasedOnArchType(set<CyPhyML::DesignContainer> &containers, map<std::string, list<CyPhyML::DesignEntity> > &groups)
{
if(containers.size() < 2) return;
set<CyPhyML::DesignContainer>::iterator it = containers.begin();
CyPhyML::DesignContainer firstContainer = *it;
}
void CyPhy2Desert::generateConstraint(map<std::string, list<CyPhyML::DesignEntity> > &groups, const Udm::Object &container, DesertIface::Element &desert_elem)
{
for(map<std::string, list<CyPhyML::DesignEntity> >::iterator pos=groups.begin();pos!=groups.end();++pos)
{
list<CyPhyML::DesignEntity> entities = (*pos).second;
CyPhyML::DesignEntity firstEntity = entities.front();
entities.pop_front();
std::string expr = generateConstraint(firstEntity, container)+"implies\n(";
while(!entities.empty())
{
CyPhyML::DesignEntity currEntity = entities.front();
entities.pop_front();
if(!entities.empty())
expr = expr + generateConstraint(currEntity, container) +"and\n";
else
expr = expr + generateConstraint(currEntity, container) +"";
}
expr += ")";
groupCount++;
char buffer[12];
_itoa_s(groupCount, buffer, 10);
std::string constraintName = "group_constraint"+std::string(buffer);
defaultConstraints.insert(constraintName);
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
dsConstraint.name() = constraintName;
/*dsConstraint.id() = dsConstraint.externalID() = vcon.ID();*/
dsConstraint.expression() = "constraint "+ constraintName+"() {\n" + expr+"\n}";
dsConstraint.context() = desert_elem;
}
}
bool CyPhy2Desert::generateConstraint(map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> > &groups, const Udm::Object &container, DesertIface::Element &desert_elem)
{
bool ret = true;
for(map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> >::iterator pos1=groups.begin();pos1!=groups.end();++pos1)
{
list<CyPhyML::DesignEntity> entities = (*pos1).second;
if(entities.size()<2)
{
return false;
}
}
for(map<CyPhyML::DesignElement, list<CyPhyML::DesignEntity> >::iterator pos=groups.begin();pos!=groups.end();++pos)
{
list<CyPhyML::DesignEntity> entities = (*pos).second;
CyPhyML::DesignEntity firstEntity = entities.front();
entities.pop_front();
std::string expr = generateConstraint(firstEntity, container)+"implies\n(";
while(!entities.empty())
{
CyPhyML::DesignEntity currEntity = entities.front();
entities.pop_front();
if(!entities.empty())
expr = expr + generateConstraint(currEntity, container) +"and\n";
else
expr = expr + generateConstraint(currEntity, container) +"";
}
expr += ")";
groupCount++;
char buffer[12];
_itoa_s(groupCount, buffer, 10);
std::string constraintName = "group_constraint"+std::string(buffer);
defaultConstraints.insert(constraintName);
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
dsConstraint.name() = constraintName;
/*dsConstraint.id() = dsConstraint.externalID() = vcon.ID();*/
dsConstraint.expression() = "constraint "+ constraintName+"() {\n" + expr+"\n}";
dsConstraint.context() = desert_elem;
}
return ret;
}
map<int, CyPhyML::DesignEntity> CyPhy2Desert::getMorphMatrixGroup()
{
return mgroupMap;
}
map<int, CyPhyML::DesignEntity> CyPhy2Desert::getMorphMatrixOption()
{
return moptionMap;
}
std::string CyPhy2Desert::getRelativePath(Udm::Object &obj, const CyPhyML::DesignEntity &cyphy_elem)
{
std::string ret;
if(obj == Udm::null) return ret;
Udm::Object pobj = obj.GetParent();
if(pobj == cyphy_elem)
ret = "";
else
{
Udm::Object ppobj = pobj.GetParent();
if(ppobj == cyphy_elem)
{
ret = "children(\""+UdmUtil::ExtractName(pobj)+"\").";
}
else
{
Udm::Object cobj = cyphy_elem.parent();
if(cobj == pobj)
ret = "parent().";
else if(cobj == ppobj)
ret = "parent().children(\""+UdmUtil::ExtractName(pobj)+"\").";
else
{
if(Uml::IsDerivedFrom(cobj.type(), CyPhyML::DesignEntity::meta))
ret = "parent()."+getRelativePath(obj, CyPhyML::DesignEntity::Cast(cobj));
}
}
}
return ret;
}
std::string CyPhy2Desert::increaseCounter()
{
static int c2dCount = 0;
c2dCount++;
char buffer[65];
_itoa_s(c2dCount, buffer, 10);
return std::string(buffer);
}
std::string CyPhy2Desert::getDesertPCM(const std::string &method)
{
std::string pcm("PCM_NOP");
if(method == "Addition")
pcm = "PCM_ADD";
else if(method == "Multiplication")
pcm = "PCM_MUL";
else if(method == "ArithmeticMean")
pcm = "PCM_AMED";
else if(method == "GeometricMean")
pcm = "PCM_GMED";
else if(method == "Maximum")
pcm = "PCM_MAX";
else if(method == "Minimum")
pcm = "PCM_MIN";
else if(method == "None")
pcm = "PCM_NONE";
else //custom
pcm = "PCM_CUST";
return pcm;
}
bool CyPhy2Desert::isAlternativeContainer(Udm::Object &obj)
{
if(Uml::IsDerivedFrom(obj.type(), CyPhyML::DesignContainer::meta))
{
CyPhyML::DesignContainer dc = CyPhyML::DesignContainer::Cast(obj);
if((std::string)dc.ContainerType()!="Compound")
return true;
else
return false;
}
else
return false;
}
DesertIface::VariableProperty CyPhy2Desert::getVariableProperty(Udm::Object &cyphy_obj, CyPhyML::DesignEntity &obj_parent)
{
DesertIface::VariableProperty dvp;
map<Udm::Object, map<CyPhyML::DesignEntity, DesertIface::VariableProperty> >::iterator vpMap_pos = vpMap.find(cyphy_obj);
if(vpMap_pos!=vpMap.end())
{
const map<CyPhyML::DesignEntity, DesertIface::VariableProperty>& tmpMap = (*vpMap_pos).second;
map<CyPhyML::DesignEntity, DesertIface::VariableProperty>::const_iterator tmpMap_pos = tmpMap.find(obj_parent);
if (tmpMap_pos!=tmpMap.end())
dvp = (*tmpMap_pos).second;
}
return dvp;
}
void CyPhy2Desert::updatevpMap(const DesertIface::VariableProperty &dvp, const Udm::Object &cyphy_obj, const CyPhyML::DesignEntity &obj_parent)
{
auto vpMap_pos = vpMap.insert(std::make_pair(cyphy_obj, map<CyPhyML::DesignEntity, DesertIface::VariableProperty>()));
vpMap_pos.first->second[obj_parent] = dvp;
}
void CyPhy2Desert::checkSourceValueFlows(set<CyPhyML::ValueFlow> &vfs, const CyPhyML::DesignContainer &dc)
{
//check whether the incoming valueflow is outside of the root designContainer,
//some design explorer may start in lower level designContainer
set<CyPhyML::ValueFlow> tmpvfs;
Udm::Object rootDC_parent = rootDC.parent();
Udm::Object dc_parent = dc.parent();
for(set<CyPhyML::ValueFlow>::iterator i=vfs.begin();i!=vfs.end();++i)
{
CyPhyML::ValueFlow vf = *i;
Udm::Object vf_parent = vf.GetParent();
if(vf_parent==rootDC_parent) continue;
if(vf_parent==dc || vf_parent==dc_parent)
tmpvfs.insert(vf);
}
vfs.clear();
vfs.insert(tmpvfs.begin(), tmpvfs.end());
}
void CyPhy2Desert::processAlternativeParameters(CyPhyML::DesignContainer &altDC)
{
//collect all parameters
map<std::string, set<std::string> > parameterMap;
std::set<std::string> propertyNames;
auto addPropertyNames = [&propertyNames](const std::set<CyPhyML::Property>& props) {
std::for_each(props.begin(), props.end(), [&](const CyPhyML::Property prop) {
propertyNames.insert(prop.name());
});
};
set<CyPhyML::DesignEntity> des = altDC.DesignEntity_kind_children();
for(set<CyPhyML::DesignEntity>::iterator it=des.begin();it!=des.end();++it)
{
CyPhyML::DesignEntity de = *it;
if(Uml::IsDerivedFrom(de.type(), CyPhyML::DesignElement::meta))
{
CyPhyML::DesignElement celem = CyPhyML::DesignElement::Cast(de);
set<CyPhyML::Parameter> params = celem.Parameter_kind_children();
for(set<CyPhyML::Parameter>::iterator pit=params.begin();pit!=params.end();++pit)
insertParameterMap(*pit, parameterMap);
addPropertyNames(celem.Property_children());
}
else if(Uml::IsDerivedFrom(de.type(), CyPhyML::ComponentRef::meta))
{
CyPhyML::ComponentRef comref = CyPhyML::ComponentRef::Cast(de);
CyPhyML::DesignElement celem = comref.ref();
if(celem!=Udm::null)
{
set<CyPhyML::Parameter> params = celem.Parameter_kind_children();
for(set<CyPhyML::Parameter>::iterator pit=params.begin();pit!=params.end();++pit)
insertParameterMap(*pit, parameterMap);
addPropertyNames(celem.Property_children());
}
else
nullComponentRefs.insert(comref);
}
else if(Uml::IsDerivedFrom(de.type(), CyPhyML::DesignContainer::meta))
{
CyPhyML::DesignContainer cdc = CyPhyML::DesignContainer::Cast(de);
set<CyPhyML::Parameter> params = cdc.Parameter_kind_children();
for(set<CyPhyML::Parameter>::iterator pit=params.begin();pit!=params.end();++pit)
insertParameterMap(*pit, parameterMap);
addPropertyNames(cdc.Property_children());
}
}
DesertIface::Element alt_delem = com2elemMap[altDC];
ASSERT(alt_delem!=Udm::null);
//generate the parameter constraint for the alternative container
for(map<std::string, set<std::string> >::iterator pos=parameterMap.begin();pos!=parameterMap.end();++pos)
{
if (propertyNames.find(pos->first) != propertyNames.end()) {
// Propertys are unconstrained
continue;
}
std::string constraint_expr;
set<std::string> ranges = (*pos).second;
for(set<std::string>::iterator rit=ranges.begin();rit!=ranges.end();++rit)
{
if (constraint_expr.length() > 0) {
constraint_expr += "\nor\n";
}
std::string parameterConstraint = generateParameterConstraint(*rit, pos->first, CyPhyML::Parameter::Cast(Udm::null));
if (parameterConstraint.length() == 0) {
// unconstrained
constraint_expr = "";
break;
}
constraint_expr = constraint_expr + parameterConstraint;
}
if (constraint_expr.length() == 0) {
continue;
}
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
if(!getDomainWithMember((*pos).first, domain, 0, member))
throw udm_exception("Property/Parameter: is not NaturalDomain. Please check the ComputationType.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(alt_delem);
vp.parametric() = false;
vp.name() = vp.CUSTName() = (*pos).first;
vp.id() = vp.externalID() = altDC.ID()+5000;
vp.PCM_STR() = "PCM_ADD";
vp.Max() = 100000;
vp.domain() = domain;
bool validate = true;
for(set<CyPhyML::DesignEntity>::iterator it=des.begin(); it!=des.end(); ++it)
{
CyPhyML::DesignEntity de = *it;
if(!validateParameter(de, (*pos).first))
validate = false;
}
if (!validate) {
if (constraint_expr.length() > 0) {
constraint_expr += "\nor\n";
}
constraint_expr = constraint_expr + "(" + pos->first + "() = -1)";
}
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(constraintSet);
std::string pcon_name = pos->first + "_" + increaseCounter() + "_constraint";
dsConstraint.name() = pcon_name;
dsConstraint.expression() = "constraint " + pcon_name + "() {\n" + constraint_expr + "\n}";
dsConstraint.context() = alt_delem;
}
}
void CyPhy2Desert::insertParameterMap(const CyPhyML::Parameter ¶m, map<std::string, set<std::string> > ¶mMap)
{
std::string pname = param.name();
std::string prange = param.Range();
set<std::string> ranges;
map<std::string, set<std::string> >::iterator pos = paramMap.find(pname);
if(pos!=paramMap.end())
{
ranges = (*pos).second;
if(ranges.find(prange)==ranges.end())
ranges.insert(prange);
}
else
ranges.insert(prange);
paramMap[pname] = ranges;
}
void CyPhy2Desert::preprocessParameters(CyPhyML::DesignContainer &dc)
{
set<CyPhyML::DesignContainer> dcs = dc.DesignContainer_kind_children();
for (auto it = dcs.begin(); it != dcs.end(); ++it)
{
CyPhyML::DesignContainer dc_child = *it;
if ((std::string)(dc_child.ContainerType()) == "Compound")
continue;
set<CyPhyML::Parameter> parameters = dc_child.Parameter_kind_children();
preprocessParameters(parameters);
}
set<CyPhyML::Property> properties = dc.Property_children();
set<std::string> propertyNames;
for (auto it = properties.begin(); it != properties.end(); ++it)
{
if (propertyNames.insert(it->name()).second != true)
{
std::string hyperlink = "<a href=\"mga:" + UdmGme::UdmId2GmeId(it->uniqueId()) + "\">" + static_cast<std::string>(it->name()) + "</a>";
errorMsg = std::string("Duplicate Property name \"") + hyperlink + "\"";
throw udm_exception(std::string("Duplicate Property name \"") + static_cast<std::string>(it->name()) + "\"");
}
}
}
void CyPhy2Desert::preprocessParameters(set<CyPhyML::Parameter> ¶meters)
{
for(set<CyPhyML::Parameter>::iterator i=parameters.begin();i!=parameters.end();++i)
{
CyPhyML::Parameter currParameter = *i;
set<CyPhyML::ValueFlow> srcvfs = currParameter.srcValueFlow();
set<CyPhyML::ValueFlow> dstvfs = currParameter.dstValueFlow();
if(srcvfs.empty() && dstvfs.empty())
continue;
std::string pname = currParameter.name();
parameterNameMap[currParameter] = pname;
int pid = currParameter.uniqueId();
char buffer[65];
_itoa_s(pid, buffer, 10);
currParameter.name() = pname+(std::string)buffer;
}
}
void CyPhy2Desert::postprocessParameters()
{
for(map<CyPhyML::Parameter, std::string>::iterator it=parameterNameMap.begin();it!=parameterNameMap.end();++it)
{
(*it).first.name() = (*it).second;
}
}
bool CyPhy2Desert::validateParameter(CyPhyML::DesignEntity &de, const std::string &pname)
{
DesertIface::Element delem = com2elemMap[de];
ASSERT(de!=Udm::null);
set<DesertIface::VariableProperty> vps = delem.VariableProperty_kind_children();
for(set<DesertIface::VariableProperty>::iterator it=vps.begin();it!=vps.end();++it)
{
std::string vpname = (*it).name();
if(vpname == pname)
return false;
}
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
if(!getDomainWithMember(pname, domain, -1, member))
throw udm_exception("Property/Parameter: is not NaturalDomain. Please check the ComputationType.");
DesertIface::VariableProperty vp = DesertIface::VariableProperty::Create(delem);
vp.parametric() = false;
vp.name() = vp.CUSTName() = pname;
vp.id() = vp.externalID() = de.ID()+5000;
vp.PCM_STR() = "PCM_NONE";
vp.Max() = 100000;
vp.domain() =domain;
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(delem);
av.id() = av.externalID() = 2000;
av.properties_end() = vp;
av.values_end() = member;
return true;
}
std::string CyPhy2Desert::generateVisualConstraint(const CyPhyML::DesignContainer &cyphy_container, const CyPhyML::VisualConstraint &vcon)
{
std::string expr;
set<CyPhyML::ImpliesEnd> implyends = vcon.ImpliesEnd_kind_children();
map<CyPhyML::ImpliesEnd, std::string> visual2string;
set<CyPhyML::ImpliesEnd> singleEnds;
for(set<CyPhyML::ImpliesEnd>::iterator ei=implyends.begin();ei!=implyends.end();++ei)
{
CyPhyML::ImpliesEnd iend = *ei;
std::string context = generateConstraint(*ei, cyphy_container);
if(context.empty()) continue;
visual2string[iend] = context;
set<CyPhyML::Implies> ims_src = iend.dstImplies();
set<CyPhyML::Implies> ims_dst = iend.srcImplies();
if(ims_src.empty() && ims_dst.empty())
singleEnds.insert(iend);
}
set<CyPhyML::Implies> implies = vcon.Implies_kind_children();
bool mul = implies.size()>1 ? true : false;
set<CyPhyML::Implies>::iterator imply_it=implies.begin();
while(imply_it!=implies.end())
{
CyPhyML::ImpliesEnd src = CyPhyML::ImpliesEnd::Cast((*imply_it).srcImplies_end());
CyPhyML::ImpliesEnd dst = CyPhyML::ImpliesEnd::Cast((*imply_it).dstImplies_end());
expr += "(";
expr = expr + "(" + visual2string[src] + ")\nimplies\n" +"(" + visual2string[dst] + "))";
imply_it++;
if(mul && imply_it!=implies.end())
expr += "\n and \n";
}
if(!singleEnds.empty() && !implies.empty())
expr += "\n and \n";
set<CyPhyML::ImpliesEnd>::iterator implyend_it = singleEnds.begin();
while(implyend_it!=singleEnds.end())
{
expr = expr + "(" + visual2string[*implyend_it] + ")";
implyend_it++;
if(implyend_it!=singleEnds.end())
expr += "\n and \n";
}
return expr;
}
//check whether CusttomFormula/SimpleFormula is the source of SimpleFormula,
//if it is, then create DesertIface::VariableProperty for transferring the value in desert
void CyPhy2Desert::pre_processValueFormulas(const set<CyPhyML::ValueFormula> &formulas, const CyPhyML::DesignEntity &celem, DesertIface::Element &delem)
{
for(auto it_f=formulas.begin();it_f!=formulas.end();++it_f)
{
CyPhyML::ValueFormula formula = *it_f;
set<CyPhyML::ValueFlow> dst_vfs = formula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
{
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::CustomFormula::meta))
throw udm_exception("CustomFormula/SimpleFormula cannot be conneted to CustomFormula.");
//create parametric VariableProperty
DesertIface::VariableProperty dvp = DesertIface::VariableProperty::Create(delem);
dvp.id() = dvp.externalID() = formula.uniqueId()+5000;
dvp.name() = dvp.CUSTName() = UdmUtil::ExtractName(formula)+"_"+increaseCounter();
dvp.parametric() = true;
updatevpMap(dvp, formula, celem);
}
}
}
}
void CyPhy2Desert::processSimpleFormula(const CyPhyML::SimpleFormula &sformula, DesertIface::Element &delem)
{
//create Desert SimpleFormula
DesertIface::SimpleFormula dsf = DesertIface::SimpleFormula::Create(CyPhy2Desert::formulaSet);
dsf.ComputationType() = CyPhy2Desert::getDesertPCM((std::string)sformula.Method());
dsf.context() = delem;
dsf.name() = "SimpleFormula";
dsf.id() = dsf.externalID() = sformula.uniqueId();
set<CyPhyML::ValueFlow> src_vfs = sformula.srcValueFlow();
for(auto it_src=src_vfs.begin();it_src!=src_vfs.end();++it_src)
{
CyPhyML::ValueFlowTarget src_end = (*it_src).srcValueFlow_end();
Udm::Object src_end_parent = (*it_src).srcValueFlow_refport_parent();
if(src_end_parent==Udm::null)
src_end_parent = src_end.GetParent();
if(!Uml::IsDerivedFrom(src_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
CyPhyML::DesignEntity src_end_entity = CyPhyML::DesignEntity::Cast(src_end_parent);
DesertIface::VariableProperty dvp = getVariableProperty(src_end, src_end_entity);
if(dvp==Udm::null)
{
DesertIface::Element delem_parent;
map<CyPhyML::DesignEntity, DesertIface::Element>::iterator pos = com2elemMap.find(src_end_entity);
if(pos!=com2elemMap.end())
delem_parent = (*pos).second;
else
continue;
dvp = DesertIface::VariableProperty::Create(delem_parent);
updatevpMap(dvp, src_end, src_end_entity);
dvp.name() = dvp.CUSTName() = src_end.name();;
dvp.id() = dvp.externalID() = src_end_entity.ID()+5000;
}
//ASSERT(dvp!=Udm::null);// || Uml::IsDerivedFrom(src_end.type(), CyPhyML::ValueFormula::meta));
if(dvp!=Udm::null)
dsf.srcProperty() += dvp;
}
set<CyPhyML::ValueFlow> dst_vfs = sformula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
Udm::Object dst_end_parent = (*it_dst).dstValueFlow_refport_parent();
if(dst_end_parent==Udm::null)
dst_end_parent = dst_end.GetParent();
if(!Uml::IsDerivedFrom(dst_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
DesertIface::VariableProperty dvp;
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
dvp = getVariableProperty((CyPhyML::SimpleFormula)sformula, CyPhyML::DesignEntity::Cast(dst_end_parent));
else
dvp = getVariableProperty(dst_end, CyPhyML::DesignEntity::Cast(dst_end_parent));
ASSERT(dvp!=Udm::null);// || Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta));
if(dvp!=Udm::null)
{
dsf.property_end() += dvp;
dvp.parametric() = true;
}
}
}
void CyPhy2Desert::processCustomFormula(const CyPhyML::CustomFormula &cformula, DesertIface::Element &delem, bool isAlt)
{
string expression = cformula.Expression();
if(expression.empty()) return;
if(!DFUtil::IsValidExpression(expression))
CyPhy2Desert::invalidCustomFormulas.insert(cformula);
map<string, string> VariablePathMap;
set<CyPhyML::ValueFlow> inputVFs = cformula.srcValueFlow();
if (inputVFs.empty())
return;
for (set<CyPhyML::ValueFlow>::const_iterator ci = inputVFs.begin(); ci != inputVFs.end(); ci++)
{
CyPhyML::ValueFlowTarget src_vfend = ci->srcValueFlow_end();
Udm::Object src_parent = ci->srcValueFlow_refport_parent();
if(src_parent==Udm::null)
src_parent = src_vfend.parent();
std::string src_vfend_name = src_vfend.name();
std::string FormulaVariableName = ci->FormulaVariableName();
DesertIface::VariableProperty dvp = getVariableProperty(src_vfend, CyPhyML::DesignEntity::Cast(src_parent));
std::string dvp_name = (std::string)dvp.name();
if (isAlt == false && src_parent != ci->parent()) {
std::string src_parent_name = MgaObject::Cast(src_parent).name();
dvp_name = "children(\"" + src_parent_name + "\")." + dvp_name;
}
VariablePathMap[(FormulaVariableName == "" ? src_vfend_name : FormulaVariableName)] = dvp_name + "()";;
}
std::string expr = DFUtil::ConvertExpression(expression, VariablePathMap);
if(expr.empty()) return;
set<CyPhyML::ValueFlow> dst_vfs = cformula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
Udm::Object dst_end_parent = (*it_dst).dstValueFlow_refport_parent();
if(dst_end_parent==Udm::null)
dst_end_parent = dst_end.GetParent();
if(!Uml::IsDerivedFrom(dst_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
DesertIface::VariableProperty dvp;
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
dvp = getVariableProperty((CyPhyML::CustomFormula)cformula, CyPhyML::DesignEntity::Cast(dst_end_parent));
else
dvp = getVariableProperty(dst_end, CyPhyML::DesignEntity::Cast(dst_end_parent));
ASSERT(dvp!=Udm::null);
if(dvp!=Udm::null)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(CyPhy2Desert::formulaSet);
std::string fname = (std::string)dvp.name();
dcf.name() = fname;
dcf.expression() = "constraint formula_"+CyPhy2Desert::increaseCounter()+"_"+fname+" () {"+expr+"}";
dcf.property_end() += dvp;
dcf.context() = delem;
dvp.parametric() = true;
}
}
}
void CyPhy2Desert::flatternComponent(const CyPhyML::DesignEntity &celem, DesertIface::Element &delem, bool isAlt)
{
if(Uml::IsDerivedFrom(celem.type(), CyPhyML::DesignContainer::meta))
return;
CyPhyML::DesignElement cyphy_de;
CyPhyML::ComponentRef comref;
if(Uml::IsDerivedFrom(celem.type(), CyPhyML::ComponentRef::meta))
{
comref = CyPhyML::ComponentRef::Cast(celem);
cyphy_de = comref.ref();
if(cyphy_de==Udm::null)
{
nullComponentRefs.insert(comref);
return;
}
}
else
cyphy_de = CyPhyML::DesignElement::Cast(celem);
Com2DesertElement comflattern(cyphy_de, comref, delem, true, isAlt);
comflattern.flatternCA();
//update the vpMap
map<Udm::Object, DesertIface::VariableProperty>& topVpMap = comflattern.getTopVpMap();
for(map<Udm::Object, DesertIface::VariableProperty>::iterator pos=topVpMap.begin(); pos!=topVpMap.end();++pos)
{
Udm::Object pobj = (*pos).first;
DesertIface::VariableProperty dvp = (*pos).second;
map<CyPhyML::DesignEntity, DesertIface::VariableProperty> tmpMap;
vpMap.insert(make_pair(pobj, std::move(tmpMap))).first->second[celem] = dvp;
}
//update NatureDomain/CustomDomain
map<DesertIface::VariableProperty, double>& vp2ValMap = comflattern.getVp2ValMap();
for(map<DesertIface::VariableProperty, double>::iterator pos_d=vp2ValMap.begin();pos_d!=vp2ValMap.end();++pos_d)
{
DesertIface::VariableProperty dvp = (*pos_d).first;
double val = (*pos_d).second;
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
getDomainWithMember((std::string)dvp.name(), domain, val, member);
dvp.domain() = domain;
DesertIface::Element vp_elem = dvp.owner();
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(vp_elem);
av.id() = av.externalID() = 2000;
av.properties_end() = dvp;
av.values_end() = member;
}
map<DesertIface::VariableProperty, set<double> >& vp2ValsMap = comflattern.getVp2ValsMap();
for(map<DesertIface::VariableProperty, set<double> >::iterator pos_ds=vp2ValsMap.begin();pos_ds!=vp2ValsMap.end();++pos_ds)
{
DesertIface::VariableProperty dvp = (*pos_ds).first;
std::string dvp_name = dvp.name();
set<double>& vals = (*pos_ds).second;
for(set<double>::iterator d_it=vals.begin();d_it!=vals.end();++d_it)
{
double val = *d_it;
DesertIface::NaturalDomain domain;
DesertIface::NaturalMember member;
getDomainWithMember(dvp_name, domain, val, member);
dvp.domain() = domain;
DesertIface::Element vp_elem = dvp.owner();
DesertIface::AssignedValues av = DesertIface::AssignedValues::Create(vp_elem);
av.id() = av.externalID() = 2000;
av.properties_end() = dvp;
av.values_end() = member;
}
}
}
bool CyPhy2Desert::checkDesignElementLoop(const CyPhyML::DesignEntity &entity, set<int> ids, std::string &path)
{
int id = entity.uniqueId();
std::string hyperlink = "<A HREF=\"mga:"+ UdmGme::UdmId2GmeId(id) + "\">" + (std::string)entity.name() + "</A>";
set<int>::iterator pos = ids.find(id);
if(pos!=ids.end())
{
path = hyperlink;
return false;
}
ids.insert(id);
set<CyPhyML::ComponentRef> comrefs;
set<std::string> componentRefNames;
set<CyPhyML::DesignContainer> dcs;
set<CyPhyML::ComponentAssembly> cas;
set<std::string> containerNames;
if(Uml::IsDerivedFrom(entity.type(), CyPhyML::DesignContainer::meta))
{
CyPhyML::DesignContainer dc = CyPhyML::DesignContainer::Cast(entity);
comrefs = dc.ComponentRef_kind_children();
dcs = dc.DesignContainer_kind_children();
cas = dc.ComponentAssembly_kind_children();
}
else if(Uml::IsDerivedFrom(entity.type(), CyPhyML::ComponentAssembly::meta))
{
CyPhyML::ComponentAssembly ca = CyPhyML::ComponentAssembly::Cast(entity);
comrefs = ca.ComponentRef_kind_children();
cas = ca.ComponentAssembly_kind_children();
}
else if(Uml::IsDerivedFrom(entity.type(), CyPhyML::ComponentRef::meta))
{
CyPhyML::ComponentRef comref = CyPhyML::ComponentRef::Cast(entity);
comrefs.insert(comref);
}
for(auto ref_it=comrefs.begin();ref_it!=comrefs.end();++ref_it)
{
const CyPhyML::ComponentRef& this_ref = *ref_it;
CyPhyML::DesignElement de = this_ref.ref();
if (!de)
{
throw udm_exception("Illegal null reference " + this_ref.getPath("/"));
}
if(!checkDesignElementLoop(de, ids,path))
{
path = hyperlink + "-->" + path;
return false;
}
if (componentRefNames.insert(this_ref.name()).second == false) {
throw udm_exception(std::string("Illegal duplicate name ") + static_cast<const std::string>(this_ref.name()) + " in " + entity.getPath("/"));
}
}
for(auto dc_it=dcs.begin();dc_it!=dcs.end();++dc_it)
{
const CyPhyML::DesignContainer& this_dc = *dc_it;
if(!checkDesignElementLoop(this_dc, ids,path))
{
path = hyperlink + "-->" + path;
return false;
}
if (containerNames.insert(this_dc.name()).second == false) {
throw udm_exception(std::string("Illegal duplicate name ") + static_cast<const std::string>(this_dc.name()) + " in " + entity.getPath("/"));
}
}
for(auto ca_it=cas.begin();ca_it!=cas.end();++ca_it)
{
const CyPhyML::ComponentAssembly& this_ca = *ca_it;
if(!checkDesignElementLoop(this_ca, ids,path))
{
path = hyperlink + "-->" + path;
return false;
}
if (containerNames.insert(this_ca.name()).second == false) {
throw udm_exception(std::string("Illegal duplicate name ") + static_cast<const std::string>(this_ca.name()) + " in " + entity.getPath("/"));
}
}
return true;
}
int Com2DesertElement::_cnt = 0;
map<DesertIface::VariableProperty, double> Com2DesertElement::_vp2ValMap;
map<DesertIface::VariableProperty, set<double> > Com2DesertElement::_vp2ValsMap;
set<std::string> Com2DesertElement::_vpNameSet;
Com2DesertElement::Com2DesertElement(const CyPhyML::DesignElement &cyphy_de, const CyPhyML::ComponentRef &comref,
DesertIface::Element &delem, bool isroot, bool isAlt)
:_com(cyphy_de), _comref(comref), _delem(delem), _isroot(isroot), _isAlt(isAlt)
{
_vfs = _com.ValueFlow_kind_children();
if(_isroot)
init();
}
void Com2DesertElement::flatternCA()
{
set<CyPhyML::Property> properties = _com.Property_kind_children();
for(auto it_prop=properties.begin(); it_prop!=properties.end(); ++it_prop)
{
processProperty(*it_prop);
}
set<CyPhyML::Parameter> parameters = _com.Parameter_kind_children();
for(auto it_para=parameters.begin(); it_para!=parameters.end();++it_para)
{
processParameter(*it_para);
}
set<CyPhyML::Constant> constants = _com.Constant_kind_children();
for(auto it_con=constants.begin(); it_con!=constants.end(); ++it_con)
{
processConstant(*it_con);
}
if(Uml::IsDerivedFrom(_com.type(), CyPhyML::ComponentAssembly::meta))
{
CyPhyML::ComponentAssembly ca = CyPhyML::ComponentAssembly::Cast(_com);
set<CyPhyML::Component> coms = ca.Component_kind_children();
for(auto it_com=coms.begin(); it_com!=coms.end(); ++it_com)
{
CyPhyML::ComponentRef cref;
Com2DesertElement com2d(*it_com, cref, _delem, false, _isAlt);
com2d.flatternCA();
updateInnerVpMap(*it_com, com2d.getTopVpMap());
}
set<CyPhyML::ComponentRef> comrefs = ca.ComponentRef_kind_children();
for(auto it_comref=comrefs.begin(); it_comref!=comrefs.end(); ++it_comref)
{
CyPhyML::ComponentRef cref = *it_comref;
Com2DesertElement comref2d(cref.ref(), cref, _delem, false, _isAlt);
comref2d.flatternCA();
updateInnerVpMap(cref, comref2d.getTopVpMap());
}
set<CyPhyML::ComponentAssembly> cas = ca.ComponentAssembly_kind_children();
for(auto it_ca=cas.begin(); it_ca!=cas.end(); ++it_ca)
{
CyPhyML::ComponentRef cref;
Com2DesertElement ca2d(*it_ca, cref, _delem, false, !_isAlt);
ca2d.flatternCA();
updateInnerVpMap(*it_ca, ca2d.getTopVpMap());
}
}
//pre-process SimpleFormula/CustomFormula to see where it is the src for another SimpleFormula,
//if it is, create DesertIface::VariableProperty
set<CyPhyML::CustomFormula> cformulas = _com.CustomFormula_kind_children();
for(auto it_cf=cformulas.begin();it_cf!=cformulas.end();++it_cf)
{
processFormula(*it_cf);
}
set<CyPhyML::SimpleFormula> sformulas = _com.SimpleFormula_kind_children();
for(auto it_sf=sformulas.begin();it_sf!=sformulas.end();++it_sf)
{
processFormula(*it_sf);
}
//processSimpleFormulas and other direct ValueFlows
for(auto it_cf=cformulas.begin();it_cf!=cformulas.end();++it_cf)
{
processCustomFormula(*it_cf);
}
for(auto it_sf=sformulas.begin();it_sf!=sformulas.end();++it_sf)
{
processSimpleFormula(*it_sf);
}
for(auto it_vf=_vfs.begin(); it_vf!=_vfs.end(); ++it_vf)
{
processDirectValueFlow(*it_vf);
}
if(!_isroot) return;
//process Connectors
set<CyPhyML::Connector> connectors = _com.Connector_kind_children();
set<std::string> uniqueConnectorNames;
for(auto it_si=connectors.begin();it_si!=connectors.end();++it_si)
{
CyPhyML::Connector connector= *it_si;
std::string si_name = connector.name();
std::string si_valid_name = checkInvalidName(si_name);
if(uniqueConnectorNames.find(si_valid_name)!=uniqueConnectorNames.end())
{
int cnt = uniqueConnectorNames.size();
char buffer[65];
_itoa_s(cnt, buffer, 10);
si_valid_name = si_valid_name+"_"+(std::string)buffer;
}
uniqueConnectorNames.insert(si_valid_name);
if(si_valid_name!=si_name)
{
connector.name() = si_valid_name;
CyPhy2Desert::originalNames[connector] = si_name;
}
std::string def = connector.Definition();
set<int> def_vals = CyPhy2Desert::getConnectorDefValue(def);
if(def_vals.size()==1)
{
int def_val = *(def_vals.begin());
DesertIface::VariableProperty dvp = createDesertVP(connector, def_val, false);
}
else if(def_vals.size()>1)
{
createDesertVP4WildCard(connector, def_vals);
}
}
}
map<Udm::Object, DesertIface::VariableProperty>& Com2DesertElement::getTopVpMap()
{
return _topVpMap;
}
map<DesertIface::VariableProperty, double>& Com2DesertElement::getVp2ValMap()
{
return _vp2ValMap;
}
map<DesertIface::VariableProperty, set<double> >& Com2DesertElement::getVp2ValsMap()
{
return _vp2ValsMap;
}
void Com2DesertElement::clearVp2ValMap()
{
_vp2ValMap.clear();
}
void Com2DesertElement::clearVp2ValsMap()
{
_vp2ValsMap.clear();
}
void Com2DesertElement::init()
{
_cnt = 0;
_vp2ValMap.clear();
_vpNameSet.clear();
}
DesertIface::VariableProperty Com2DesertElement::createDesertVP(const Udm::Object &cyphy_vp, double value, bool parametric)
{
std::string pname = UdmUtil::ExtractName(cyphy_vp);
set<std::string>::iterator it = _vpNameSet.find(pname);
if(it!=_vpNameSet.end())
{
char buffer[65];
_itoa_s(_cnt++, buffer, 10);
pname = pname + (std::string)buffer;
}
_vpNameSet.insert(pname);
int pid = cyphy_vp.uniqueId();
DesertIface::VariableProperty newdvp = DesertIface::VariableProperty::Create(_delem);
newdvp.id() = newdvp.externalID() = pid+5000;
newdvp.name() = newdvp.CUSTName() = pname;
newdvp.PCM_STR() = "PCM_NONE";
newdvp.Max() = value+100000;
newdvp.parametric() = parametric;
if(!parametric)
{
Com2DesertElement::_vp2ValMap[newdvp] = value;
}
_topVpMap[cyphy_vp] = newdvp;
return newdvp;
}
void Com2DesertElement::createDesertVP4WildCard(const Udm::Object &si, set<int> vals)
{
std::string pname = UdmUtil::ExtractName(si);
set<std::string>::iterator it = _vpNameSet.find(pname);
if(it!=_vpNameSet.end())
{
char buffer[65];
_itoa_s(_cnt++, buffer, 10);
pname = pname + (std::string)buffer;
}
_vpNameSet.insert(pname);
int pid = si.uniqueId();
DesertIface::VariableProperty newdvp = DesertIface::VariableProperty::Create(_delem);
newdvp.id() = newdvp.externalID() = pid+5000;
newdvp.name() = newdvp.CUSTName() = pname;
newdvp.PCM_STR() = "";
newdvp.parametric() = false;
_topVpMap[si] = newdvp;
set<double> tmp_vals;
for(set<int>::iterator it=vals.begin();it!=vals.end();++it)
tmp_vals.insert(*it);
Com2DesertElement::_vp2ValsMap[newdvp] = tmp_vals;
}
void Com2DesertElement::processProperty(const CyPhyML::Property &prop)
{
//set<CyPhyML::ValueFlow> src_vfs = prop.srcValueFlow();
//bool parametric = src_vfs.empty() ? false : true;
//not complete here, need more consideration, even if src_vfs is not empty,
//it may come from somewhere else due to the reference port case
CyPhyML::ValueFlowTarget src_end;
Udm::Object src_end_parent;
bool parametric = isVariableParametric(prop, src_end, src_end_parent);
set<CyPhyML::ValueFlow> dst_vfs = prop.dstValueFlow();
if(!_isroot && !parametric && dst_vfs.empty())
return; //stand alone property
if((std::string)prop.ComputationType()=="Cust")
return;
std::string val_str = prop.Value();
double value = atof(val_str.c_str());
DesertIface::VariableProperty dvp = createDesertVP(prop, value, parametric);
if(src_end==Udm::null) return;
if (Uml::IsDerivedFrom(src_end.type(), CyPhyML::Parameter::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Property::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Constant::meta)
)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(CyPhy2Desert::formulaSet);
std::string fname = dvp.name();
dcf.name() = fname;
dcf.expression() = "constraint formula_"+CyPhy2Desert::increaseCounter()+"_"+fname+" () {"+DFUtil::getRelativePath(src_end, src_end_parent, _comref!=Udm::null?_comref:_com)+std::string(src_end.name())+"() }";
dcf.property_end() += dvp;
dcf.context() = _delem;
}
}
void Com2DesertElement::processParameter(const CyPhyML::Parameter ¶m)
{
//set<CyPhyML::ValueFlow> src_vfs = param.srcValueFlow();
//bool parametric = src_vfs.empty() ? false : true;
CyPhyML::ValueFlowTarget src_end;
Udm::Object src_end_parent;
bool parametric = isVariableParametric(param, src_end, src_end_parent);
set<CyPhyML::ValueFlow> dst_vfs = param.dstValueFlow();
if(!_isroot && !parametric && dst_vfs.empty() && param.Disable())
return;
std::string val_str = param.Value();
double value = atof(val_str.c_str());
DesertIface::VariableProperty dvp = createDesertVP(param, value, parametric);
std::string newParamName = dvp.name();
if(_isroot && !param.Disable() && !_isAlt)
{
//generate constraints
std::string expr = CyPhy2Desert::generateParameterConstraint(param, newParamName);
if(!(expr=="()" || expr.empty()))
{
DesertIface::Constraint dsConstraint = DesertIface::Constraint::Create(CyPhy2Desert::constraintSet);
std::string pcon_name = newParamName +"_"+CyPhy2Desert::increaseCounter()+"_constraint";
dsConstraint.name() = pcon_name;
dsConstraint.expression() = "constraint "+ pcon_name+"() {\n" + expr+"\n}";
dsConstraint.context() = _delem;
}
}
if(src_end==Udm::null) return;
if (Uml::IsDerivedFrom(src_end.type(), CyPhyML::Parameter::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Property::meta)
|| Uml::IsDerivedFrom(src_end.type(), CyPhyML::Constant::meta)
)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(CyPhy2Desert::formulaSet);
std::string fname = dvp.name();
dcf.name() = fname;
dcf.expression() = "constraint formula_"+CyPhy2Desert::increaseCounter()+"_"+fname+" () {"+DFUtil::getRelativePath(src_end, src_end_parent, _comref!=Udm::null?_comref:_com)+std::string(src_end.name())+"() }";
dcf.property_end() += dvp;
dcf.context() = _delem;
}
}
void Com2DesertElement::processConstant(const CyPhyML::Constant &constant)
{
set<CyPhyML::ValueFlow> src_vfs = constant.srcValueFlow(); //shoud not have incoming valueflows
set<CyPhyML::ValueFlow> dst_vfs = constant.dstValueFlow();
if(!_isroot && src_vfs.empty() && dst_vfs.empty())
return;
double value = constant.ConstantValue();
DesertIface::VariableProperty dvp = createDesertVP(constant, value, false);
}
void Com2DesertElement::processFormula(const CyPhyML::ValueFormula &formula)
{
set<CyPhyML::ValueFlow> dst_vfs = formula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
{
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::CustomFormula::meta))
throw udm_exception("CustomFormula/SimpleFormula cannot be conneted to CustomFormula.");
DesertIface::VariableProperty dvp = createDesertVP(formula, 0, true);
return;
}
}
}
void Com2DesertElement::processSimpleFormula(const CyPhyML::SimpleFormula &sformula)
{
//create Desert SimpleFormula
DesertIface::SimpleFormula dsf = DesertIface::SimpleFormula::Create(CyPhy2Desert::formulaSet);
dsf.ComputationType() = CyPhy2Desert::getDesertPCM((std::string)sformula.Method());
dsf.context() = _delem;
dsf.name() = "SimpleFormula";
dsf.id() = dsf.externalID() = sformula.uniqueId();
set<CyPhyML::ValueFlow> src_vfs = sformula.srcValueFlow();
for(auto it_src=src_vfs.begin();it_src!=src_vfs.end();++it_src)
{
set<CyPhyML::ValueFlow>::iterator it_vf = _vfs.find(*it_src);
if(it_vf!=_vfs.end())
_vfs.erase(it_vf);
CyPhyML::ValueFlowTarget src_end = (*it_src).srcValueFlow_end();
Udm::Object src_end_parent = (*it_src).srcValueFlow_refport_parent();
if(src_end_parent==Udm::null)
src_end_parent = src_end.GetParent();
if(!Uml::IsDerivedFrom(src_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
DesertIface::VariableProperty dvp = getVariableProperty(src_end, CyPhyML::DesignEntity::Cast(src_end_parent));
ASSERT(dvp!=Udm::null);// || Uml::IsDerivedFrom(src_end.type(), CyPhyML::ValueFormula::meta));
if(dvp!=Udm::null)
dsf.srcProperty() += dvp;
}
set<CyPhyML::ValueFlow> dst_vfs = sformula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
set<CyPhyML::ValueFlow>::iterator it_vf = _vfs.find(*it_dst);
if(it_vf!=_vfs.end())
_vfs.erase(it_vf);
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
Udm::Object dst_end_parent = (*it_dst).dstValueFlow_refport_parent();
if(dst_end_parent==Udm::null)
dst_end_parent = dst_end.GetParent();
if(!Uml::IsDerivedFrom(dst_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
DesertIface::VariableProperty dvp;
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
dvp = getVariableProperty((CyPhyML::SimpleFormula)sformula, CyPhyML::DesignEntity::Cast(dst_end_parent));
else
dvp = getVariableProperty(dst_end, CyPhyML::DesignEntity::Cast(dst_end_parent));
ASSERT(dvp!=Udm::null);// || Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta));
if(dvp!=Udm::null)
{
dsf.property_end() += dvp;
dvp.parametric() = true;
}
}
}
void Com2DesertElement::processCustomFormula(const CyPhyML::CustomFormula &cformula)
{
string expression = cformula.Expression();
if(!DFUtil::IsValidExpression(expression))
CyPhy2Desert::invalidCustomFormulas.insert(cformula);
map<string, string> VariablePathMap;
set<CyPhyML::ValueFlow> inputVFs = cformula.srcValueFlow();
if (inputVFs.empty())
return;
for (set<CyPhyML::ValueFlow>::const_iterator ci = inputVFs.begin(); ci != inputVFs.end(); ci++)
{
set<CyPhyML::ValueFlow>::iterator it_vf = _vfs.find(*ci);
if(it_vf!=_vfs.end())
_vfs.erase(it_vf);
CyPhyML::ValueFlowTarget src_vfend = ci->srcValueFlow_end();
Udm::Object src_parent = ci->srcValueFlow_refport_parent();
if(src_parent==Udm::null)
src_parent = src_vfend.parent();
std::string src_vfend_name = src_vfend.name();
std::string FormulaVariableName = ci->FormulaVariableName();
DesertIface::VariableProperty dvp = getVariableProperty(src_vfend, CyPhyML::DesignEntity::Cast(src_parent));
VariablePathMap[(FormulaVariableName == "" ? src_vfend_name : FormulaVariableName)] = (std::string)dvp.name()+"()";;
}
std::string expr = DFUtil::ConvertExpression(expression, VariablePathMap);
if(expr.empty()) return;
set<CyPhyML::ValueFlow> dst_vfs = cformula.dstValueFlow();
for(auto it_dst=dst_vfs.begin();it_dst!=dst_vfs.end();++it_dst)
{
set<CyPhyML::ValueFlow>::iterator it_vf = _vfs.find(*it_dst);
if(it_vf!=_vfs.end())
_vfs.erase(it_vf);
// if(expr.empty()) continue;
CyPhyML::ValueFlowTarget dst_end = (*it_dst).dstValueFlow_end();
Udm::Object dst_end_parent = (*it_dst).dstValueFlow_refport_parent();
if(dst_end_parent==Udm::null)
dst_end_parent = dst_end.GetParent();
if(!Uml::IsDerivedFrom(dst_end_parent.type(), CyPhyML::DesignEntity::meta))
continue;
DesertIface::VariableProperty dvp;
if(Uml::IsDerivedFrom(dst_end.type(), CyPhyML::ValueFormula::meta))
dvp = getVariableProperty((CyPhyML::CustomFormula)cformula, CyPhyML::DesignEntity::Cast(dst_end_parent));
else
dvp = getVariableProperty(dst_end, CyPhyML::DesignEntity::Cast(dst_end_parent));
ASSERT(dvp!=Udm::null);
if(dvp!=Udm::null)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(CyPhy2Desert::formulaSet);
std::string fname = (std::string)dvp.name();
dcf.name() = fname;
dcf.expression() = "constraint formula_"+CyPhy2Desert::increaseCounter()+"_"+fname+" () {"+expr+"}";
dcf.property_end() += dvp;
dcf.context() = _delem;
dvp.parametric() = true;
}
}
}
void Com2DesertElement::processDirectValueFlow(const CyPhyML::ValueFlow &vf)
{
CyPhyML::ValueFlowTarget dst_end = vf.dstValueFlow_end();
Udm::Object dst_end_parent = vf.dstValueFlow_refport_parent();
if(dst_end_parent==Udm::null)
dst_end_parent = dst_end.GetParent();
DesertIface::VariableProperty dst_dvp = getVariableProperty(dst_end, CyPhyML::DesignEntity::Cast(dst_end_parent));
ASSERT(dst_dvp!=Udm::null);
CyPhyML::ValueFlowTarget src_end = vf.srcValueFlow_end();
Udm::Object src_end_parent = vf.srcValueFlow_refport_parent();
if(src_end_parent==Udm::null)
src_end_parent = src_end.GetParent();
DesertIface::VariableProperty src_dvp = getVariableProperty(src_end, CyPhyML::DesignEntity::Cast(src_end_parent));
ASSERT(src_dvp!=Udm::null);
if(dst_dvp!=Udm::null && src_dvp!=Udm::null)
{
DesertIface::CustomFormula dcf = DesertIface::CustomFormula::Create(CyPhy2Desert::formulaSet);
std::string fname = (std::string)dst_dvp.name();
dcf.name() = fname;
dcf.expression() = "constraint formula_"+CyPhy2Desert::increaseCounter()+"_"+fname+" () {"+(std::string)src_dvp.name()+"()}";
dcf.property_end() += dst_dvp;
dcf.context() = _delem;
dst_dvp.parametric() = true;
}
}
void Com2DesertElement::updateInnerVpMap(const CyPhyML::DesignEntity &cyphy_elem, map<Udm::Object, DesertIface::VariableProperty> &topVpMap)
{
for(map<Udm::Object, DesertIface::VariableProperty>::iterator pos = topVpMap.begin(); pos != topVpMap.end(); ++pos)
{
const Udm::Object& pobj = (*pos).first;
if(Uml::IsDerivedFrom(pobj.type(), CyPhyML::ValueFormula::meta))
continue;
DesertIface::VariableProperty dvp = (*pos).second;
map<CyPhyML::DesignEntity, DesertIface::VariableProperty> tmpMap;
_innerVpMap.insert(make_pair(pobj, std::move(tmpMap))).first->second[cyphy_elem] = dvp;
}
}
DesertIface::VariableProperty Com2DesertElement::getVariableProperty(CyPhyML::ValueFlowTarget &cyphy_obj, CyPhyML::DesignEntity &obj_parent)
{
DesertIface::VariableProperty dvp;
VPMap::iterator vpMap_pos = _innerVpMap.find(cyphy_obj);
if(vpMap_pos!=_innerVpMap.end())
{
map<CyPhyML::DesignEntity, DesertIface::VariableProperty>& tmpMap = (*vpMap_pos).second;
map<CyPhyML::DesignEntity, DesertIface::VariableProperty>::iterator tmpMap_pos = tmpMap.find(obj_parent);
if(tmpMap_pos!=tmpMap.end())
dvp = (*tmpMap_pos).second;
}
else if(obj_parent == _com)
{
map<Udm::Object, DesertIface::VariableProperty>::iterator pos = _topVpMap.find(cyphy_obj);
if(pos!=_topVpMap.end())
dvp = (*pos).second;
}
return dvp;
}
bool Com2DesertElement::isVariableParametric(const CyPhyML::ValueFlowTarget &var, CyPhyML::ValueFlowTarget &src_end, Udm::Object &src_end_parent)
{
set<CyPhyML::ValueFlow> src_vfs = var.srcValueFlow();
if(src_vfs.empty()) return false;
set<CyPhyML::ValueFlow> real_vfs;
for(auto it=src_vfs.begin();it!=src_vfs.end();++it)
{
CyPhyML::ValueFlow src_vf = *it;
CyPhyML::ValueFlowTarget dst_end = src_vf.dstValueFlow_end();
CyPhyML::ValueFlow_dstValueFlow_RPContainer_Base dst_end_refParent = src_vf.dstValueFlow_refport_parent();
if(dst_end_refParent!=Udm::null && _comref!=Udm::null && dst_end_refParent.uniqueId()==_comref.uniqueId())
{
real_vfs.insert(src_vf);
}
else if(dst_end_refParent==Udm::null && _com.uniqueId() == dst_end.GetParent().uniqueId())// && _comref==Udm::null)
{
//same component
real_vfs.insert(src_vf);
}
}
if(real_vfs.empty()) return false;
if(real_vfs.size()>1)
throw udm_exception("Property/Parameter: "+(std::string)var.name()+" cannot have more than one source ValueFlow.");
CyPhyML::ValueFlow real_vf = *(real_vfs.begin());
Udm::Object topParent;
if(_comref!=Udm::null)
topParent = _comref.GetParent();
else
topParent = _com.GetParent();
if(_isroot && real_vf.GetParent()==topParent)
{
src_end = real_vf.srcValueFlow_end();
src_end_parent = real_vf.srcValueFlow_refport_parent();
}
return true;
}
//set<int> CyPhy2Desert::getStructuralInterfaceTypeValue(std::string &si_type)
//{
// set<int> ret;
// map<std::string, int>::iterator pos = structuralInterfaceTypeMap.find(si_type);
// if(pos!=structuralInterfaceTypeMap.end())
// {
// ret.insert((*pos).second);
// }
// else
// {
// map<std::string, set<int> >::iterator pos1 = sitWildCardMap.find(si_type);
// if(pos1!=sitWildCardMap.end())
// ret = (*pos1).second;
// }
// return ret;
//}
set<int> CyPhy2Desert::getConnectorDefValue(std::string &def)
{
set<int> ret;
map<std::string, int>::iterator pos = connectorDefMap.find(def);
if(pos!=connectorDefMap.end())
{
ret.insert((*pos).second);
}
else
{
map<std::string, set<int> >::iterator pos1 = connectorDefWildCardMap.find(def);
if(pos1!=connectorDefWildCardMap.end())
ret = (*pos1).second;
}
return ret;
}
#endif
|
danjpgriffin/totallylazy
|
test/com/googlecode/totallylazy/proxy/ProxyTest.java
|
package com.googlecode.totallylazy.proxy;
import com.googlecode.totallylazy.concurrent.NamedExecutors;
import com.googlecode.totallylazy.concurrent.NamedThreadFactory;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import static com.googlecode.totallylazy.Assert.assertThat;
import static com.googlecode.totallylazy.Assert.assertTrue;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.totallylazy.predicates.Predicates.is;
import static com.googlecode.totallylazy.predicates.Predicates.nullValue;
import static com.googlecode.totallylazy.proxy.Proxy.lazy;
import static com.googlecode.totallylazy.proxy.Proxy.proxy;
public class ProxyTest {
abstract class VarArgs {
public abstract int add(int a, int... b);
}
@Test
public void marksVarArgsMethodsCorrectly() throws Exception {
VarArgs instance = proxy(VarArgs.class, (proxy, method, args) -> 12);
Method method = instance.getClass().getMethod("add", int.class, int[].class);
assertThat(method.isVarArgs(), is(true));
}
abstract class NonPublic {
public abstract int add(int a, int b);
}
@Test
public void canCreateProxyForNonPublicClass() throws Exception {
NonPublic instance = proxy(NonPublic.class, (proxy, method, args) -> 12);
assertThat(instance.add(1, 2), is(12));
}
@Test
public void supportsProxyClassForRestrictedPackage() throws Exception {
proxy(Exception.class, (proxy, method, args) -> null );
}
@Test
public void canCreateALazyProxyWithReflectoMagic() throws Exception {
User user = lazy(() -> new User("dan", "bod"));
assertThat(user.firstName(), is("dan"));
}
@Test
public void canCreateALazyProxy() throws Exception {
AtomicInteger called = new AtomicInteger();
User user = lazy(User.class, () -> {
called.incrementAndGet();
return new User("dan", "bod");
});
assertThat(called.get(), is(0));
assertThat(user.firstName(), is("dan"));
assertThat(called.get(), is(1));
assertThat(user.lastName(), is("bod"));
assertThat(called.get(), is(1));
}
@Test(expected = UnsupportedOperationException.class)
public void canNotCreateProxyForFinalClass() throws Exception {
Proxy.proxy(Integer.class, null);
}
@Test
public void canCreateAnAsyncProxy() throws Exception {
ExecutorService executors = NamedExecutors.newCachedThreadPool(getClass());
CountDownLatch latch = new CountDownLatch(1);
Sync async = Proxy.async(Sync.class, () -> {
latch.await();
return () -> "done";
}, executors);
Interface proxy = async.get(); // Would normally block
latch.countDown();
assertThat(proxy.name(), is("done"));
executors.shutdown();
}
interface Sync{
Interface get() throws Exception;
}
interface Interface {
String name();
}
@Test
public void canCreateProxyForInterface() throws Exception {
Interface instance = proxy(Interface.class, (proxy, method, args) -> "Hello");
assertThat(instance.name(), is("Hello"));
}
public static abstract class CorrectMethod {
public abstract Method theRightMethod();
}
@Test
public void passesCorrectMethod() throws Throwable {
CorrectMethod instance = proxy(CorrectMethod.class, (proxy, method, args) -> method);
assertThat(instance.theRightMethod(), is(CorrectMethod.class.getMethod("theRightMethod")));
}
public static abstract class BooleanArguments {
public abstract boolean add(boolean a, boolean b);
}
@Test
public void supportsBoolean() throws Throwable {
BooleanArguments instance = proxy(BooleanArguments.class, (proxy, method, args) -> true);
assertThat(instance.add(false, false), is(true));
}
public static abstract class IntegerArguments {
public abstract int add(int a, int b);
}
@Test
public void supportsInteger() throws Throwable {
IntegerArguments instance = proxy(IntegerArguments.class, (proxy, method, args) -> 12);
assertThat(instance.add(1, 2), is(12));
}
public static abstract class LongArguments {
public abstract long add(long a, long b);
}
@Test
public void supportsLong() throws Throwable {
LongArguments instance = proxy(LongArguments.class, (proxy, method, args) -> 12L);
assertThat(instance.add(1L, 2L), is(12L));
}
public static abstract class FloatArguments {
public abstract float add(float a, float b);
}
@Test
public void supportsFloat() throws Throwable {
FloatArguments instance = proxy(FloatArguments.class, (proxy, method, args) -> 12F);
assertThat(instance.add(1F, 2F), is(12F));
}
public static abstract class DoubleArguments {
public abstract double add(double a, double b);
}
@Test
public void supportsDouble() throws Throwable {
DoubleArguments instance = proxy(DoubleArguments.class, (proxy, method, args) -> 12D);
assertThat(instance.add(1D, 2D), is(12D));
}
public static abstract class ByteArguments {
public abstract byte add(byte a, byte b);
}
@Test
public void supportsByte() throws Throwable {
ByteArguments instance = proxy(ByteArguments.class, (proxy, method, args) -> (byte)12);
assertThat(instance.add((byte)1, (byte)2), is((byte)12));
}
public static abstract class ShortArguments {
public abstract short add(short a, short b);
}
@Test
public void supportsShort() throws Throwable {
ShortArguments instance = proxy(ShortArguments.class, (proxy, method, args) -> (short)12);
assertThat(instance.add((short)1, (short)2), is((short)12));
}
public static abstract class CharArguments {
public abstract char add(char a, char b);
}
@Test
public void supportsChar() throws Throwable {
CharArguments instance = proxy(CharArguments.class, (proxy, method, args) -> (char)12);
assertThat(instance.add((char)1, (char)2), is((char)12));
}
public static abstract class ByteArrayArguments {
public abstract byte[] add(byte[] a, byte[] b);
}
@Test
public void supportsPrimativeArrays() throws Throwable {
ByteArrayArguments instance = proxy(ByteArrayArguments.class, (proxy, method, args) -> new byte[]{12});
assertTrue(Arrays.equals(instance.add(new byte[]{1}, new byte[]{2}), new byte[]{12}));
}
public static abstract class BigByteArguments {
public abstract Byte add(Byte a, Byte b);
}
@Test
public void supportsBoxedPrimatives() throws Throwable {
BigByteArguments instance = proxy(BigByteArguments.class, (proxy, method, args) -> (byte)12);
assertThat(instance.add((byte) 1, (byte) 2), is((byte) 12));
}
public static abstract class VoidArguments {
public abstract void add(Void a, Void b);
public abstract Void add(Void a);
}
@Test
public void supportsVoid() throws Throwable {
AtomicInteger count = new AtomicInteger();
VoidArguments instance = proxy(VoidArguments.class, (proxy, method, args) -> {
count.incrementAndGet();
return null;
});
instance.add(null, null);
assertThat(instance.add(null), is(nullValue()));
assertThat(count.intValue(), is(2));
}
}
|
lifei321/LoveBird
|
LoveBird/LoveBird/BaseViewController/AppBaseTabBarController.h
|
<gh_stars>0
//
// AppBaseTabBarController.h
// LoveBird
//
// Created by ShanCheli on 2017/7/7.
// Copyright © 2017年 shancheli. All rights reserved.
//
#import <UIKit/UIKit.h>
@class SubControllerAttribute;
@interface AppBaseTabBarController : UITabBarController
/**
* 控制器的公共导航控制器类,如果没有按照系统导航控制器创建
*/
@property (nonatomic, strong) Class commonNavControllerClass;
/**
* 控制器属性数组
*/
@property (nonatomic, strong) NSArray<SubControllerAttribute *> *subControllerAttributes;
@end
//----------------SubControllerAttribute类----------------
#pragma mark - SubControllerAttribute类
//属性类,存储控制器需要添加的控制器的属性
@interface SubControllerAttribute : NSObject
/**
* 导航控制器的类
*/
@property (nonatomic, strong) Class navigationClass;
/**
* 子控制器的类
*/
@property (nonatomic, strong) Class controllerClass;
/**
* TabbarItem的标题
*/
@property (nonatomic, strong) NSString *title;
/**
* TabbarItem的正常图片
*/
@property (nonatomic, strong) NSString *image;
/**
* TabbarItem的选中图片
*/
@property (nonatomic, strong) NSString *selectImage;
/**
* 类方法创建属性对象
*/
+ (instancetype)attributeWithClass:(Class)controllerClass TabBarItemTitle:(NSString *)title image:(NSString *)image selectImage:(NSString *)selectImage;
/**
* 类方法创建属性对象
*/
+ (instancetype)attributeWithClass:(Class)class NavigationClass:(Class)navigationClass TabBarItemTitle:(NSString *)title image:(NSString *)image selectImage:(NSString *)selectImage;
@end
|
Frozen/cockroach
|
pkg/sql/colflow/colrpc/inbox.go
|
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package colrpc
import (
"context"
"fmt"
"io"
"sync"
"github.com/apache/arrow/go/arrow/array"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/colserde"
"github.com/cockroachdb/cockroach/pkg/col/coltypes"
"github.com/cockroachdb/cockroach/pkg/sql/colexec"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/execerror"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/logtags"
)
// flowStreamServer is a utility interface used to mock out the RPC layer.
type flowStreamServer interface {
Send(*execinfrapb.ConsumerSignal) error
Recv() (*execinfrapb.ProducerMessage, error)
}
// Inbox is used to expose data from remote flows through an exec.Operator
// interface. FlowStream RPC handlers should call RunWithStream (which blocks
// until operation terminates, gracefully or unexpectedly) to pass the stream
// to the inbox. Next may be called before RunWithStream, it will just block
// until the stream is made available or its context is canceled. Note that
// ownership of the stream is passed from the RunWithStream goroutine to the
// Next goroutine. In exchange, the RunWithStream goroutine receives the first
// context passed into Next and listens for cancellation. Returning from
// RunWithStream (or more specifically, the RPC handler) will unblock Next by
// closing the stream.
type Inbox struct {
colexec.ZeroInputNode
typs []coltypes.T
zeroBatch coldata.Batch
converter *colserde.ArrowBatchConverter
serializer *colserde.RecordBatchSerializer
// streamID is used to overwrite a caller's streamID
// in the ctx argument of Next and DrainMeta.
streamID execinfrapb.StreamID
// streamCh is the channel over which the stream is passed from the stream
// handler to the reader goroutine.
streamCh chan flowStreamServer
// contextCh is the channel over which the reader goroutine passes the first
// context to the stream handler so that it can listen for context
// cancellation.
contextCh chan context.Context
// timeoutCh is the channel over which an error will be sent if the reader
// goroutine should exit while waiting for a stream.
timeoutCh chan error
// errCh is the channel that RunWithStream will block on, waiting until the
// Inbox does not need a stream any more. An error will only be sent on this
// channel in the event of a cancellation or a non-io.EOF error originating
// from a stream.Recv.
errCh chan error
// ctxInterceptorFn is a callback to expose the inbox's context
// right after init. To be used for unit testing.
ctxInterceptorFn func(context.Context)
// We need two mutexes because a single mutex is insufficient to handle
// concurrent calls to Next() and DrainMeta(). See comment in DrainMeta.
stateMu struct {
syncutil.Mutex
// initialized prevents double initialization. Should not be used by the
// RunWithStream goroutine.
initialized bool
// done prevents double closing. It should not be used by the RunWithStream
// goroutine.
done bool
// nextRunning indicates whether Next goroutine is running at the moment.
nextRunning bool
// nextExited is a condition variable on which DrainMeta might block in
// order to wait for Next goroutine to exit.
nextExited *sync.Cond
// nextShouldExit indicates to Next goroutine that it should exit. It must
// only be updated by DrainMeta goroutine.
nextShouldExit bool
// bufferedMeta buffers any metadata found in Next when reading from the
// stream and is returned by DrainMeta.
bufferedMeta []execinfrapb.ProducerMetadata
}
streamMu struct {
syncutil.Mutex
// stream is the RPC stream. It is set when RunWithStream is called but
// only the Next and DrainMeta goroutines may access it.
stream flowStreamServer
}
scratch struct {
data []*array.Data
b coldata.Batch
}
}
var _ colexec.StaticMemoryOperator = &Inbox{}
// NewInbox creates a new Inbox.
func NewInbox(typs []coltypes.T, streamID execinfrapb.StreamID) (*Inbox, error) {
c, err := colserde.NewArrowBatchConverter(typs)
if err != nil {
return nil, err
}
s, err := colserde.NewRecordBatchSerializer(typs)
if err != nil {
return nil, err
}
i := &Inbox{
typs: typs,
zeroBatch: coldata.NewMemBatchWithSize(typs, 0),
converter: c,
serializer: s,
streamID: streamID,
streamCh: make(chan flowStreamServer, 1),
contextCh: make(chan context.Context, 1),
timeoutCh: make(chan error, 1),
errCh: make(chan error, 1),
}
i.zeroBatch.SetLength(0)
i.scratch.data = make([]*array.Data, len(typs))
i.scratch.b = coldata.NewMemBatch(typs)
i.stateMu.bufferedMeta = make([]execinfrapb.ProducerMetadata, 0)
i.stateMu.nextExited = sync.NewCond(&i.stateMu)
return i, nil
}
// EstimateStaticMemoryUsage implements the StaticMemoryOperator interface.
func (i *Inbox) EstimateStaticMemoryUsage() int {
return colexec.EstimateBatchSizeBytes(i.typs, int(coldata.BatchSize()))
}
// maybeInitLocked calls Inbox.initLocked if the inbox is not initialized and
// returns an error if the initialization was not successful. Usually this is
// because the given context is canceled before the remote stream arrives.
// NOTE: i.stateMu *must* be held when calling this function.
func (i *Inbox) maybeInitLocked(ctx context.Context) error {
if !i.stateMu.initialized {
if err := i.initLocked(ctx); err != nil {
return err
}
i.stateMu.initialized = true
}
return nil
}
// initLocked initializes the Inbox for operation by blocking until
// RunWithStream sets the stream to read from. ctx ownership is retained until
// the stream arrives (to allow for unblocking the wait for a stream), at which
// point ownership is transferred to RunWithStream. This should only be called
// from the reader goroutine when it needs a stream.
// NOTE: i.stateMu *must* be held when calling this function because it is
// sufficient to protect access to i.streamMu.stream since the stream will only
// be accessed after the initialization.
func (i *Inbox) initLocked(ctx context.Context) error {
// Wait for the stream to be initialized. We're essentially waiting for the
// remote connection.
select {
case i.streamMu.stream = <-i.streamCh:
case err := <-i.timeoutCh:
i.errCh <- fmt.Errorf("%s: remote stream arrived too late", err)
return err
case <-ctx.Done():
i.errCh <- fmt.Errorf("%s: Inbox while waiting for stream", ctx.Err())
return ctx.Err()
}
if i.ctxInterceptorFn != nil {
i.ctxInterceptorFn(ctx)
}
i.contextCh <- ctx
return nil
}
// closeLocked closes the inbox, ensuring that any call to RunWithStream will
// return immediately. closeLocked is idempotent.
// NOTE: i.stateMu *must* be held when calling this function.
func (i *Inbox) closeLocked() {
if !i.stateMu.done {
i.stateMu.done = true
close(i.errCh)
}
}
// RunWithStream sets the Inbox's stream and waits until either streamCtx is
// canceled, a caller of Next cancels the first context passed into Next, or
// an EOF is encountered on the stream by the Next goroutine.
func (i *Inbox) RunWithStream(streamCtx context.Context, stream flowStreamServer) error {
streamCtx = logtags.AddTag(streamCtx, "streamID", i.streamID)
log.VEvent(streamCtx, 2, "Inbox handling stream")
defer log.VEvent(streamCtx, 2, "Inbox exited stream handler")
// Pass the stream to the reader goroutine (non-blocking) and get the context
// to listen for cancellation.
i.streamCh <- stream
var readerCtx context.Context
select {
case err := <-i.errCh:
return err
case readerCtx = <-i.contextCh:
log.VEvent(streamCtx, 2, "Inbox reader arrived")
case <-streamCtx.Done():
return fmt.Errorf("%s: streamCtx while waiting for reader (remote client canceled)", streamCtx.Err())
}
// Now wait for one of the events described in the method comment. If a
// cancellation is encountered, nothing special must be done to cancel the
// reader goroutine as returning from the handler will close the stream.
select {
case err := <-i.errCh:
// nil will be read from errCh when the channel is closed.
return err
case <-readerCtx.Done():
// The reader canceled the stream.
return fmt.Errorf("%s: readerCtx in Inbox stream handler (local reader canceled)", readerCtx.Err())
case <-streamCtx.Done():
// The client canceled the stream.
return fmt.Errorf("%s: streamCtx in Inbox stream handler (remote client canceled)", streamCtx.Err())
}
}
// Timeout sends the given error to any readers waiting for a stream to be
// established (i.e. RunWithStream to be called).
func (i *Inbox) Timeout(err error) {
i.timeoutCh <- err
}
// Init is part of the Operator interface.
func (i *Inbox) Init() {}
// Next returns the next batch. It will block until there is data available.
// The Inbox will exit when either the context passed in on the first call to
// Next is canceled or when DrainMeta goroutine tells it to do so.
func (i *Inbox) Next(ctx context.Context) coldata.Batch {
i.stateMu.Lock()
stateMuLocked := true
i.stateMu.nextRunning = true
defer func() {
i.stateMu.nextRunning = false
i.stateMu.nextExited.Signal()
i.stateMu.Unlock()
}()
if i.stateMu.done {
// TODO(yuzefovich): do we want to be on the safe side and explicitly set
// the length here (and below) to 0?
return i.zeroBatch
}
ctx = logtags.AddTag(ctx, "streamID", i.streamID)
defer func() {
// Catch any panics that occur and close the errCh in order to not leak the
// goroutine listening for context cancellation. errCh must still be closed
// during normal termination.
if err := recover(); err != nil {
if !stateMuLocked {
// The panic occurred while we were Recv'ing when we were holding
// i.streamMu and were not holding i.stateMu.
i.stateMu.Lock()
i.streamMu.Unlock()
}
i.closeLocked()
execerror.VectorizedInternalPanic(err)
}
}()
// NOTE: It is very important to close i.errCh only when execution terminates
// ungracefully or when DrainMeta has been called (which indicates a graceful
// termination). DrainMeta will use the stream to read any remaining metadata
// after Next returns a zero-length batch during normal execution.
if err := i.maybeInitLocked(ctx); err != nil {
execerror.VectorizedInternalPanic(err)
}
for {
// DrainMeta goroutine indicated to us that we should exit. We do so
// without closing errCh since DrainMeta still needs the stream.
if i.stateMu.nextShouldExit {
return i.zeroBatch
}
i.stateMu.Unlock()
stateMuLocked = false
i.streamMu.Lock()
m, err := i.streamMu.stream.Recv()
i.streamMu.Unlock()
i.stateMu.Lock()
stateMuLocked = true
if err != nil {
if err == io.EOF {
// Done.
i.closeLocked()
return i.zeroBatch
}
i.errCh <- err
execerror.VectorizedInternalPanic(err)
}
if len(m.Data.Metadata) != 0 {
for _, rpm := range m.Data.Metadata {
meta, ok := execinfrapb.RemoteProducerMetaToLocalMeta(ctx, rpm)
if !ok {
continue
}
i.stateMu.bufferedMeta = append(i.stateMu.bufferedMeta, meta)
}
// Continue until we get the next batch or EOF.
continue
}
if len(m.Data.RawBytes) == 0 {
// Protect against Deserialization panics by skipping empty messages.
continue
}
i.scratch.data = i.scratch.data[:0]
if err := i.serializer.Deserialize(&i.scratch.data, m.Data.RawBytes); err != nil {
execerror.VectorizedInternalPanic(err)
}
if err := i.converter.ArrowToBatch(i.scratch.data, i.scratch.b); err != nil {
execerror.VectorizedInternalPanic(err)
}
return i.scratch.b
}
}
func (i *Inbox) sendDrainSignal(ctx context.Context) error {
log.VEvent(ctx, 2, "Inbox sending drain signal to Outbox")
// It is safe to Send without holding the mutex because it is legal to call
// Send and Recv from different goroutines.
if err := i.streamMu.stream.Send(&execinfrapb.ConsumerSignal{DrainRequest: &execinfrapb.DrainRequest{}}); err != nil {
log.Warningf(ctx, "Inbox unable to send drain signal to Outbox: %+v", err)
return err
}
return nil
}
// DrainMeta is part of the MetadataGenerator interface. DrainMeta may be
// called concurrently with Next.
// Note: DrainMeta will cause Next goroutine to finish.
func (i *Inbox) DrainMeta(ctx context.Context) []execinfrapb.ProducerMetadata {
i.stateMu.Lock()
defer i.stateMu.Unlock()
allMeta := i.stateMu.bufferedMeta
i.stateMu.bufferedMeta = i.stateMu.bufferedMeta[:0]
if i.stateMu.done {
return allMeta
}
ctx = logtags.AddTag(ctx, "streamID", i.streamID)
// We want draining the Inbox to work regardless of whether or not we have a
// goroutine in Next. We essentially need to do two things: 1) Is the stream
// safe to use? If yes, then 2) Make sure nobody else is receiving.
// Unfortunately, there is no way to cancel a Recv on a stream, so we need to
// do this by sending the message. However, we can't unconditionally send a
// message since we don't know the state of the stream (is it initialized?).
// This leaves us with having two separate mutexes, one for the state and
// another one for the stream (to make sure we wait until the Next goroutine
// has finished Recv'ing).
drainSignalSent := false
if i.stateMu.initialized {
if err := i.sendDrainSignal(ctx); err != nil {
return allMeta
}
drainSignalSent = true
i.stateMu.nextShouldExit = true
for i.stateMu.nextRunning {
i.stateMu.nextExited.Wait()
}
// It is possible that Next goroutine has buffered more metadata, so we
// need to grab it.
allMeta = append(allMeta, i.stateMu.bufferedMeta...)
i.stateMu.bufferedMeta = i.stateMu.bufferedMeta[:0]
}
// Note that unlocking defer from above will execute after this defer because
// the unlocking one will be pushed below on the stack, so we still will have
// the lock when this one is executed.
defer i.closeLocked()
if err := i.maybeInitLocked(ctx); err != nil {
log.Warningf(ctx, "Inbox unable to initialize stream while draining metadata: %+v", err)
return allMeta
}
if !drainSignalSent {
if err := i.sendDrainSignal(ctx); err != nil {
return allMeta
}
}
i.streamMu.Lock()
defer i.streamMu.Unlock()
for {
msg, err := i.streamMu.stream.Recv()
if err != nil {
if err == io.EOF {
break
}
log.Warningf(ctx, "Inbox Recv connection error while draining metadata: %+v", err)
return allMeta
}
for _, remoteMeta := range msg.Data.Metadata {
meta, ok := execinfrapb.RemoteProducerMetaToLocalMeta(ctx, remoteMeta)
if !ok {
continue
}
allMeta = append(allMeta, meta)
}
}
return allMeta
}
|
sobolevn/lona
|
lona/routing.py
|
import logging
import re
ABSTRACT_ROUTE_RE = re.compile(r'<(?P<name>[^:>]+)(:(?P<pattern>[^>]+))?>')
ROUTE_PART_FORMAT_STRING = r'(?P<{}>{})'
DEFAULT_PATTERN = r'[^/]+'
OPTIONAL_TRAILING_SLASH_PATTERN = r'(/)'
MATCH_ALL = 1
logger = logging.getLogger('lona.routing')
class Route:
def __init__(self, raw_pattern, view, name='', interactive=True,
http_pass_through=False, frontend_view=None):
self.raw_pattern = raw_pattern
self.view = view
self.name = name
self.interactive = interactive
self.http_pass_through = http_pass_through
self.frontend_view = frontend_view
self.path = None
self.format_string = ''
self.optional_trailing_slash = False
# match all
if self.raw_pattern == MATCH_ALL:
self.path = MATCH_ALL
# string or regex
else:
if self.raw_pattern.endswith(OPTIONAL_TRAILING_SLASH_PATTERN):
self.optional_trailing_slash = True
groups = ABSTRACT_ROUTE_RE.findall(self.raw_pattern)
# path is no pattern but simple string
if not groups:
self.path = self.raw_pattern
self.format_string = self.raw_pattern
if self.optional_trailing_slash:
suffix_len = len(OPTIONAL_TRAILING_SLASH_PATTERN) * -1
self.path = self.path[:suffix_len]
self.format_string = self.path[:suffix_len]
return
pattern_names = [i[0] for i in groups]
patterns = [(i[0], i[2] or DEFAULT_PATTERN, ) for i in groups]
cleaned_pattern = ABSTRACT_ROUTE_RE.sub('{}', self.raw_pattern)
# setup format string
self.format_string = cleaned_pattern.format(
*['{' + i + '}' for i in pattern_names])
# compile pattern
self.pattern = re.compile(
r'^{}{}$'.format(
cleaned_pattern.format(
*[ROUTE_PART_FORMAT_STRING.format(*i)
for i in patterns]
),
(OPTIONAL_TRAILING_SLASH_PATTERN
if self.optional_trailing_slash else ''),
)
)
def match(self, path):
# match all
if self.path == MATCH_ALL:
return True, {}
# simple string
if self.path:
if self.optional_trailing_slash and path.endswith('/'):
path = path[:-1]
return path == self.path, {}
# pattern
match_object = self.pattern.match(path)
if not match_object:
return False, {}
return True, match_object.groupdict()
def __repr__(self):
raw_pattern = self.raw_pattern
if raw_pattern == MATCH_ALL:
raw_pattern = 'MATCH_ALL'
return '<Route({}, {})>'.format(
raw_pattern,
self.view,
)
class Router:
def __init__(self):
self.routes = []
def add_route(self, route):
self.routes.append(route)
def add_routes(self, *routes):
for route in routes:
self.add_route(route)
def resolve(self, path):
logger.debug("resolving '%s'", path)
for route in self.routes:
match, match_info = route.match(path)
if match:
logger.debug('%s matched', route)
return True, route, match_info
logger.debug("no match for '%s'", path)
return False, None, {}
def reverse(self, name, *args, **kwargs):
route = None
for i in self.routes:
if i.name == name:
route = i
break
if not route:
raise ValueError("no route named '{}' found".format(name))
if route.path:
return route.path
key_error = None
try:
return route.format_string.format(*args, **kwargs)
except KeyError as e:
key_error = e
raise ValueError('missing URL arg: {} '.format(key_error.args[0]))
|
Zi0P4tch0/sdks
|
iPhoneOS14.2.sdk/System/Library/Frameworks/GameKit.framework/Headers/GKSavedGame.h
|
<filename>iPhoneOS14.2.sdk/System/Library/Frameworks/GameKit.framework/Headers/GKSavedGame.h
//
// GKSavedGame.h
// Game Center
//
// Copyright 2010-2020 Apple Inc. All rights reserved.
//
#import <GameKit/GKLocalPlayer.h>
#import <GameKit/GKSavedGameListener.h>
/// Class representing a saved game for the local player, or a version of a saved game when in conflict
NS_CLASS_AVAILABLE(10_10, 8_0) __WATCHOS_PROHIBITED
@interface GKSavedGame : NSObject <NSCopying>
NS_ASSUME_NONNULL_BEGIN
@property (atomic, nullable, readonly) NSString *name NS_AVAILABLE(10_10, 8_0);
@property (atomic, nullable, readonly) NSString *deviceName NS_AVAILABLE(10_10, 8_0);
@property (atomic, nullable, readonly) NSDate *modificationDate NS_AVAILABLE(10_10, 8_0);
/// Asynchronously load the data for this saved game. The completion handler is called with loaded data or an error.
- (void)loadDataWithCompletionHandler:(void(^__nullable)(NSData * __nullable data, NSError * __nullable error))handler NS_AVAILABLE(10_10, 8_0);
@end
#if !TARGET_OS_WATCH && !TARGET_OS_TV
@interface GKLocalPlayer (GKSavedGame) <GKSavedGameListener>
/// Asynchronously fetch saved games. The handler is called with an array of GKSavedGame objects or an error.
/// If there is more than one saved game with the same name then a conflict exists. The application should determine the correct data to use and call resolveConflictingSavedGames:withData:completionHandler:. This may require data merging or asking the user.
- (void)fetchSavedGamesWithCompletionHandler:(void(^__nullable)(NSArray<GKSavedGame *> * __nullable savedGames, NSError * __nullable error))handler NS_AVAILABLE(10_10, 8_0) ;
/// Asynchronously save game data. If a saved game with that name already exists it is overwritten, otherwise a new one is created. The completion handler is called with the new / modified GKSavedGame or an error.
/// If the saved game was in conflict then the overwritten version will be the one with the same deviceName if present, otherwise the most recent overall.
- (void)saveGameData:(NSData *)data withName:(NSString *)name completionHandler:(void(^__nullable)(GKSavedGame * __nullable savedGame, NSError * __nullable error))handler NS_AVAILABLE(10_10, 8_0) ;
/// Asynchronously delete saved games with the given name. The completion handler will indicate whether or not the deletion was successful.
- (void)deleteSavedGamesWithName:(NSString *)name completionHandler:(void(^__nullable)(NSError * __nullable error))handler NS_AVAILABLE(10_10, 8_0) ;
/// Asynchronously resolve a saved game conflict. This deletes all versions included in conflictingSavedGames and creates a new version with the given data. The completion handler is called with the newly created save and all other remaining versions or an error.
- (void)resolveConflictingSavedGames:(NSArray<GKSavedGame *> *)conflictingSavedGames withData:(NSData *)data completionHandler:(void(^__nullable)(NSArray<GKSavedGame *> * __nullable savedGames, NSError * __nullable error))handler NS_AVAILABLE(10_10, 8_0) ;
@end
#endif
NS_ASSUME_NONNULL_END
|
LauZyHou/-
|
LeetCode/面试题 17.20.cpp
|
<filename>LeetCode/面试题 17.20.cpp
class MedianFinder {
private:
// 存小数的最大堆
priority_queue<int, vector<int>, less<int> > sml;
// 存大数的最小堆
priority_queue<int, vector<int>, greater<int> > big;
public:
/** initialize your data structure here. */
MedianFinder() {
sml = priority_queue<int, vector<int>, less<int> >();
big = priority_queue<int, vector<int>, greater<int> >();
}
void addNum(int num) {
if (sml.size() == big.size()) {
big.push(num);
int val = big.top();
big.pop();
sml.push(val);
}
else {
sml.push(num);
int val = sml.top();
sml.pop();
big.push(val);
}
}
double findMedian() {
if (big.size() == sml.size()) {
double vb = big.top();
double vs = sml.top();
return (vb + vs) / 2;
}
else {
return sml.top();
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
|
roj234/rojlib
|
roj/opengl/text/FontTex.java
|
/*
* This file is a part of MI
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Roj234
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package roj.opengl.text;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL30;
import roj.collect.*;
import roj.io.IOUtil;
import roj.opengl.texture.TextureManager;
import roj.opengl.util.Util;
import roj.text.CharList;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.function.IntFunction;
import static org.lwjgl.opengl.GL11.*;
/**
* No description provided
*
* @author Roj234
* @version 0.1
* @since 2021/2/3 21:47
*/
public class FontTex {
public static final class Tex {
public final int textureId;
public final int width, height, bottom;
public final float u1, v1, u2, v2;
public Tex(int textureId, Rectangle rect, int boundaryHeight, float x, float y) {
this.textureId = textureId;
this.width = rect.width;
this.height = rect.height;
// boundary: 32 while top = 10 means (22 - height) px for bottom
this.bottom = boundaryHeight - rect.y - rect.height;
this.u1 = x / TEXTURE_SIZE;
this.v1 = y / TEXTURE_SIZE;
this.u2 = (x + width) / TEXTURE_SIZE;
this.v2 = (y + height) / TEXTURE_SIZE;
}
}
public static final int TEXTURE_SIZE = 256;
public static final int GLYPH_BORDER = 1;
public static final int LAYOUT_FLAGS = Font.LAYOUT_LEFT_TO_RIGHT;
public static final Font DEFAULT_FONT;
static {
/* Use Java's logical font as the default initial font if user does not override it in some configuration file */
GraphicsEnvironment.getLocalGraphicsEnvironment().preferLocaleFonts();
DEFAULT_FONT = new Font(null, Font.PLAIN, 24);
}
private static final Color TRANSPARENT = new Color(1, 1, 1, 0);
private static final IntFunction<IntList> WII = value -> new IntList();
private static BufferedImage charTmpImg = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY);
private static Graphics2D charGraphics = charTmpImg.createGraphics();
private static FontRenderContext charFRC = charGraphics.getFontRenderContext();
private static void resizeCharTmp(int w, int h) {
charTmpImg = new BufferedImage(w + 2, h, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D cg = charGraphics = charTmpImg.createGraphics();
cg.setBackground(TRANSPARENT);
cg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
cg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
cg.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
cg.setPaint(Color.WHITE);
charFRC = cg.getFontRenderContext();
}
public final Font font;
public final BufferedImage textureImage = new BufferedImage(TEXTURE_SIZE, TEXTURE_SIZE, BufferedImage.TYPE_BYTE_GRAY);
private final Graphics2D textureGraphics = textureImage.createGraphics();
/**
* ID of current OpenGL cache texture being used by cacheGlyphs() to store pre-rendered glyph images.
* efficiency
*/
private int textureId = -1;
private final Int2IntMap textureIds = new Int2IntMap();
private final byte transparentFilter;
private final CharMap<Tex> charTexture = new CharMap<>();
private final CharMap<IntList> byWidth = new CharMap<>();
private int currImgX, currImgY, currLineHeight;
public FontTex(String nameAndCfg, int transparentFilter) {
if(nameAndCfg != null) {
this.font = Font.decode(nameAndCfg);
} else {
this.font = DEFAULT_FONT;
}
textureGraphics.setBackground(TRANSPARENT);
textureGraphics.setComposite(AlphaComposite.Src);
this.transparentFilter = (byte) transparentFilter;
}
public FontTex(String nameAndCfg) {
this(nameAndCfg, 0xA0);
}
public Tex getEntry(char c) {
Tex tex = charTexture.get(c);
if(tex != null)
textureIds.getEntry(tex.textureId).v = (int) System.currentTimeMillis();
return tex;
}
public Tex getOrCreateEntry(char c) {
if(!charTexture.containsKey(c)) {
preRender(String.valueOf(c), 0, 1);
}
Tex tex = charTexture.get(c);
if(tex != null)
textureIds.getEntry(tex.textureId).v = (int) System.currentTimeMillis();
return tex;
}
public void invalidateCache(int delta) {
int v = (int) (System.currentTimeMillis() - delta);
for (Iterator<Int2IntMap.Entry> itr = textureIds.entrySet().iterator(); itr.hasNext(); ) {
Int2IntMap.Entry entry = itr.next();
if (entry.v < v) {
glDeleteTextures(entry.getKey());
itr.remove();
}
}
}
public IntList getEntriesByWidth(int w) {
IntList list = byWidth.get((char) w);
return list == null ? new IntList() : list;
}
public Font getFont() {
return font;
}
@Override
public void finalize() {
if(textureIds.size() == 0) return;
for (PrimitiveIterator.OfInt itr = textureIds.keySet().iterator(); itr.hasNext(); ) {
glDeleteTextures(itr.nextInt());
}
textureIds.clear();
charTexture.clear();
byWidth.clear();
}
public void dumpTexture() {
glDisable(GL_CULL_FACE);
int z = 100;
for (PrimitiveIterator.OfInt itr = textureIds.keySet().iterator(); itr.hasNext(); ) {
glBindTexture(GL_TEXTURE_2D, itr.nextInt());
glBegin(GL_QUADS);
glVertex3i(50, -50, z);
glTexCoord2f(0, 0);
glVertex3i(50, 50, z);
glTexCoord2f(1, 0);
glVertex3i(-50, 50, z);
glTexCoord2f(1, 1);
glVertex3i(-50, -50, z);
glTexCoord2f(0, 1);
glEnd();
z += 20;
}
glEnable(GL_CULL_FACE);
}
public int preRender(CharSequence chars, int start, int length) {
length += start;
final CharMap<Tex> done = this.charTexture;
IBitSet tmp = new LongBitSet();
CharList noDuplicate = new CharList();
for (int i = start; i < length; i++) {
char c = chars.charAt(i);
if(!done.containsKey(c) && tmp.add(c)) {
noDuplicate.append(c);
}
}
if(noDuplicate.length() > 0) {
noDuplicate.append('|'); // 限制最低高度
preRender0(noDuplicate.list, 0, noDuplicate.length());
}
return font.getSize();
}
private void preRender0(char[] chars, int start, int length) {
if(textureId == -1) {
textureId = allocateTexture();
}
GlyphVector vector = font.layoutGlyphVector(charFRC, chars, start, start + length, LAYOUT_FLAGS);
int flag = vector.getLayoutFlags();
if((flag & GlyphVector.FLAG_COMPLEX_GLYPHS) != 0) {
System.err.println("[FontEx]Complex Char Glyph Detected");
}
int numGlyphs = vector.getNumGlyphs();
for (int i = 0; i < numGlyphs; i++) {
Point2D pos = vector.getGlyphPosition(i);
pos.setLocation(pos.getX() + 2 * i, pos.getY());
vector.setGlyphPosition(i, pos);
}
numGlyphs--;
Rectangle bound = vector.getPixelBounds(charFRC, 0, 0);
if (bound.width > charTmpImg.getWidth() || bound.height > charTmpImg.getHeight()) {
resizeCharTmp(bound.width, bound.height);
}
charGraphics.clearRect(0, 0, bound.width, bound.height);
charGraphics.drawGlyphVector(vector, -bound.x, -bound.y);
Rectangle dirty = new Rectangle();
int lineHeight = currLineHeight;
int i, x = this.currImgX, y = this.currImgY;
for (i = 0; i < numGlyphs; i++) {
Rectangle rect = vector.getGlyphPixelBounds(i, null, -bound.x, -bound.y);
if (x + rect.width + GLYPH_BORDER > TEXTURE_SIZE) {
x = GLYPH_BORDER;
y += lineHeight + GLYPH_BORDER;
lineHeight = 0;
}
if (y + rect.height + GLYPH_BORDER > TEXTURE_SIZE) {
break;
}
if (rect.height > lineHeight) {
lineHeight = rect.height;
}
textureGraphics.drawImage(charTmpImg,
x, y, x + rect.width, y + rect.height,
rect.x, rect.y, rect.x + rect.width, rect.y + rect.height,
null);
charTexture.put(chars[start + i], new Tex(textureId, rect, bound.height, x, y));
byWidth.computeIfAbsent((char) rect.width, WII).add(chars[start + i]);
rect.setLocation(x, y);
dirty.add(rect);
x += rect.width + GLYPH_BORDER;
}
updateTexture(dirty, textureId);
if(i < numGlyphs) {
// 超高, 搞一个新的材质
this.textureId = -1;
this.currImgX = 0;
this.currImgY = 0;
this.currLineHeight = 0;
preRender0(chars, start + i, length);
} else {
this.currLineHeight = lineHeight;
this.currImgX = x;
this.currImgY = y;
}
}
private void updateTexture(Rectangle dirty, int textureId) {
int prevTexture = glGetInteger(GL_TEXTURE_BINDING_2D);
Util.bindTexture(textureId);
// ! 向纹理中写入数据的时候不清空其内部的数据在特定情况可能会降低性能
synchronized (TextureManager.UPLOAD_LOCK) {
ByteBuffer buf = TextureManager.uploadImage(textureImage, dirty.x, dirty.y, dirty.width, dirty.height);
if(transparentFilter != 0x00) {
int target = transparentFilter & 0xFF;
for (int i = 0; i < buf.limit(); i += 4) {
if((buf.get(i + 3) & 0xFF) < target) {
buf.put(i + 3, (byte) 0);
}
}
}
glTexSubImage2D(GL_TEXTURE_2D, 0,
dirty.x, dirty.y, dirty.width, dirty.height,
GL12.GL_BGRA, GL_UNSIGNED_BYTE, buf);
if(buf != TextureManager.UPLOAD_LOCK) {
IOUtil.clean(buf);
}
}
/* Re-generate mipmap */
GL30.glGenerateMipmap(GL_TEXTURE_2D);
Util.bindTexture(prevTexture);
}
private int allocateTexture() {
//Initialize the background.
textureGraphics.clearRect(0, 0, TEXTURE_SIZE, TEXTURE_SIZE);
//Allocate new OpenGL texture
textureIds.put(textureId = glGenTextures(), (int) System.currentTimeMillis());
int prevTexture = glGetInteger(GL_TEXTURE_BINDING_2D);
Util.bindTexture(textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL12.GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 4);
// 上传空图像, alpha8: 256级透明度
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, TEXTURE_SIZE, TEXTURE_SIZE, 0, GL12.GL_BGRA, GL_UNSIGNED_BYTE, (ByteBuffer) null);
Util.bindTexture(prevTexture);
return textureId;
}
}
|
MBKayro/kolibri
|
kolibri/core/assets/src/utils/setupAndLoadFonts.js
|
<gh_stars>100-1000
import FontFaceObserver from 'fontfaceobserver';
import { availableLanguages, currentLanguage } from 'kolibri.utils.i18n';
import logger from 'kolibri.lib.logging';
import { browser, passesRequirements } from './browserInfo';
import plugin_data from 'plugin_data';
const logging = logger.getLogger(__filename);
// These browsers fully support font-display: swap
// https://caniuse.com/?search=swap
const fontSwapSupportingBrowsers = {
Edge: {
major: 17,
},
Firefox: {
major: 58,
},
Chrome: {
major: 60,
},
'Chrome WebView': {
major: 60,
},
Safari: {
major: 11,
minor: 1,
},
Opera: {
major: 47,
},
'Mobile Safari': {
major: 11,
minor: 4,
},
IE: {
major: 100, // specify impossible IE version, forcing passesRequirements to fail
},
};
// See
// https://github.com/learningequality/kolibri-design-system/blob/main/lib/styles/definitions.scss
const FULL_FONTS = 'full-fonts-loaded';
const PARTIAL_FONTS = 'partial-fonts-loaded';
function loadFullFontsProgressively() {
/*
* This function eagerly loads the full fonts for the current language asynchronously, but
* avoids referencing them until they've been fully loaded. This is done by adding a
* class to the HTML root which has the effect of switching fonts from system defaults
* to Noto.
*
* This prevents the text from being invisible while the fonts are loading ("FOIT")
* and instead falls back on system fonts while they're loading ("FOUT").
*/
const htmlEl = document.documentElement;
htmlEl.classList.add(PARTIAL_FONTS);
const uiNormal = new FontFaceObserver('noto-full', { weight: 400 });
const uiBold = new FontFaceObserver('noto-full', { weight: 700 });
// passing the language name to 'load' for its glyphs, not its value per se
const string = availableLanguages[currentLanguage].lang_name;
Promise.all([uiNormal.load(string, 20000), uiBold.load(string, 20000)])
.then(function() {
htmlEl.classList.remove(PARTIAL_FONTS);
htmlEl.classList.add(FULL_FONTS);
logging.debug(`Loaded full font for '${currentLanguage}'`);
})
.catch(function() {
logging.warn(`Could not load full font for '${currentLanguage}'`);
});
}
function loadFullFontsImmediately() {
const htmlEl = document.documentElement;
htmlEl.classList.add(FULL_FONTS);
}
function addFontStylesheetLink(href) {
const fonts = document.createElement('link');
fonts.rel = 'stylesheet';
fonts.type = 'text/css';
fonts.href = href;
document.head.appendChild(fonts);
}
export default function setupAndLoadFonts() {
if (passesRequirements(browser, fontSwapSupportingBrowsers)) {
addFontStylesheetLink(plugin_data.fullCSSFileModern);
loadFullFontsImmediately();
} else {
addFontStylesheetLink(plugin_data.fullCSSFileBasic);
loadFullFontsProgressively();
}
}
|
MrSandman5/2019-ads
|
src/main/java/ru/mail/polis/ads/part2/MrSandman5/Task1.java
|
package ru.mail.polis.ads.part2.MrSandman5;
/*В индийском храме пол прямоугольной формы выложен одинаковыми квадратными плитками 1 х 1, на каждую из которых высыпано от 0 до k зернышек (k ≤ 30000). Размеры пола m х n.
Мышка выбегает из левого нижнего угла пола храма и двигается к входу в другую норку, расположенную в противоположном углу.
Мышка может двигаться только вправо или вперед, собирая все зернышки с плитки, на которой она находится.
Найти маршрут, двигаясь по которому мышка соберет наибольшее количество зернышек.
Входные данные
Первая строка содержит числа m и n – размеры пола (1 ≤ m, n ≤ 100).
Далее идет m строк, начиная сверху, в каждой из которых размещено n чисел – количество зернышек на соответствующей плитке.
Выходные данные
Вывести маршрут движения мышки в формате: RRFFFRF (F – шаг вперед, R – шаг вправо).
* */
//https://www.e-olymp.com/ru/submissions/5847303
import java.io.*;
import java.util.StringTokenizer;
public class Task1 {
private static void solve(final FastScanner in, final PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
long[][] board = new long[100][100];
StringBuilder sb = new StringBuilder();
for (int i = n - 1; i >= 0; i--)
for (int j = 0; j < m; j++)
board[i][j] = in.nextLong();
for(int i = 1; i < n; i++)
board[i][0] = board[i][0] + board[i-1][0];
for(int j = 1; j < m; j++)
board[0][j] = board[0][j] + board[0][j-1];
for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++)
board[i][j] = board[i][j] + Math.max(board[i - 1][j], board[i][j - 1]);
int k = n - 1, t = m - 1;
while (k > 0 || t > 0){
if (k > 0 && t > 0){
if (board[k-1][t] > board[k][t-1]){
sb.append("F");
k--;
}
else{
sb.append("R");
t--;
}
}
else if (k == 0){
sb.append("R");
t--;
}
else if (t == 0){
sb.append("F");
k--;
}
}
out.println(sb.reverse().toString());
}
private static class FastScanner {
private final BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(final InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong(){ return Long.parseLong(next());}
}
public static void main(final String[] arg) {
final FastScanner in = new FastScanner(System.in);
try (PrintWriter out = new PrintWriter(System.out)) {
solve(in, out);
}
}
}
|
cquoss/jboss-4.2.3.GA-jdk8
|
testsuite/src/main/org/jboss/test/aop/bean/CallingPOJO.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.aop.bean;
import org.jboss.aop.Advised;
/**
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision: 57211 $
*/
public class CallingPOJO
{
POJO pojo;
NonadvisedPOJO nonpojo;
public CallingPOJO()
{
CallerInterceptor.called = false;
pojo = new POJO();
if (!CallerInterceptor.called)
{
throw new RuntimeException("constructor caller interceptor didn't work from within constructor");
}
CallerInterceptor.called = false;
pojo.someMethod();
if (!CallerInterceptor.called)
{
throw new RuntimeException("caller interceptor didn't work");
}
CallerInterceptor.called = false;
nonpojo = new NonadvisedPOJO("helloworld");
if (!CallerInterceptor.called)
{
throw new RuntimeException("constructor caller interceptor didn't work");
}
CallerInterceptor.called = false;
nonpojo.remoteTest();
if (!CallerInterceptor.called)
{
throw new RuntimeException("caller interceptor didn't work");
}
if (nonpojo instanceof Advised)
{
throw new RuntimeException("nonpojo is Advised when it shouldn't be");
}
}
/**
* This method should be a caller pointcut
*/
public void callSomeMethod()
{
CallerInterceptor.called = false;
pojo = new POJO();
if (!CallerInterceptor.called)
{
throw new RuntimeException("constructor caller interceptor didn't work within method");
}
CallerInterceptor.called = false;
pojo.someMethod();
if (!CallerInterceptor.called)
{
throw new RuntimeException("caller interceptor didn't work");
}
}
/**
* This method should not be a caller pointcut
*/
public void nocallSomeMethod()
{
CallerInterceptor.called = false;
pojo = new POJO();
if (CallerInterceptor.called)
{
throw new RuntimeException("constructor caller interceptor didn't work, interceptor was invoked when it shouldn't have been");
}
pojo.someMethod();
if (CallerInterceptor.called)
{
throw new RuntimeException("caller interceptor didn't work, caller interceptor was invoked when it shouldn't have been");
}
}
public void callUnadvised()
{
CallerInterceptor.called = false;
nonpojo = new NonadvisedPOJO("helloworld");
if (!CallerInterceptor.called)
{
throw new RuntimeException("consturctor caller interceptor didn't work");
}
CallerInterceptor.called = false;
nonpojo.remoteTest();
if (!CallerInterceptor.called)
{
throw new RuntimeException("caller interceptor didn't work");
}
if (nonpojo instanceof Advised)
{
throw new RuntimeException("nonpojo is Advised when it shouldn't be");
}
}
}
|
dldevinc/paper-uploads
|
paper_uploads/forms/dialogs/file.py
|
<gh_stars>1-10
from ...models.file import UploadedFile
from .base import UploadedFileBaseForm
class UploadedFileDialog(UploadedFileBaseForm):
class Meta:
model = UploadedFile
fields = ("new_name", "display_name")
|
ray1888/leetcode-interview
|
easy100/intersection_of_two_arrays.go
|
<reponame>ray1888/leetcode-interview
package easy100
func intersection(nums1 []int, nums2 []int) []int {
if len(nums1) == 0 || len(nums2) == 0 {
return []int{}
}
num1Map := make(map[int]bool)
for _, item := range nums1 {
num1Map[item] = true
}
resultMap := make(map[int]bool)
for _, item := range nums2 {
if _, ok := num1Map[item]; ok {
resultMap[item] = true
}
}
result := make([]int, 0)
for item := range resultMap {
result = append(result, item)
}
return result
}
|
mathewhawley/suitejs
|
packages/icons/src/md/image/Details.js
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdDetails(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 8h36L24 40 6 8zm6.75 4L24 32l11.25-20h-22.5z" />
</IconBase>
);
}
export default MdDetails;
|
RAM-16/gdscaec-Angular
|
node_modules/core-js/es/regexp/sticky.js
|
<gh_stars>1000+
require('../../modules/es.regexp.constructor');
require('../../modules/es.regexp.exec');
require('../../modules/es.regexp.sticky');
module.exports = function (it) {
return it.sticky;
};
|
sujith-mn/cobigen
|
cobigen-cli/cli/src/main/java/com/devonfw/cobigen/cli/utils/ValidationUtils.java
|
package com.devonfw.cobigen.cli.utils;
import java.io.File;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.devonfw.cobigen.api.to.GenerationReportTo;
import com.devonfw.cobigen.cli.CobiGenCLI;
/**
* Utilities class for validating user's input and generation
*/
public final class ValidationUtils {
/**
* Logger useful for printing information
*/
private static Logger LOG = LoggerFactory.getLogger(CobiGenCLI.class);
/**
* Extension of a POM file
*/
private static final String POM_EXTENSION = "xml";
/**
* Validating user input file is correct or not. We check if file exists and it can be read
*
* @param inputFile
* user input file
* @return true when file is valid
*/
public boolean validateFile(File inputFile) {
if (inputFile == null) {
return false;
}
if (!inputFile.exists()) {
LOG.error("The input file " + inputFile.getAbsolutePath() + " has not been found on your system.");
return false;
}
if (!inputFile.canRead()) {
LOG.error("The input file '{}' cannot be read. Please check file permissions on the file",
inputFile.getAbsolutePath());
return false;
}
return true;
}
/**
* Tries to find a pom.xml file in the passed folder
* @param source
* folder where we check if a pom.xml file is found
* @return the pom.xml file if it was found, null otherwise
*/
public static File findPom(File source) {
String filename = source.getName();
if (source.isFile()) {
String basename;
File pomFile;
int lastDot = filename.lastIndexOf('.');
if (lastDot > 0) {
basename = filename.substring(0, lastDot);
pomFile = new File(source.getParent(), basename + '.' + POM_EXTENSION);
if (pomFile.exists() || pomFile.toString().contains("pom.xml")) {
LOG.info("This is a valid maven project project ");
return pomFile;
}
}
int lastSlash = filename.indexOf('-');
if (lastSlash > 0) {
basename = filename.substring(0, lastSlash);
pomFile = new File(source.getParent(), basename + POM_EXTENSION);
if (pomFile.exists()) {
return pomFile;
}
}
return findPomFromFolder(source.getAbsoluteFile().getParentFile());
} else if (source.isDirectory()) {
return findPomFromFolder(source);
}
return null;
}
/**
* Recursively tries to find a pom.xml file in the parent folders
* @param folder
* folder where we want to recursively find the pom.xml
* @return the pom.xml file if it was found, null otherwise
*/
private static File findPomFromFolder(File folder) {
if (folder == null) {
return null;
}
String POM_XML = "pom.xml";
File pomFile = new File(folder, POM_XML);
if (pomFile.exists()) {
return pomFile;
}
return findPomFromFolder(folder.getParentFile());
}
/**
* Checks whether all the user input files are of the same type
* @param inputFiles
* user input files
* @return true when all input files are equal
*/
public static Boolean areInputFilesSameType(ArrayList<File> inputFiles) {
for (int i = 0; i < inputFiles.size() - 1; i++) {
String extensionCurrentFile = inputFiles.get(i).getName().toLowerCase();
String extensionNextFile = inputFiles.get(i + 1).getName().toLowerCase();
if (extensionCurrentFile.equals(extensionNextFile) == false) {
return false;
}
}
return true;
}
/**
* Checks whether the current output root path is valid. It can be either null because it is an optional
* parameter or either a folder that exists.
* @param outputRootPath
* where the user wants to generate the code
*
* @return true if it is a valid output root path
*/
public static Boolean isOutputRootPathValid(File outputRootPath) {
// As outputRootPath is an optional parameter, it means that it can be null
if (outputRootPath == null || outputRootPath.exists()) {
return true;
} else {
LOG.error("Your <outputRootPath> '{}' does not exist, please use a valid path.", outputRootPath);
return false;
}
}
/**
* Checks the generation report in order to find possible errors and warnings
* @param report
* the generation report returned by the CobiGen.generate method
* @return true of the generation was successful, false if any error occurred
*/
public static Boolean checkGenerationReport(GenerationReportTo report) {
for (String warning : report.getWarnings()) {
LOG.debug("Warning: {}", warning);
}
if (report.getErrors() == null || report.getErrors().isEmpty()) {
LOG.info("Successful generation.\n");
return true;
} else {
LOG.error("Generation failed due to the following problems:");
for (Throwable throwable : report.getErrors()) {
LOG.error(throwable.getMessage());
}
return false;
}
}
/**
* Prints an error message to the user informing that no triggers have been matched. Depending on the type
* of the input file will print different messages.
* @param inputFile
* User input file
* @param isJavaInput
* true when input file is Java
* @param isOpenApiInput
* true when input file is OpenAPI
*/
public static void printNoTriggersMatched(File inputFile, Boolean isJavaInput, Boolean isOpenApiInput) {
LOG.error(
"Your input file '{}' is not valid as input for any generation purpose. It does not match any trigger.",
inputFile.getName());
if (isJavaInput) {
LOG.error("Check that your Java input file is following devon4j naming convention. "
+ "Explained on https://github.com/devonfw/devon4j/wiki/coding-conventions");
} else if (isOpenApiInput) {
LOG.error("Validate your OpenAPI specification, check that is following 3.0 standard. "
+ "More info here https://github.com/devonfw/cobigen/wiki/cobigen-openapiplugin#usage");
}
throw new IllegalArgumentException("Your input file is invalid");
}
}
|
northwesternmutual/kanali
|
spec/service_test.go
|
// Copyright (c) 2017 <NAME>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package spec
import (
"bytes"
"net/http"
"testing"
"github.com/northwesternmutual/kanali/config"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
)
func TestGetServiceStore(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
store.Clear()
assert.Equal(0, len(store.serviceMap), "store should be empty")
v := ServiceFactory{}
var i interface{} = &v
_, ok := i.(Store)
assert.True(ok, "ServiceFactory does not implement the Store interface")
}
func TestIsEmpty(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Clear()
assert.True(store.IsEmpty())
store.Set(serviceList[0])
assert.False(store.IsEmpty())
store.Clear()
assert.True(store.IsEmpty())
store.Set(serviceList[0])
assert.False(store.IsEmpty())
store.Delete(serviceList[0])
assert.True(store.IsEmpty())
}
func TestCreateService(t *testing.T) {
assert := assert.New(t)
message := "service received is not expected"
svc := CreateService(api.Service{
TypeMeta: unversioned.TypeMeta{},
ObjectMeta: api.ObjectMeta{
Name: "foo",
Namespace: "bar",
Labels: map[string]string{
"one": "two",
"three": "four",
},
},
Spec: api.ServiceSpec{},
})
assert.Equal("foo", svc.Name, message)
assert.Equal("bar", svc.Namespace, message)
assert.Equal(2, len(svc.Labels), message)
assert.True((svc.Labels[0] == Label{
Name: "one",
Value: "two",
}) || (svc.Labels[1] == Label{
Name: "one",
Value: "two",
}), message)
assert.True((svc.Labels[0] == Label{
Name: "three",
Value: "four",
}) || (svc.Labels[1] == Label{
Name: "three",
Value: "four",
}), message)
}
func TestServiceSet(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Clear()
store.Set(serviceList[0])
store.Set(serviceList[1])
err := store.Set(APIProxy{})
assert.Equal(err.Error(), "grrr - you're only allowed add services to the services store.... duh", "wrong error")
assert.Equal(2, len(store.serviceMap), "store should have 2 namespaces represented")
assert.Equal(serviceList[0], store.serviceMap["foo"][0], "service should be present")
assert.Equal(serviceList[1], store.serviceMap["bar"][0], "service should be present")
svcOne := serviceList[0]
svcTwo := serviceList[1]
svcOne.Labels[1].Name = "name-foo"
svcTwo.Labels[1].Name = "name-foo"
store.Set(serviceList[0])
store.Set(serviceList[1])
assert.Equal(svcOne, store.serviceMap["foo"][0], "service should be present")
assert.Equal(svcTwo, store.serviceMap["bar"][0], "service should be present")
store.Set(serviceList[2])
assert.Equal(serviceList[2], store.serviceMap["bar"][1], "service should be present")
}
func TestServiceUpdate(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Clear()
store.Update(serviceList[0])
store.Update(serviceList[1])
err := store.Update(APIProxy{})
assert.Equal(err.Error(), "grrr - you're only allowed add services to the services store.... duh", "wrong error")
assert.Equal(2, len(store.serviceMap), "store should have 2 namespaces represented")
assert.Equal(serviceList[0], store.serviceMap["foo"][0], "service should be present")
assert.Equal(serviceList[1], store.serviceMap["bar"][0], "service should be present")
svcOne := serviceList[0]
svcTwo := serviceList[1]
svcOne.Labels[1].Name = "name-foo"
svcTwo.Labels[1].Name = "name-foo"
store.Update(serviceList[0])
store.Update(serviceList[1])
assert.Equal(svcOne, store.serviceMap["foo"][0], "service should be present")
assert.Equal(svcTwo, store.serviceMap["bar"][0], "service should be present")
store.Update(serviceList[2])
assert.Equal(serviceList[2], store.serviceMap["bar"][1], "service should be present")
}
func TestServiceClear(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Set(serviceList[0])
store.Set(serviceList[1])
store.Set(serviceList[2])
store.Clear()
assert.Equal(0, len(store.serviceMap), "store should be empty")
}
func TestEquals(t *testing.T) {
defer viper.Reset()
h := http.Header{}
h.Add("x-nm-deploy", "production")
l1 := Label{
Name: "release",
Header: "x-nm-deploy",
}
l2 := Label{
Name: "release",
Header: "x-nm-deploy-foo",
}
assert.True(t, l1.equals(Label{
Name: "release",
Value: "production",
}, h))
assert.False(t, l1.equals(Label{
Name: "release",
Value: "test",
}, h))
viper.SetConfigType("toml")
viper.ReadConfig(bytes.NewBuffer([]byte(`
[proxy.default_header_values]
x-nm-deploy = "stable"
x-nm-deploy-foo = "hello"
`)))
h.Del("x-nm-deploy")
assert.True(t, l1.equals(Label{
Name: "release",
Value: "stable",
}, h))
assert.True(t, l2.equals(Label{
Name: "release",
Value: "hello",
}, h))
viper.Reset()
viper.SetConfigType("toml")
viper.ReadConfig(bytes.NewBuffer([]byte(`
[proxy.default_header_values]
x-nm-deploy = ""
`)))
assert.False(t, l1.equals(Label{
Name: "release",
Value: "stable",
}, h))
}
func TestServiceGet(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Clear()
store.Set(serviceList[0])
store.Set(serviceList[1])
_, err := store.Get("")
assert.Equal(err.Error(), "getting a service requires 2 parameters", "wrong error")
_, err = store.Get(APIProxy{}, "")
assert.Equal(err.Error(), "first argument should be a service", "wrong error")
_, err = store.Get(Service{}, 5)
assert.Equal(err.Error(), "second argument should either be nil or http.Header", "wrong error")
headerOne := http.Header{}
headerOne.Add("x-nm-deploy", "production")
headerTwo := http.Header{}
headerTwo.Add("X-nM-dePloy", "pRoduCtion")
viper.SetDefault(config.FlagProxyDefaultHeaderValues.GetLong(), map[string]string{
"x-nm-deploy": "production",
})
result, _ := store.Get(Service{}, nil)
assert.Nil(result, "nil service should return nil")
result, _ = store.Get(Service{
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
},
}, headerOne)
assert.Equal(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-two",
},
},
}, headerOne)
assert.Equal(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-two",
},
},
}, nil)
assert.Equal(serviceList[0], result, "service should exist")
viper.SetDefault(config.FlagProxyDefaultHeaderValues.GetLong(), map[string]string{
"x-nm-deploy": "",
})
result, _ = store.Get(Service{
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-two",
},
},
}, nil)
assert.Nil(result, "service should not exist")
result, _ = store.Get(Service{
Namespace: "foo",
Labels: Labels{
Label{
Name: "name-two",
Value: "value-two",
},
},
}, headerOne)
assert.Equal(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "bar",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-three",
},
},
}, headerOne)
assert.NotEqual(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Name: "my-cool-service-one",
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-three",
},
},
}, headerOne)
assert.Equal(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "bar",
Labels: Labels{
Label{
Name: "release",
Header: "x-nm-deploy",
},
Label{
Name: "name-two",
Value: "value-three",
},
},
}, headerTwo)
assert.NotEqual(serviceList[0], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "bar",
Labels: Labels{
Label{
Name: "name-prime-one",
Header: "x-nm-deploy",
},
Label{
Name: "name-prime-two",
Value: "value-two",
},
},
}, nil)
assert.NotEqual(serviceList[1], result, "service should exist")
result, _ = store.Get(Service{
Namespace: "bar",
Labels: Labels{
Label{
Name: "name-prime-one",
Value: "value-one",
},
Label{
Name: "name-prime-two",
Value: "value-two",
},
},
}, nil)
assert.Equal(serviceList[1], result, "service should exist")
}
func TestServiceDelete(t *testing.T) {
assert := assert.New(t)
store := ServiceStore
serviceList := getTestServiceList()
store.Clear()
store.Set(serviceList[0])
store.Set(serviceList[1])
store.Set(serviceList[2])
store.Set(serviceList[0])
store.Set(serviceList[1])
result, _ := store.Delete(nil)
assert.Nil(result, "nil service should return nil")
result, _ = store.Delete(Service{
Name: "my-cool-service-one",
Namespace: "foo",
Labels: Labels{},
})
assert.Equal(serviceList[0], result, "delete should return deleted service")
result, _ = store.Delete(Service{
Name: "my-cool-service-one",
Namespace: "foo",
Labels: Labels{},
})
assert.Nil(result, "service should not exist")
assert.Equal(0, len(store.serviceMap["foo"]), "length not equal")
assert.Equal(1, len(store.serviceMap), "length not equal")
assert.Equal(2, len(store.serviceMap["bar"]), "length not equal")
result, _ = store.Delete(Service{
Name: "my-cool-service-two",
Namespace: "bar",
Labels: Labels{},
})
assert.Equal(serviceList[1], result, "delete should return deleted service")
assert.Equal(1, len(store.serviceMap), "store should be empty")
result, _ = store.Delete(Service{
Name: "my-cool-service-two",
Namespace: "bar",
Labels: Labels{},
})
assert.Nil(result, "deleted service should return nil")
}
func getTestServiceList() services {
return services{
Service{
Name: "my-cool-service-one",
Namespace: "foo",
Labels: Labels{
Label{
Name: "release",
Value: "production",
},
Label{
Name: "name-two",
Value: "value-two",
},
},
},
Service{
Name: "my-cool-service-two",
Namespace: "bar",
Labels: Labels{
Label{
Name: "name-prime-one",
Value: "value-one",
},
Label{
Name: "name-prime-two",
Value: "value-two",
},
},
},
Service{
Name: "my-cool-service-three",
Namespace: "bar",
Labels: Labels{
Label{
Name: "name-prime-one",
Value: "value-one",
},
Label{
Name: "name-prime-two",
Value: "value-two",
},
},
},
}
}
|
PhysShell/inexplicable_engine
|
inex/render/core/sources/pch.h
|
<filename>inex/render/core/sources/pch.h
////////////////////////////////////////////////////////////////////////////
// Created : 27.12.2018
// Author : <NAME>
////////////////////////////////////////////////////////////////////////////
#ifndef PCH_H_INCLUDED
# define PCH_H_INCLUDED
# include <inex/extensions.h>
#endif // #ifndef PCH_H_INCLUDED
|
reinteractive/nsw-state-library-amplify
|
app/policies/transcription_convention_policy.rb
|
class TranscriptionConventionPolicy < ApplicationPolicy
attr_reader :user, :csope
def initialize(user, scope)
@user = user
@csope = scope
end
def index?
admin_or_content_editor?
end
def new?
admin_or_content_editor?
end
def create?
admin_or_content_editor?
end
def edit?
admin_or_content_editor?
end
def update?
admin_or_content_editor?
end
def destroy?
@user.admin?
end
class Scope < Scope
def resolve
if @user.admin?
TranscriptionConvention.all
else
TranscriptionConvention.where(institution_id: @user.institution_id).
order_asc
end
end
end
end
|
Mathtician/vzome
|
core/src/main/java/com/vzome/core/edits/SelectManifestation.java
|
<filename>core/src/main/java/com/vzome/core/edits/SelectManifestation.java
package com.vzome.core.edits;
import java.util.Map;
import org.w3c.dom.Element;
import com.vzome.core.commands.AttributeMap;
import com.vzome.core.commands.XmlSaveFormat;
import com.vzome.core.construction.Construction;
import com.vzome.core.construction.Point;
import com.vzome.core.construction.Polygon;
import com.vzome.core.construction.Segment;
import com.vzome.core.editor.api.ChangeSelection;
import com.vzome.core.editor.api.EditorModel;
import com.vzome.core.model.Manifestation;
import com.vzome.core.model.RealizedModel;
import com.vzome.xml.DomUtils;
public class SelectManifestation extends ChangeSelection
{
private Manifestation mManifestation;
private Construction construction; // just for save
private final RealizedModel mRealized;
private boolean mReplace;
public SelectManifestation( EditorModel editor )
{
super( editor .getSelection() );
this.mRealized = editor .getRealizedModel();
}
@Override
protected boolean groupingAware()
{
return true;
}
/**
* Used by CommandEdit.
* @param editor
* @param m
*/
public SelectManifestation( EditorModel editor, Manifestation m )
{
this( editor );
this .mManifestation = m;
if ( this.mManifestation != null )
{
// must record the construction for save, because if this gets undone, there's no
// guarantee that the manifestation will have any constructions!
construction = this.mManifestation .toConstruction();
}
}
public void configure( Map<String, Object> props )
{
String mode = (String) props .get( "mode" );
this.mReplace = "replace" .equals( mode );
this.mManifestation = (Manifestation) props .get( "picked" );
if ( this.mManifestation != null )
{
// must record the construction for save, because if this gets undone, there's no
// guarantee that the manifestation will have any constructions!
construction = this.mManifestation .toConstruction();
}
}
@Override
public void perform()
{
if ( mReplace ) {
for (Manifestation man : mSelection) {
unselect( man, true );
}
select( mManifestation );
}
else if ( mSelection .manifestationSelected( mManifestation ) )
unselect( mManifestation );
else
select( mManifestation );
redo();
}
@Override
protected void getXmlAttributes( Element result )
{
if ( construction instanceof Point )
XmlSaveFormat .serializePoint( result, "point", (Point) construction );
else if ( construction instanceof Segment )
XmlSaveFormat .serializeSegment( result, "startSegment", "endSegment", (Segment) construction );
else if ( construction instanceof Polygon )
XmlSaveFormat .serializePolygon( result, "polygonVertex", (Polygon) construction );
if ( mReplace )
DomUtils .addAttribute( result, "replace", "true" );
}
@Override
public void setXmlAttributes( Element xml, XmlSaveFormat format )
{
if ( format .rationalVectors() )
{
construction = format .parsePoint( xml, "point" );
if ( construction == null )
construction = format .parseSegment( xml, "startSegment", "endSegment" );
if ( construction == null )
{
Element kid = DomUtils .getFirstChildElement( xml, "polygon" );
if ( kid != null ) // the interim 4.0.0 format (3.0 alpha 5 and before?)
construction = format .parsePolygon( kid, "vertex" );
else
construction = format .parsePolygon( xml, "polygonVertex" );
}
}
else
{
AttributeMap attrs = format .loadCommandAttributes( xml );
construction = (Construction) attrs .get( "manifestation" );
Boolean replaceVal = (Boolean) attrs .get( "replace" );
if ( replaceVal != null && replaceVal )
mReplace = true;
}
mManifestation = mRealized .getManifestation( construction );
// accommodate old bug that did not distinguish polygon vertex orders.
// This is acceptable on the basis that only a bug would result in a null manifestation
if ( mManifestation == null && format .rationalVectors() && construction instanceof Polygon )
{
construction = format .parsePolygonReversed( xml, "polygonVertex" );
mManifestation = mRealized .getManifestation( construction );
if ( mManifestation != null )
logBugAccommodation( "reverse-oriented polygon" );
}
}
@Override
protected String getXmlElementName()
{
return "SelectManifestation";
}
}
|
fspace/go-playground
|
examples/constants/main.go
|
<gh_stars>1-10
package main
import "fmt"
const MAX_Xx = 100 // integer
const MAX_Xx2 = 20.99 // float
const EVENT_USER_ADDED = "user-added" // string
const STATUS_ON = true // boolean
const STATUS_OFF = false
// const RGBS = [...]int{255} // wrong!
const PiApprox = 3.14
//var PiInt int = PiApprox // 3, converted to integer
//var Pi float64 = PiApprox // is a float
//
//type MyString string
//
//const Greeting = "Hello!"
//
//var s1 string = Greeting // is a string
//var s2 MyString = Greeting // string is converted to MyString
const a int16 = 27
func main() {
constDemo()
shadow()
typeInfer() // 编译器类型推断
iotaDemo()
iotaDemo2()
iotaDemo3()
iotaDemo4()
iotaDemo5()
}
func constDemo() {
const myConst int = 42
fmt.Printf("%v, %T\n", myConst, myConst)
}
// 外部同名常量被遮盖
func shadow() {
const a int16 = 3
fmt.Printf("%v, %T\n", a, a)
}
func typeInfer() {
const a = 42 // a 类型受后面运算类型影响!
var b int16 = 27
fmt.Printf("%v, %T\n", a+b, a+b)
}
const n = iota // 常量 数字型计数器
func iotaDemo() {
fmt.Printf("%v, %T\n", n, n)
}
const (
c1 = iota
c2 = iota
c3 // 编译器推导
c4 // 编译器推导
)
const (
STATUS_A = iota
STATUS_B = iota
)
func iotaDemo2() {
fmt.Println("iota-demo2 ===============================")
fmt.Printf("%v, %T\n ", c1, c1)
fmt.Printf("%v, %T\n ", c2, c2)
fmt.Printf("%v, %T\n ", c3, c3)
fmt.Printf("%v, %T\n ", c4, c4)
// 另一个常量块
fmt.Printf("%v, %T\n ", STATUS_A, STATUS_A)
fmt.Printf("%v, %T\n ", STATUS_B, STATUS_B)
}
const (
_ = iota + 5
catSpecialist
dogSpecialist
snakeSpecialist
)
func iotaDemo3() {
fmt.Printf("%v\n", catSpecialist)
}
const (
_ = iota // 忽略第一个0值 通过赋值给一个下划线
KB = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
func iotaDemo4() {
fileSize := 400000000.
fmt.Printf("%.2f GB", fileSize/GB)
}
const (
isAdmin = 1 << iota
isHeadquarters
canSeeFinancials
canSeeAfrica
canSeeAsia
canSeeEurope
canSeeNorthAmerica
canSeeSouthAmerica
)
func iotaDemo5() {
var roles byte = isAdmin | canSeeFinancials | canSeeEurope
fmt.Printf("\n %b\n", roles)
fmt.Printf("IS Admin? %v \n", isAdmin&roles == isAdmin)
fmt.Printf("IS HQ? %v \n", isHeadquarters&roles == isHeadquarters)
}
|
salviof/intERPRestful
|
src/test/java/br/org/coletivoJava/fw/erp/implementacao/erpintegracao/teste/FabDadosIniciaisTesteIntegracao.java
|
<reponame>salviof/intERPRestful
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.org.coletivoJava.fw.erp.implementacao.erpintegracao.teste;
import br.org.coletivoJava.fw.erp.implementacao.erpintegracao.model.FabGrupoTestesIntegracao;
import com.super_bits.modulos.SBAcessosModel.model.UsuarioSB;
import com.super_bits.modulosSB.Persistencia.fabrica.ItfFabricaComPersistencia;
import com.super_bits.modulosSB.SBCore.modulos.objetos.registro.Interfaces.basico.ItfGrupoUsuario;
/**
*
* @author sfurbino
*/
public enum FabDadosIniciaisTesteIntegracao implements ItfFabricaComPersistencia {
// GRUPO_TESTE,
USUARIO_SALVIO;
// MODULO_TESTE_INTEGRACAO;
@Override
public Object getRegistro() {
switch (this) {
// case MODULO_TESTE_INTEGRACAO:
// ModuloAcaoSistema nonvomodulo = new ModuloAcaoSistema();
// nonvomodulo.setId(1);
// nonvomodulo.setDescricao("teste");
// nonvomodulo.setNome("teste");
// return nonvomodulo;
// case GRUPO_TESTE:
// GrupoUsuarioSB grupo = new GrupoUsuarioSB();
// grupo.setId(1);
// return grupo;
case USUARIO_SALVIO:
UsuarioSB usuario = new UsuarioSB();
usuario.setNome("Salvio");
usuario.setId(1);
usuario.setGrupo((ItfGrupoUsuario) FabGrupoTestesIntegracao.GRUPO_TESTE.getRegistro());
usuario.setEmail("<EMAIL>");
usuario.setSenha("<PASSWORD>");
return usuario;
default:
throw new AssertionError(this.name());
}
}
}
|
littleRich/AutoInteraction-Library
|
Demo/src/main/java/silence/com/cn/a310application/qqanalyst/QQSimulateBusiness.java
|
package silence.com.cn.a310application.qqanalyst;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import silence.com.cn.a310application.appanalyst.AnalystBusiness;
import silence.com.cn.a310application.appanalyst.AnalystServiceHandler;
import silence.com.cn.a310application.appanalyst.GpsMocker;
import silence.com.cn.a310application.appanalyst.Log;
import silence.com.cn.a310application.appanalyst.MyException;
import silence.com.cn.a310application.appanalyst.ToastDuration;
import silence.com.cn.a310application.appanalyst.UiTree;
public class QQSimulateBusiness extends AnalystBusiness {
public static final int RECONNECT_SERVER_DELAY = 5 * 1000;
public static final int SUBMIT_WXPERSON_TIMEOUT = 10 * 1000;
public static final int LOCATING_TIMEOUT = 10 * 1000;
private static final java.lang.String TAG = "QQSimulateBusiness";
private final Handler mMainHandler = new Handler();
// private final DiskFiles mDiskFiles;
private Thread mNewGpsThread[] = new Thread[]{null};
// private WxTask mWxTask;
private ClipboardManager.OnPrimaryClipChangedListener mPrimaryClipChangedListener;
public QQSimulateBusiness(@NonNull AnalystServiceHandler serviceHandler) throws MyException {
super(serviceHandler);
// mDiskFiles = new DiskFiles(new File(Environment.getExternalStorageDirectory(), "tencent" + File.separator +
// "MicroMsg" + File.separator + "WeiXin"));
}
@Override
public void handleUiEvent(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
Log.i("QQSimulateBusiness.handleUiEvent # keepingAlive=" + (keepingAlive ? "true" : "false"));
FormPage formPage = FormPage.valueOf(uiTree.getFoundFormPage());
if (null == formPage) {
return;
}
switch (formPage) {
case QQ_MainActivity_Message:
handle_QQMainActivity_Message(uiTree, keepingAlive);
break;
}
}
private void handle_QQMainActivity_Message(UiTree uiTree, boolean keepingAlive) {
try {
uiTree.getNode("动态").click();
Log.d("点击了动态页面==============");
} catch (MyException e) {
e.printStackTrace();
}
}
public Context getContext() {
return getServiceHandler().getContext();
}
public GpsMocker getGpsMocker() {
return getServiceHandler().getGpsMocker();
}
private void readyClipboard(ClipboardManager.OnPrimaryClipChangedListener listener) {
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
if (null != mPrimaryClipChangedListener) {
clipboardManager.removePrimaryClipChangedListener(mPrimaryClipChangedListener);
}
mPrimaryClipChangedListener = listener;
clipboardManager.addPrimaryClipChangedListener(mPrimaryClipChangedListener);
}
private void releaseClipboard() {
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.removePrimaryClipChangedListener(mPrimaryClipChangedListener);
mPrimaryClipChangedListener = null;
}
public void requireBack(@NonNull UiTree uiTree) {
try {
uiTree.getNode("返回").click();
} catch (MyException e) {
getServiceHandler().requireBack();
}
}
private void submitGlobalException(final String message) {
// final Config config = new Config();
// config.load(getContext());
/* new Thread(new Runnable() {
@Override
public void run() {
String url = "http://" + config.getAppServerUrl() + Url.SubmitGlobalException;
try {
Connection connection = Jsoup.connect(url);
connection.ignoreContentType(true); connection.data("content", message);
connection.data("pointId", "");
connection.data("type", "1");
connection.post();
} catch (Exception e) {
Log.e(new MyException("提交异常信息失败", new MyException("连接URL: " + url, e)));
}
}
}).start();*/
}
private void submitTaskException(final int taskId, final String message) {
/* final Config config = new Config();
config.load(getContext());
new Thread(new Runnable() {
@Override
public void run() {
String url = "http://" + config.getAppServerUrl() + Url.SubmitTaskException;
try {
Connection connection = Jsoup.connect(url);
connection.ignoreContentType(true);
connection.data("content", message);
connection.data("pointId", "" + taskId);
connection.data("type", "2");
connection.post();
} catch (Exception e) {
Log.e(new MyException("提交异常信息失败", new MyException("连接URL: " + url, e)));
}
}
}).start();*/
}
private void submitException(@Nullable Integer taskId, final String message) {
if (null == taskId) {
submitGlobalException(message);
} else {
submitTaskException(taskId, message);
}
}
private void handle_LauncherUI_Login(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
Log.e("界面异常 - 当前为登录界面", getContext(), ToastDuration.LENGTH_LONG);
submitGlobalException("当前为登录界面,需要人工登录");
}
/*private void handle_LauncherUI_Main(@NonNull final UiTree uiTree, final boolean keepingAlive) throws MyException {
if (!getGpsMocker().isWorking()) {
synchronized (mNewGpsThread) {
if (null == mNewGpsThread[0]) {
mNewGpsThread[0] = new Thread(new Runnable() {
@Override
public void run() {
final int id;
final int areaId;
final Gps mockGps;
final WxScope wxScope;
try {
if (Macro.RealGps || !Macro.Network) {
mockGps = Macro.MockGps;
id = 0;
areaId = 0;
// wxScope = WxScope.forPersonCount(10);
} else {
try {
JSONObject jsonObject;
String url = null;
try {
Config config = new Config();
config.load(getContext());
url = "http://" + config.getAppServerUrl() + Url.GetTask + config
.getAppAreaConfig();
Connection connection = Jsoup.connect(url);
connection.ignoreContentType(true);
Document document = connection.get();
SilenceLog.e(document.toString());
jsonObject = new JSONObject(document.body().text());
} catch (Exception e) {
throw new MyException("连接服务器失败", new MyException("连接URL: " + url, e));
}
String gpsText;
int amount;
long intervalTime;//秒
String type;
try {
JSONArray jsonArray = jsonObject.getJSONArray("data");
JSONObject itemObject = jsonArray.getJSONObject(0);
id = itemObject.getInt("id");
areaId = itemObject.getInt("area_id");
gpsText = itemObject.getString("position");
amount = itemObject.getInt("amount");
intervalTime = itemObject.getLong("interval_time");
type = itemObject.getString("type");
} catch (Exception e) {
throw new MyException("解析服务器数据异常", new MyException("连接URL: " + url, e));
}
try {
String[] texts = gpsText.split(":");
mockGps = new Gps(Float.parseFloat(texts[2]), Float.parseFloat(texts[1]));
} catch (Exception e) {
throw new MyException("解析服务器GPS数据异常", new MyException("连接URL: " + url, e));
}
if ("amount".equals(type)) {
wxScope = WxScope.forPersonCount(amount);
} else if ("interval_time".equals(type)) {
wxScope = WxScope.forTaskTime(intervalTime * 1000);
} else {
throw new MyException("解析服务器工作方式异常", new MyException("连接URL: " + url));
}
} catch (Exception e) {
Log.e(e, getContext(), ToastDuration.LENGTH_SHORT);
mMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
getServiceHandler().requirePost();
}
}, RECONNECT_SERVER_DELAY);
return;
}
}
} finally {
synchronized (mNewGpsThread) {
mNewGpsThread[0] = null;
}
}
mMainHandler.post(new Runnable() {
@Override
public void run() {
getGpsMocker().start(getContext(), mockGps);
mWxTask = new WxTask(id, areaId, wxScope);
getServiceHandler().requirePost();
}
});
}
});
mNewGpsThread[0].start();
}
}
} else {
uiTree.getNode("发现").click();
uiTree.getNode("附近的人").click();
}
}*/
/* private void handle_LoginHistoryUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
//TODO Zhukun 自动登录
final Config config = new Config();
config.load(getContext());
uiTree.getNode("输入密码").setEditText(QQApplication.getContext(), "");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
uiTree.getNode("输入密码").setEditText(QQApplication.getContext(), config.getWeChatPwd());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
uiTree.getNode("登录").click();
submitGlobalException("输入密码" + config.getWeChatPwd());
Log.e("输入密码" + config.getWeChatPwd(), getContext(), ToastDuration.LENGTH_LONG);
}*/
/**
* 帐号或密码错误,请重新填写
*
* @param uiTree uiTree
* @param keepingAlive keepingAlive
* @throws MyException
*/
/* private void handle_LoginErro_1(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("确定").click();
Log.e("帐号或密码错误,请重新填写");
}*/
/**
* 密码错误,找回或重置密码?
*
* @param uiTree uiTree
* @param keepingAlive keepingAlive
* @throws MyException
*/
/* private void handle_LoginErro_2(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("取消").click();
Log.e("密码错误,找回或重置密码?");
}*/
/* private void handle_NearbyFriendsIntroUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (!getGpsMocker().isWorking()) {
requireBack(uiTree);
return;
}
uiTree.getNode("开始查看").click();
}*/
/* private void handle_NearbyFriendShowSayHiUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (!getGpsMocker().isWorking()) {
requireBack(uiTree);
return;
}
uiTree.getNode("开始查看").click();
}*/
/* private void handle_BaseP_0(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (!getGpsMocker().isWorking()) {
requireBack(uiTree);
return;
}
if (null == mWxTask) {
getGpsMocker().stop();
requireBack(uiTree);
return;
}
if (mWxTask.mLocatingStartTime <= 0) {
//第一次进入该页面
mWxTask.mLocatingStartTime = System.currentTimeMillis();
return;
}
if (System.currentTimeMillis() >= mWxTask.mLocatingStartTime + LOCATING_TIMEOUT) {
mWxTask.mLocatingStartTime = 0;
submitTaskException(mWxTask.getId(), "定位超时");
requireBack(uiTree);
return;
}
}*/
/*
private void handle_BaseH_0(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("下次不提示").click();
uiTree.getNode("确定").click();
}
*/
/* private void handle_BaseH_1(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("确定").click();
}
*/
/* private void handle_BaseH_2(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
Log.e("定位异常", getContext(), ToastDuration.LENGTH_LONG);
submitException(null == mWxTask ? null : mWxTask.getId(), "定位失败");
getGpsMocker().stop();
requireBack(uiTree);
}*/
/* private void handle_BaseH_3(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("确定").click();
}*/
/* private void handle_BaseH_4(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("确定").click();
}*/
/* private void handle_BaseH_5(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("关闭").click();
}*/
private void handle_BaseH_6(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("取消").click();
}
private void handle_BaseH_7(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("取消").click();
}
private void handle_BaseH_8(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("取消").click();
}
private void handle_BaseH_9(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
uiTree.getNode("确定").click();
}
/* private void handle_NearbyFriendsUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (!getGpsMocker().isWorking()) {
requireBack(uiTree);
return;
}
if (null == mWxTask) {
getGpsMocker().stop();
requireBack(uiTree);
return;
}
if (null == mWxTask.person()) {
uiTree.getNode("更多").click();
return;
}
UiNode listNode = uiTree.getNode("列表");
if (mWxTask.mPersonIndex >= listNode.getChildCount()) {
//需要翻页
int count = listNode.getChildCount();
if (count > 0) {
UiNode lastItemNode = listNode.getChild(count - 1);
WxPersonTemp personTemp = new WxPersonTemp();
try {
UiNode node = lastItemNode.getChild(0).getChild(1).getChild(0).getChild(0);
personTemp.mNickname = StringUtil.toNullable(node.getText());
} catch (NullPointerException e) {
//忽略异常
}
try {
UiNode node = lastItemNode.getChild(0).getChild(1).getChild(0).getChild(1);
personTemp.mSex = StringUtil.toNullable(node.getDescription());
} catch (NullPointerException e) {
//忽略异常
}
try {
UiNode node = lastItemNode.getChild(0).getChild(1).getChild(1).getChild(0);
personTemp.mDistance = StringUtil.toNullable(node.getText());
} catch (NullPointerException e) {
//忽略异常
}
try {
UiNode node = lastItemNode.getChild(0).getChild(2).getChild(0);
personTemp.mIdiograph = StringUtil.toNullable(node.getText());
} catch (NullPointerException e) {
//忽略异常
}
if (null != mWxTask.mPersonTemp) {
if (personTemp.equals(mWxTask.mPersonTemp)) {
Log.i("遍历结束", getContext(), ToastDuration.LENGTH_SHORT);
getGpsMocker().stop();
getServiceHandler().requirePost();
return;
}
}
mWxTask.mPersonTemp = personTemp;
} else {
mWxTask.mPersonTemp = null;
}
mWxTask.mPersonIndex = 0;
listNode.scrollForward();
getServiceHandler().requirePost();
} else {
UiNode itemNode = listNode.getChild(mWxTask.mPersonIndex);
if (0 == mWxTask.mPersonIndex) {
if (0 == itemNode.getChildCount()) {
//首页第一个为空,跳过
mWxTask.mPersonIndex++;
handle_NearbyFriendsUI(uiTree, keepingAlive);
return;
} else {
Rect listViewBounds = new Rect();
listNode.getBoundsInScreen(listViewBounds);
Rect itemBounds = new Rect();
itemNode.getBoundsInScreen(itemBounds);
if (itemBounds.top < listViewBounds.top) {
//第一个为上一页已访问的,跳过
mWxTask.mPersonIndex++;
handle_NearbyFriendsUI(uiTree, keepingAlive);
return;
}
}
}
mWxTask.mPersonIndex++;
try {
mWxTask.personNew();
} catch (WxTask.TaskEndException e) {
Log.i("当前任务结束", getContext(), ToastDuration.LENGTH_SHORT);
getGpsMocker().stop();
requireBack(uiTree);
return;
} catch (MyException e) {
Log.e(new MyException("获取下个Person异常", e), getContext(), ToastDuration.LENGTH_SHORT);
getGpsMocker().stop();
requireBack(uiTree);
return;
}
itemNode.click();
}
}
*/
private void handle_NearbyFriendsUI_Nobody(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (getGpsMocker().isWorking()) {
Log.e("没有附近的人", getContext(), ToastDuration.LENGTH_LONG);
getGpsMocker().stop();
}
requireBack(uiTree);
}
/* private void handle_NearbyFriendsUI_NoLocation(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (getGpsMocker().isWorking()) {
Log.e("不能获取位置", getContext(), ToastDuration.LENGTH_LONG);
submitException(null == mWxTask ? null : mWxTask.getId(), "不能获取位置");
getGpsMocker().stop();
}
requireBack(uiTree);
}*/
/* private void handle_NearbyFriendsUIMenu(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null != mWxTask && null == mWxTask.person()) {
mWxTask.personReset();
uiTree.getNode("清除位置并退出").click();
} else {
requireBack(uiTree);
}
}*/
/*private void handle_ContactInfoUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case PersonInfo:
handle_ContactInfoUI_CasePersonInfo(uiTree, keepingAlive);
break;
case PersonImage:
handle_ContactInfoUI_CasePersonImage(uiTree, keepingAlive);
break;
case Messages:
handle_ContactInfoUI_CaseMessages(uiTree, keepingAlive);
break;
case Finish:
case Finished:
handle_ContactInfoUI_CaseFinish(uiTree, keepingAlive);
break;
default:
Log.e("QQSimulateBusiness.handle_ContactInfoUI # 错误步骤(" + mWxTask.person().step().name() + "),返回",
getContext(), ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}*/
/*private void handle_ContactInfoUI_CasePersonInfo(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.PersonInfo != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
String nickname = StringUtil.toNb(uiTree.getNode("昵称").getText());
if (null != nickname) {
// 昵称总是会多一个空格,这里去掉
if (nickname.endsWith(" ")) {
nickname = nickname.substring(0, nickname.length() - 1);
}
}
mWxTask.person().setNickname(nickname);
String sex = StringUtil.toNb(uiTree.getNode("性别").getDescription());
mWxTask.person().setSex(sex);
String location = StringUtil.toNb(uiTree.getNode("位置").getText());
mWxTask.person().setLocation(location);
UiNode listNode = uiTree.getNode("列表");
for (int i = 2; i < listNode.getChildCount(); i++) {
try {
UiNode itemNode = listNode.getChild(i);
UiNode labelNode = itemNode.getChild(0).getChild(0).getChild(0).getChild(0);
String label = StringUtil.toEb(labelNode.getText());
if (label.equals("地区")) {
UiNode valueNode = itemNode.getChild(0).getChild(0).getChild(1).getChild(0).getChild(0);
mWxTask.person().setRegion(StringUtil.toNb(valueNode.getText()));
} else if (label.equals("个性签名")) {
UiNode valueNode = itemNode.getChild(0).getChild(0).getChild(1).getChild(0).getChild(0);
mWxTask.person().setIdiograph(StringUtil.toNb(valueNode.getText()));
}
} catch (NullPointerException e) {
//继续遍历
}
}
mWxTask.person().nextStep(WxPerson.Step.PersonImage);
handle_ContactInfoUI_CasePersonImage(uiTree, keepingAlive);
}*/
/*private void handle_ContactInfoUI_CasePersonImage(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.PersonImage != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
uiTree.getNode("头像").click();
}*/
/*private void handle_ContactInfoUIImage(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case PersonImage: {
UiNode node = uiTree.getNode("图片");
Rect bounds = new Rect();
node.getBoundsInScreen(bounds);
mWxTask.person().nextStep(WxPerson.Step.PersonImageSaving);
mWxTask.person().mImageSaveCount = 0;
getServiceHandler().requireMockLongClick(new PointXY(bounds.centerX(), bounds.centerY()));
getServiceHandler().requirePost();
}
break;
case PersonImageSaving:
if (mWxTask.person().mImageSaveCount > 3) {
Log.e("获取头像失败", getContext(), ToastDuration.LENGTH_SHORT);
mWxTask.person().nextStep(WxPerson.Step.PersonImageSaved);
mWxTask.person().nextStep();
requireBack(uiTree);
} else {
mWxTask.person().mImageSaveCount++;
getServiceHandler().requirePost();
}
break;
case PersonImageSaved:
mWxTask.person().setPersonImage(mDiskFiles.nextFreshFileName());
mWxTask.person().nextStep();
requireBack(uiTree);
break;
default:
Log.e("QQSimulateBusiness.handle_ContactInfoUIImage # 错误步骤(" + mWxTask.person().step().name() + "),返回",
getContext(), ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}*/
/*private void handle_BaseK_ImageSaving(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.PersonImageSaving != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
mDiskFiles.scanFiles();
mWxTask.person().nextStep(WxPerson.Step.PersonImageSaved);
uiTree.getNode("保存到手机").click();
}*/
/* private void handle_ContactInfoUI_CaseMessages(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.Messages != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
UiNode listNode = uiTree.getNode("列表");
UiNode photosNode = null;
for (int i = 2; i < listNode.getChildCount(); i++) {
try {
UiNode itemNode = listNode.getChild(i);
String description = StringUtil.toEb(itemNode.getDescription());
if (description.startsWith("个人相册")) {
photosNode = itemNode;
break;
}
} catch (Exception e) {
//继续遍历
}
}
if (null == photosNode) {
mWxTask.person().nextStep(WxPerson.Step.Finish);
handle_ContactInfoUI_CaseFinish(uiTree, keepingAlive);
} else {
photosNode.click();
}
}*/
/*private void handle_ContactInfoUI_CaseFinish(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case Finish: {
if (null != mWxTask.person().mFinishTime) {
//判断超时
if (System.currentTimeMillis() >= mWxTask.person().mFinishTime + SUBMIT_WXPERSON_TIMEOUT) {
mWxTask.person().nextStep(WxPerson.Step.Finished);
getServiceHandler().requirePost();
}
} else {
final WxPerson wxPerson = mWxTask.person();
wxPerson.mFinishTime = System.currentTimeMillis();
final Config config = new Config();
config.load(getContext());
new Thread(new Runnable() {
@Override
public void run() {
try {
wxPerson.submit(getContext(), config);
Log.i("提交完成");
} catch (MyException e) {
Log.e(e, getContext(), ToastDuration.LENGTH_SHORT);
}
mMainHandler.post(new Runnable() {
@Override
public void run() {
wxPerson.deleteImageFiles();
wxPerson.nextStep(WxPerson.Step.Finished);
getServiceHandler().requirePost();
}
});
}
}).start();
}
}
break;
case Finished:
requireBack(uiTree);
break;
default:
Log.e("QQSimulateBusiness.handle_ContactInfoUI_CaseFinish # 错误步骤(" + mWxTask.person().step().name() + ")" +
",返回", getContext(), ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}*/
/*private void handle_SnsUserUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.Messages != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
UiNode listNode = uiTree.getNode("列表");
List<WxMessage> wxMessages = mWxTask.person().getMessages();
String md = null;
for (int i = 1; i < listNode.getChildCount(); i++) {
if (i - 1 >= wxMessages.size()) {
wxMessages.add(null);
}
WxMessage wxMessage = wxMessages.get(i - 1);
UiNode itemNode = listNode.getChild(i);
try {
UiNode dateMdNode = itemNode.getChild(2).getChild(0).getChild(0).getChild(0);
UiNode dateDNode = dateMdNode.getChild(0);
if (StringUtil.compareNb(dateDNode.getClassName(), "android.widget.TextView")) {
String d = StringUtil.toEb(dateDNode.getText());
md = DateUtil.toMd(d, null);
if (null == md) {
UiNode dateMNode = dateMdNode.getChild(1);
String m = StringUtil.toEb(dateMNode.getText());
md = m + d;
}
}
} catch (NullPointerException e) {
//忽略异常
}
if (null == wxMessage) {
try {
if (StringUtil.compareNb(itemNode.getChild(0).getChild(0).getChild(1).getText(), "非朋友最多显示十张照片")) {
//结束
break;
}
} catch (NullPointerException e) {
//忽略异常
}
try {
UiNode node = itemNode;
if (StringUtil.compareNb("android.widget.LinearLayout", node.getClassName()) && 1 == node
.getChildCount()) {
node = itemNode.getChild(0);
if (StringUtil.compareNb("android.widget.LinearLayout", node.getClassName()) && 1 == node
.getChildCount()) {
node = node.getChild(0);
if (StringUtil.compareNb("android.widget.LinearLayout", node.getClassName()) && 1 == node
.getChildCount()) {
node = node.getChild(0);
if (StringUtil.compareNb("android.widget.ImageView", node.getClassName()) && 0 ==
node.getChildCount()) {
//结束行
break;
}
}
}
}
} catch (NullPointerException e) {
//忽略异常
}
//由于可点的位置在itemNode内部,所以使用最后一个子节点来判断
UiNode childNode = null;
for (int n = 0; n < itemNode.getChildCount(); n++) {
UiNode node = null;
try {
node = itemNode.getChild(n).getChild(0);
} catch (NullPointerException e) {
//忽略异常
}
try {
node = itemNode.getChild(n).getChild(1);
} catch (NullPointerException e) {
//忽略异常
}
if (null != node) {
childNode = node;
}
}
if (null == childNode) {
//异常,结束
break;
}
//点击进入具体的消息页面
Rect listBounds = new Rect();
listNode.getBoundsInScreen(listBounds);
Rect childBounds = new Rect();
childNode.getBoundsInScreen(childBounds);
if (childBounds.top >= listBounds.bottom) {
//该项已经在显示界面之外,由于目前没有滚屏机制,所以忽略之后的item
break;
}
PointXY point = new PointXY(childBounds.centerX(), childBounds.centerY());
if (point.mY >= listBounds.bottom) {
point.mY = listBounds.bottom - 1;
}
getServiceHandler().requireMockClick(point);
return;
} else {
wxMessage.setDateMd(md);
}
}
//遍历结束
if (!wxMessages.isEmpty()) {
//去掉最后一条,最后一条为结束图标
if (null == wxMessages.get(wxMessages.size() - 1)) {
wxMessages.remove(wxMessages.size() - 1);
}
}
mWxTask.person().nextStep(WxPerson.Step.Finish);
requireBack(uiTree);
}
*/
/*private void handle_SnsGalleryUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case Messages: {
List<WxMessage> wxMessages = mWxTask.person().getMessages();
if (wxMessages.isEmpty()) {
requireBack(uiTree);
return;
}
WxMessage wxMessage = new WxMessage();
wxMessage.mGalleryPageIndex = 0;
wxMessage.mGalleryNoTitleClickCount = 0;
try {
wxMessage.setDescription(StringUtil.toNb(uiTree.getNode("描述").getText()));
} catch (MyException e) {
//忽略异常
}
wxMessage.setDateYmdhm(DateUtil.toYmdhm(StringUtil.toNb(uiTree.getNode("时间").getText())));
wxMessages.set(wxMessages.size() - 1, wxMessage);
mWxTask.person().nextStep(WxPerson.Step.MessageImageReading);
handle_SnsGalleryUI(uiTree, keepingAlive);
}
break;
case MessageImageReading: {
uiTree.getNode("更多").click();
}
break;
case MessageImageOneReadEnd: {
List<WxMessage> wxMessages = mWxTask.person().getMessages();
if (wxMessages.isEmpty()) {
requireBack(uiTree);
return;
}
WxMessage wxMessage = wxMessages.get(wxMessages.size() - 1);
if (null == wxMessage) {
requireBack(uiTree);
return;
}
wxMessage.getImages().add(mDiskFiles.nextFreshFileName());
UiNode pagingNode = null;
try {
pagingNode = uiTree.getNode("分页");
} catch (MyException e) {
//忽略异常
}
if (null != pagingNode) {
wxMessage.mGalleryPageIndex++;
String text = StringUtil.toEb(pagingNode.getText());
String separator = " / ";
int off = text.indexOf(separator);
int page = Integer.parseInt(text.substring(0, off));
if (page != wxMessage.mGalleryPageIndex) {
Log.e("当前页码不匹配,返回", getContext(), ToastDuration.LENGTH_SHORT);
mWxTask.person().nextStep(WxPerson.Step.Messages);
requireBack(uiTree);
}
int count = Integer.parseInt(text.substring(off + separator.length()));
if (page < count) {
UiNode galleryNode = uiTree.getNode("照片墙");
Rect bounds = new Rect();
galleryNode.getBoundsInScreen(bounds);
if (Math.abs(bounds.right - bounds.left) <= 2) {
throw new MyException("照片墙控件大小异常");
}
wxMessage.mGalleryNoTitleClickCount = 0;
mWxTask.person().nextStep(WxPerson.Step.MessageImageReading);
getServiceHandler().requireMockMove(new PointXY2XY(new PointXY(bounds.right - 1, bounds
.centerY()), new PointXY(bounds.left + 1, bounds.centerY())));
return;
} else {
mWxTask.person().nextStep(WxPerson.Step.Messages);
requireBack(uiTree);
}
} else {
mWxTask.person().nextStep(WxPerson.Step.Messages);
requireBack(uiTree);
}
}
break;
default:
Log.e("QQSimulateBusiness.handle_SnsGalleryUI # 错误步骤(" + mWxTask.person().step().name() + "),返回", getContext
(), ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}*/
/*private void handle_SnsGalleryUI_NoTitle(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.MessageImageReading != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
List<WxMessage> wxMessages = mWxTask.person().getMessages();
if (wxMessages.isEmpty()) {
requireBack(uiTree);
return;
}
WxMessage wxMessage = wxMessages.get(wxMessages.size() - 1);
if (null == wxMessage) {
requireBack(uiTree);
return;
}
if (wxMessage.mGalleryNoTitleClickCount >= 5) {
//点击多次无反应,则当前页面为“图片获取中”状态
requireBack(uiTree);
return;
}
wxMessage.mGalleryNoTitleClickCount++;
UiNode node = uiTree.getNode("照片墙");
Rect bounds = new Rect();
node.getBoundsInScreen(bounds);
getServiceHandler().requireMockClick(new PointXY(bounds.centerX(), bounds.centerY()));
getServiceHandler().requirePost();
}
private void handle_SnsGalleryUIMenu(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.MessageImageReading != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
mWxTask.person().nextStep(WxPerson.Step.MessageImageOneReadEnd);
mDiskFiles.scanFiles();
try {
uiTree.getNode("保存到手机").click();
} catch (MyException e) {
//当前为视频或其他
requireBack(uiTree);
}
}*/
/* private void handle_SnsCommentDetailUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case Messages: {
List<WxMessage> wxMessages = mWxTask.person().getMessages();
if (wxMessages.isEmpty()) {
requireBack(uiTree);
return;
}
final WxMessage wxMessage = new WxMessage();
try {
wxMessage.setTitle(StringUtil.toNb(uiTree.getNode("标题").getText()));
} catch (MyException e) {
//忽略异常
}
try {
wxMessage.setDescription(StringUtil.toNb(uiTree.getNode("描述").getText()));
} catch (MyException e) {
//忽略异常
}
try {
wxMessage.setSource(StringUtil.toNb(uiTree.getNode("源").getText()));
} catch (MyException e) {
//忽略异常
}
try {
wxMessage.setRegion(StringUtil.toNb(uiTree.getNode("地区").getText()));
} catch (MyException e) {
//忽略异常
}
try {
wxMessage.setDateYmdhm(DateUtil.toYmdhm(StringUtil.toNb(uiTree.getNode("时间").getText())));
} catch (MyException e) {
//忽略异常
}
try {
wxMessage.setTail(StringUtil.toNb(uiTree.getNode("尾注").getText()));
} catch (MyException e) {
//忽略异常
}
if (Macro.Debug) {
String text = "获取消息内容:";
text += "\n日期:" + wxMessage.getDateYmdhm();
text += "\n描述:" + wxMessage.getDescription();
text += "\n标题:" + wxMessage.getTitle();
text += "\n源:" + wxMessage.getSource();
text += "\n尾注:" + wxMessage.getTail();
text += "\n地区位置:" + wxMessage.getRegion();
Log.i(text);
}
wxMessages.set(wxMessages.size() - 1, wxMessage);
UiNode enterNode = null;
try {
enterNode = uiTree.getNode("进入");
} catch (MyException e) {
//忽略异常
}
if (null != enterNode) {
mWxTask.person().nextStep(WxPerson.Step.MessageWebReading);
readyClipboard(new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService
(Context.CLIPBOARD_SERVICE);
try {
wxMessage.setUrl(StringUtil.toNb(clipboardManager.getPrimaryClip().getItemAt(0)
.getText()));
if (Macro.Debug) {
Log.i("获取URL:" + wxMessage.getUrl());
}
} catch (Exception e) {
//忽略异常
}
releaseClipboard();
}
});
Rect bounds = new Rect();
enterNode.getBoundsInScreen(bounds);
getServiceHandler().requireMockClick(new PointXY(bounds.centerX(), bounds.centerY()));
getServiceHandler().requirePost();
} else {
requireBack(uiTree);
}
}
break;
case MessageWebReading: {
List<WxMessage> wxMessages = mWxTask.person().getMessages();
if (wxMessages.isEmpty()) {
requireBack(uiTree);
return;
}
WxMessage wxMessage = wxMessages.get(wxMessages.size() - 1);
if (null == wxMessage) {
requireBack(uiTree);
return;
}
if (wxMessage.mWebReadingCount > 3) {
Log.e("获取URL失败", getContext(), ToastDuration.LENGTH_SHORT);
mWxTask.person().nextStep(WxPerson.Step.Messages);
requireBack(uiTree);
} else {
wxMessage.mWebReadingCount++;
}
}
break;
case MessageWebReadEnd: {
releaseClipboard();
mWxTask.person().nextStep(WxPerson.Step.Messages);
requireBack(uiTree);
}
break;
default:
Log.e("QQSimulateBusiness.handle_SnsCommentDetailUI # 错误步骤(" + mWxTask.person().step().name() + "),返回",
getContext(), ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}*/
/*private void handle_WebViewUI(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
switch (mWxTask.person().step()) {
case MessageWebReading:
try {
uiTree.getNode("更多").click();
} catch (MyException e) {
mWxTask.person().nextStep(WxPerson.Step.MessageWebReadEnd);
requireBack(uiTree);
}
break;
case MessageWebReadEnd:
requireBack(uiTree);
break;
default:
Log.e("QQSimulateBusiness.handle_WebViewUI # 错误步骤(" + mWxTask.person().step().name() + "),返回", getContext(),
ToastDuration.LENGTH_SHORT);
requireBack(uiTree);
break;
}
}
*/
/*private void handle_WebViewUIMenu_Normal(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.MessageWebReading != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
mWxTask.person().nextStep(WxPerson.Step.MessageWebReadEnd);
uiTree.getNode("复制链接").click();
}*/
/*private void handle_WebViewUIMenu_Other(@NonNull UiTree uiTree, boolean keepingAlive) throws MyException {
if (null == mWxTask || null == mWxTask.person()) {
requireBack(uiTree);
return;
}
if (WxPerson.Step.MessageWebReading != mWxTask.person().step()) {
requireBack(uiTree);
return;
}
mWxTask.person().nextStep(WxPerson.Step.MessageWebReadEnd);
requireBack(uiTree);
}*/
}
|
AmandaRiu/TaggerApp
|
app/src/main/java/com/amandariu/tagger/demo/data/source/ITagsDataSource.java
|
package com.amandariu.tagger.demo.data.source;
import android.support.annotation.NonNull;
import com.amandariu.tagger.ITag;
import java.util.List;
/**
* Main entry point for accessing Tags data.
*/
public interface ITagsDataSource extends ISourceBase {
interface ISaveTagsCallback {
void onTagsSavedSuccess();
void onTagsSavedError(Exception e);
}
void saveTags(@NonNull List<? extends ITag> tags, @NonNull ISaveTagsCallback callback);
}
|
heyoni/opentrons
|
protocol-designer/src/file-data/selectors/commands.js
|
<filename>protocol-designer/src/file-data/selectors/commands.js<gh_stars>0
// @flow
import {createSelector} from 'reselect'
import isEmpty from 'lodash/isEmpty'
import last from 'lodash/last'
import reduce from 'lodash/reduce'
import type {BaseState, Selector} from '../../types'
import * as StepGeneration from '../../step-generation'
import {selectors as steplistSelectors} from '../../steplist/reducers'
import {equippedPipettes} from './pipettes'
import {selectors as labwareIngredSelectors} from '../../labware-ingred/reducers'
import type {IngredInstance} from '../../labware-ingred/types'
const all96Tips = reduce( // TODO Ian 2018-04-05 mapValues
StepGeneration.tiprackWellNamesFlat,
(acc: {[string]: boolean}, wellName: string) => ({...acc, [wellName]: true}),
{}
)
type LiquidState = $PropertyType<StepGeneration.RobotState, 'liquidState'>
type LabwareLiquidState = $PropertyType<LiquidState, 'labware'>
/** getLabwareLiquidState reshapes data from labwareIngreds.ingredLocations reducer
* to match RobotState.liquidState.labware's shape
*/
export const getLabwareLiquidState: Selector<LabwareLiquidState> = createSelector(
labwareIngredSelectors.getLabware,
labwareIngredSelectors.getIngredientLocations,
(labware, ingredLocs) => {
const allLabwareIds = Object.keys(labware)
type WellVolume = {volume: number}
function getAllIngredsForLabware (labwareId: string) {
return reduce(ingredLocs, (ingredAcc: {[wellName: string]: WellVolume}, ingredGroupData: IngredInstance, ingredGroupId: string) => {
return {
...ingredAcc,
...reduce(ingredGroupData[labwareId], (wellAcc, wellData: WellVolume, wellName: string) => ({
...wellAcc,
[wellName]: {
...ingredAcc[wellName],
[ingredGroupId]: wellData
}
}), {})
}
}, {})
}
return allLabwareIds.reduce((acc, labwareId) => ({
...acc,
[labwareId]: getAllIngredsForLabware(labwareId)
}), {})
}
)
export const getInitialRobotState: BaseState => StepGeneration.RobotState = createSelector(
equippedPipettes,
labwareIngredSelectors.getLabware,
getLabwareLiquidState,
(pipettes, labware, labwareLiquidState) => {
type TipState = $PropertyType<StepGeneration.RobotState, 'tipState'>
type TiprackTipState = $PropertyType<TipState, 'tipracks'>
const tipracks: TiprackTipState = reduce(
labware,
(acc: TiprackTipState, labwareData: StepGeneration.LabwareData, labwareId: string) => {
// TODO Ian 2018-05-18 have a more robust way of designating labware types
// as tiprack or not
if (labwareData.type && labwareData.type.startsWith('tiprack')) {
return {
...acc,
// TODO LATER Ian 2018-05-18 use shared-data wells instead of assuming 96 tips?
[labwareId]: {...all96Tips}
}
}
return acc
},
{})
type PipetteTipState = {[pipetteId: string]: boolean}
const pipetteTipState: PipetteTipState = reduce(
pipettes,
(acc: PipetteTipState, pipetteData: StepGeneration.PipetteData) =>
({
...acc,
[pipetteData.id]: false // start with no tips
}),
{})
const pipetteLiquidState = reduce(
pipettes,
(acc, pipetteData: StepGeneration.PipetteData, pipetteId: string) => ({
...acc,
[pipetteId]: (pipetteData.channels > 1)
? {'0': {}, '1': {}, '2': {}, '3': {}, '4': {}, '5': {}, '6': {}, '7': {}}
: {'0': {}}
}),
{})
return {
instruments: pipettes,
labware,
tipState: {
tipracks,
pipettes: pipetteTipState
},
liquidState: {
pipettes: pipetteLiquidState,
labware: labwareLiquidState
}
}
}
)
export type RobotStateTimeline = {
formErrors: {[string]: string},
timeline: Array<StepGeneration.CommandsAndRobotState>,
robotState: StepGeneration.RobotState,
timelineErrors?: ?Array<StepGeneration.CommandCreatorError>,
errorStepId?: number
}
// exposes errors and last valid robotState
export const robotStateTimeline: Selector<RobotStateTimeline> = createSelector(
steplistSelectors.validatedForms,
steplistSelectors.orderedSteps,
getInitialRobotState,
(forms, orderedSteps, initialRobotState) => {
const finalStepId = last(orderedSteps)
const result: RobotStateTimeline = orderedSteps.reduce((acc: RobotStateTimeline, stepId): RobotStateTimeline => {
if (!isEmpty(acc.formErrors)) {
// short-circut the reduce if there were errors with validating / processing the form
return acc
}
if (acc.timelineErrors) {
// short-circut the reduce if there were timeline errors
return acc
}
const form = forms[stepId]
if (stepId === 0) {
// The first stepId is the "initial deck setup" step.
// It doesn't have a form, it just sets up initialRobotState
return {
...acc,
timeline: [
...acc.timeline,
{
commands: [],
robotState: initialRobotState
}
]
}
}
// un-nest to make flow happy
const validatedForm = form.validatedForm
// put form errors into accumulator
if (!validatedForm) {
return {
...acc,
formErrors: form.errors
}
}
// finally, deal with valid step forms
let commandCreators = []
if (validatedForm.stepType === 'consolidate') {
commandCreators.push(StepGeneration.consolidate(validatedForm))
} else
if (validatedForm.stepType === 'transfer') {
commandCreators.push(StepGeneration.transfer(validatedForm))
} else
if (validatedForm.stepType === 'distribute') {
commandCreators.push(StepGeneration.distribute(validatedForm))
} else
if (validatedForm.stepType === 'pause') {
commandCreators.push(StepGeneration.delay(validatedForm))
} else
if (validatedForm.stepType === 'mix') {
commandCreators.push(StepGeneration.mix(validatedForm))
} else {
// TODO Ian 2018-05-08 use assert
console.warn(`StepType "${validatedForm.stepType}" not yet implemented`)
return {
...acc,
formErrors: {
...acc.formErrors,
'STEP NOT IMPLEMENTED': validatedForm.stepType
}
}
}
if (stepId === finalStepId) {
// Drop any tips at end of protocol
// (dropTip should do no-op when pipette has no tips)
const allPipettes = Object.keys(acc.robotState.instruments)
allPipettes.forEach(pipetteId =>
commandCreators.push(StepGeneration.dropTip(pipetteId))
)
}
const nextCommandsAndState = StepGeneration.reduceCommandCreators(commandCreators)(acc.robotState)
// for supported steps
if (nextCommandsAndState.errors) {
return {
...acc,
timelineErrors: nextCommandsAndState.errors,
errorStepId: stepId
}
}
return {
...acc,
timeline: [...acc.timeline, nextCommandsAndState],
robotState: nextCommandsAndState.robotState
}
}, {formErrors: {}, timeline: [], robotState: initialRobotState, timelineErrors: null})
// TODO Ian 2018-03-01 pass along name and description of steps for command annotations in file
if (!isEmpty(result.formErrors)) {
// TODO Ian 2018-03-01 remove log later
console.log('Got form errors while constructing timeline', result)
}
if (result.timelineErrors) {
// TODO Ian 2018-04-30 remove log later
console.log('Got timeline errors', result)
}
return result
}
)
|
rcpoison/dxvk-cache-pool
|
dxvk-cache-pool-common/src/main/java/com/ignorelist/kassandra/dxvk/cache/pool/common/crypto/SignaturePublicKeyInfo.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ignorelist.kassandra.dxvk.cache.pool.common.crypto;
import java.io.Serializable;
import java.util.Objects;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author poison
*/
@XmlRootElement
public class SignaturePublicKeyInfo implements Serializable {
private Signature signature;
private PublicKeyInfo publicKeyInfo;
public SignaturePublicKeyInfo() {
}
public SignaturePublicKeyInfo(Signature signature, PublicKeyInfo publicKeyInfo) {
this.signature=signature;
this.publicKeyInfo=publicKeyInfo;
}
@NotNull
@XmlElement(required=true)
public Signature getSignature() {
return signature;
}
public void setSignature(Signature signature) {
this.signature=signature;
}
@NotNull
@XmlElement(required=true)
public PublicKeyInfo getPublicKeyInfo() {
return publicKeyInfo;
}
public void setPublicKeyInfo(PublicKeyInfo publicKeyInfo) {
this.publicKeyInfo=publicKeyInfo;
}
@Override
public int hashCode() {
int hash=7;
hash=73*hash+Objects.hashCode(this.signature);
hash=73*hash+Objects.hashCode(this.publicKeyInfo);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this==obj) {
return true;
}
if (obj==null) {
return false;
}
if (!(obj instanceof SignaturePublicKeyInfo)) {
return false;
}
final SignaturePublicKeyInfo other=(SignaturePublicKeyInfo) obj;
if (!Objects.equals(this.signature, other.signature)) {
return false;
}
if (!Objects.equals(this.publicKeyInfo, other.publicKeyInfo)) {
return false;
}
return true;
}
}
|
simon-ritchie/apyscript
|
apysc/_event/stop_propagation_interface.py
|
"""Class implementation for the stop_propagation interface.
"""
from apysc._type.variable_name_interface import VariableNameInterface
class StopPropagationInterface(VariableNameInterface):
def stop_propagation(self) -> None:
"""
Stop event propagation.
"""
import apysc as ap
with ap.DebugInfo(
callable_=self.stop_propagation, locals_=locals(),
module_name=__name__, class_=StopPropagationInterface):
expression: str = (
f'{self.variable_name}.stopPropagation();'
)
ap.append_js_expression(expression=expression)
|
EdsonGermano/socrata-platform-socrata-thirdparty-utils
|
core/src/main/scala/com/socrata/thirdparty/typesafeconfig/ConfigClass.scala
|
package com.socrata.thirdparty.typesafeconfig
import com.typesafe.config.{Config, ConfigException, ConfigUtil}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._
import scala.collection.JavaConverters._
/** A helper for making typed configurations. */
abstract class ConfigClass(config: Config, root: String) {
protected def path(key: String*) = root + "." + ConfigUtil.joinPath(key : _*)
// we'll add more of these as we need them
def getInt(key: String): Int = config.getInt(path(key))
def getString(key: String): String = config.getString(path(key))
def getStringList(key: String): Seq[String] = config.getStringList(path(key)).asScala
def getDuration(key: String): FiniteDuration = config.getMilliseconds(path(key)).longValue.millis
def getBytes(key: String): Long = config.getBytes(path(key)).longValue
def getBoolean(key: String): Boolean = config.getBoolean(path(key))
def getConfig[T](key: String, decoder: (Config, String) => T): T = decoder(config, path(key))
def getObjectOf[T](key: String, decoder: (Config, String) => T): Map[String, T] =
config.getObject(path(key)).keySet.asScala.toSeq.map { k =>
k -> decoder(config, path(key, k))
}.toMap
def getRawConfig(key: String): Config = config.getConfig(path(key))
def optionally[T](e: => T): Option[T] = try {
Some(e)
} catch {
case _: ConfigException.Missing => None
}
}
|
phillips96/similarity
|
tests/retrieval_metrics/test_recall_at_k.py
|
<filename>tests/retrieval_metrics/test_recall_at_k.py
import pytest
import tensorflow as tf
from tensorflow_similarity.retrieval_metrics import RecallAtK
testdata = [
(
"micro",
tf.constant(0.75),
),
(
"macro",
tf.constant(0.5),
),
]
@pytest.mark.parametrize("avg, expected", testdata, ids=["micro", "macro"])
def test_compute(avg, expected):
query_labels = tf.constant([1, 1, 1, 0])
match_mask = tf.constant(
[
[True, True, False],
[True, True, False],
[True, True, False],
[False, False, True],
],
dtype=bool,
)
rm = RecallAtK(k=2, average=avg)
recall = rm.compute(query_labels=query_labels, match_mask=match_mask)
assert recall == expected
|
mdahmen/emptycanvas
|
src/main/java/info/emptycanvas/library/object/ZS3D.java
|
<gh_stars>0
/*
Vous êtes libre de :
*/
package info.emptycanvas.library.object;
public interface ZS3D {
public void addToBuffer(Representable r);
public void removeFromBuffer(Representable r);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.