text
string
size
int64
token_count
int64
/* * FloatingSine.cpp * ofSynth * * Created by damian on 12/01/11. * Copyright 2011 frey damian@frey.co.nz. All rights reserved. * */ #include "FloatingSine.h" static const float RADIUS = 30.0f; // pentatonic static const int SCALE_STEPS_PENTATONIC = 5; static const float SCALE_PENTATONIC[SCALE_STEPS_PENTATONIC] = { 0, 2, 5, 7, 10 }; // lydian Tone, tone, semitone, tone, tone, tone, semitone static const int SCALE_STEPS_LYDIAN = 8; static const float SCALE_LYDIAN[SCALE_STEPS_LYDIAN] = { 0, 2, 3, 5, 7, 9, 10 }; static const float BASE_MIDI_NOTE = 62.0f; float midiToFrequency( float midiNote ) { return 440.0f*powf(2.0f,(midiNote-60.0f)/12.0f); } void FloatingSine::setup( ofSoundMixer* mixer, vector<FloatingSine*> * n, ofImage* particleImage ) { neighbours = n; particle = particleImage; setScale( 0 ); setBaseMidiNote( BASE_MIDI_NOTE ); // setup the sound // // we have a chain like this: // [tone generator]---->[volume control]------>[mixer] // // the mixer is shared amongst all objects // int whichScaleNote = ofRandom( 0, 0.99999f*scaleSteps ); float midiNote = baseMidiNote + scale[whichScaleNote]; frequency = midiToFrequency( midiNote ); octaveOffset = ofRandom( -2.99f, 0.99f ); tone.setFrequency( frequency ); // tone goes through volume control volume.addInputFrom( &tone ); volume.setVolume( 1.0f/(n->size()) ); // we add the volume control to the mixer mixer->addInputFrom( &volume ); sawtooth = false; bBackgroundAuto = false; velocity = 0; // colours for sine and sawtooth waveforms sineColour.setHsb( 255.0f*(ofRandom( -10, 10 ) + 221.0f)/360.0f, 255.0f*(ofRandom( -0.1f, 0.1f ) + 0.79), 255.0f*(ofRandom( -0.1f, 0.1f ) + 0.66f), 200.0f ); sawColour.setHsb( 255.0f*(ofRandom( -10, 10 ) + 33.0f)/360.0f, 255.0f*(ofRandom( -0.1f, 0.1f ) + 0.79), 255.0f*(ofRandom( -0.1f, 0.1f ) + 0.66f), 200.0f ); // setup motion behaviour // each dot has a 'buddy' that it tries to maintain a fixed multiple of shellDistance away from // each dot also has an 'enemy' that it tries to run away from shellDistance = ofRandom( 100.0f, 200.0f ); position.set( ofRandom( 3.0f*ofGetWidth()/8, 5.0f*ofGetWidth()/8 ), ofRandom( 3.0f*ofGetHeight()/8, 5.0f*ofGetHeight()/8 ) ); if ( neighbours->size() >= 3 ) { buddy = ofRandomuf()*0.99999f*neighbours->size(); // avoid selecting ourselves as the buddy while ( n->at( buddy ) == this ) { buddy = (buddy+1)%neighbours->size(); } enemy = ofRandomuf()*0.99999f*neighbours->size(); // avoid selecting ourselves as the buddy while ( n->at( enemy ) == this || buddy == enemy ) { enemy = (enemy+1)%neighbours->size(); } } else { buddy = 0; enemy = 0; } } void FloatingSine::setScale( int which ) { which = min(max(0,which),1); if ( which == 0 ) { scale = SCALE_PENTATONIC; scaleSteps = SCALE_STEPS_PENTATONIC; } else { scale = SCALE_LYDIAN; scaleSteps = SCALE_STEPS_LYDIAN; } } void FloatingSine::toggleWaveform() { setWaveform ( !sawtooth ); } void FloatingSine::setWaveform( bool toSawtooth ) { sawtooth = toSawtooth; if ( sawtooth ) { tone.setSawtoothWaveform(); } else { tone.setSineWaveform(); } } void FloatingSine::update( ) { // update the position position += velocity*ofGetLastFrameTime(); // damp the velocity velocity *= powf(0.99f,ofGetLastFrameTime()); ofVec2f delta = neighbours->at( buddy )->position - position; float distance = delta.length(); ofVec2f deltaNorm = delta/distance; distanceUnits = distance/shellDistance; // calculate distance in terms of shellDistance int whichScaleNote = distanceUnits; float remainder = distanceUnits - whichScaleNote; if ( remainder > 0.5f ) { // round distanceUnits += 1.0f; whichScaleNote += 1.0f; remainder = 1.0f-remainder; } // update frequency float midiNote = baseMidiNote; while ( whichScaleNote>=scaleSteps ) { midiNote += 12; whichScaleNote -= scaleSteps; } // convert scale steps to actual scale notes float scaleNote = scale[whichScaleNote%scaleSteps]; float nextScaleNote = scale[(whichScaleNote+1)%scaleSteps]; float prevScaleNote = scale[(whichScaleNote+4)%scaleSteps]; if ( prevScaleNote>nextScaleNote) { // wrap nextScaleNote += 12.0f; } // set the actual frequency, adding on a detune calculated from remainder tone.setFrequency( midiToFrequency( float(octaveOffset*12) + midiNote + scaleNote + remainder*0.1f /* (remainder>0.0f?1.0f:-1.0f)*remainder*remainder*/ ) ); // set volume float vol = 1.0f-min(1.0f,(distance/ofGetWidth())); volume.setVolume( 1.0f*vol/(neighbours->size()) ); // calculate forces static const float BUDDY_FORCE_MUL = 1000.0f; static const float ENEMY_FORCE_MUL = 100.0f; static const float CENTRE_FORCE_MUL = 0.3f; // move towards the nearest shell out from our buddy ofVec2f dv = ((remainder>0.0f)&&(distanceUnits>1.0f)>0.0f?-1.0f:1.0f)* remainder*remainder*deltaNorm*ofGetLastFrameTime()*BUDDY_FORCE_MUL; velocity += dv*0.5f; neighbours->at(buddy)->velocity -= dv*0.5f; // run away from enemy ofVec2f enemyDelta = neighbours->at( enemy )->position - position; float enemyDistance = enemyDelta.length(); ofVec2f enemyDeltaNorm = enemyDelta/enemyDistance; dv = enemyDeltaNorm*(1.0f/enemyDistance)*ofGetLastFrameTime()*ENEMY_FORCE_MUL; velocity -= dv*0.5f; neighbours->at( enemy )->velocity += dv*0.5f; // don't get too far away from the centre of the screen ofVec2f centreDelta = ofVec2f(ofGetWidth()/2,ofGetHeight()/2)-position; velocity += centreDelta*ofGetLastFrameTime()*CENTRE_FORCE_MUL; } void FloatingSine::draw(){ float vol = volume.getVolume(); float volSq = vol*vol; float alpha = fabsf(2.0f*(distanceUnits-int(distanceUnits)-0.5f)); // select colour based on waveform ofColor colour = sawtooth?sawColour:sineColour; // draw the particle float particleAlpha = (bBackgroundAuto?1.0f:0.2f)*(128+128.0f*alpha); ofSetColor( colour.r, colour.g, colour.b, particleAlpha ); ofFill(); particle->setAnchorPercent(0.5,0.5); ofCircle( position.x, position.y, RADIUS*(0.4f+0.6f*alpha*volume.getVolume()*neighbours->size()) ); // draw the connecting lines and shell lines float lineAlpha = (bBackgroundAuto?1.0f:0.2f)*(255.0f*alpha); ofSetColor( colour.r, colour.g, colour.b, lineAlpha ); ofNoFill(); ofVec2f buddyPosition = neighbours->at(buddy)->position; ofLine( position.x, position.y, buddyPosition.x, buddyPosition.y ); ofCircle( buddyPosition.x, buddyPosition.y, distanceUnits*shellDistance ); } void FloatingSine::setBackgroundAuto( bool bAuto ) { bBackgroundAuto = bAuto; }
6,615
2,868
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright EntityRef license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <Source/Framework/ScriptCanvasTestFixture.h> #include <Source/Framework/ScriptCanvasTestUtilities.h> #include <Source/Framework/ScriptCanvasTestNodes.h> #include <AzCore/Serialization/IdUtils.h> #include <ScriptCanvas/Asset/RuntimeAsset.h> #include <ScriptCanvas/Asset/RuntimeAssetHandler.h> #include <ScriptCanvas/Execution/RuntimeComponent.h> #include <ScriptCanvas/Variable/GraphVariableManagerComponent.h> using namespace ScriptCanvasTests; using namespace TestNodes; TEST_F(ScriptCanvasTestFixture, CoreNodeFunction_OwningGraphCheck) { using namespace ScriptCanvas; Graph* graph = CreateGraph(); ConfigurableUnitTestNode* groupedNode = CreateConfigurableNode(); EXPECT_EQ(graph, groupedNode->GetGraph()); } TEST_F(ScriptCanvasTestFixture, AddRemoveSlot) { RegisterComponentDescriptor<AddNodeWithRemoveSlot>(); using namespace ScriptCanvas; using namespace Nodes; AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("RemoveSlotGraph"); graphEntity->Init(); Graph* graph{}; SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get()); AZ::EntityId graphUniqueId = graph->GetUniqueId(); AZ::EntityId outID; auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID); auto numberAddNode = CreateTestNode<AddNodeWithRemoveSlot>(graphUniqueId, outID); auto number1Node = CreateDataNode<Data::NumberType>(graphUniqueId, 1.0, outID); auto number2Node = CreateDataNode<Data::NumberType>(graphUniqueId, 2.0, outID); auto number3Node = CreateDataNode<Data::NumberType>(graphUniqueId, 4.0, outID); auto numberResultNode = CreateDataNode<Data::NumberType>(graphUniqueId, 0.0, outID); // data EXPECT_TRUE(Connect(*graph, number1Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "A")); EXPECT_TRUE(Connect(*graph, number2Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "B")); EXPECT_TRUE(Connect(*graph, number3Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "C")); EXPECT_TRUE(Connect(*graph, numberAddNode->GetEntityId(), "Result", numberResultNode->GetEntityId(), "Set")); // logic EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", numberAddNode->GetEntityId(), "In")); // execute pre remove graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set")) { SC_EXPECT_DOUBLE_EQ(7.0, *result); } else { ADD_FAILURE(); } // Remove the second number slot from the AddNodeWithRemoveSlot node(the one that contains value = 2.0) numberAddNode->RemoveSlot(numberAddNode->GetSlotId("B")); EXPECT_FALSE(numberAddNode->GetSlotId("B").IsValid()); // execute post-remove graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set")) { SC_EXPECT_DOUBLE_EQ(5.0, *result); } else { ADD_FAILURE(); } // Add two more slots and set there values to 8.0 and 16.0 EXPECT_TRUE(numberAddNode->AddSlot("D").IsValid()); EXPECT_TRUE(numberAddNode->AddSlot("B").IsValid()); auto number4Node = CreateDataNode<Data::NumberType>(graphUniqueId, 8.0, outID); auto number5Node = CreateDataNode<Data::NumberType>(graphUniqueId, 16.0, outID); EXPECT_TRUE(Connect(*graph, number4Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "D")); EXPECT_TRUE(Connect(*graph, number5Node->GetEntityId(), "Get", numberAddNode->GetEntityId(), "B")); // execute post-add of slot "D" and re-add of slot "A" graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set")) { SC_EXPECT_DOUBLE_EQ(1.0 + 4.0 + 8.0 + 16.0, *result); } else { ADD_FAILURE(); } // Remove the first number slot from the AddNodeWithRemoveSlot node(the one that contains value = 1.0 numberAddNode->RemoveSlot(numberAddNode->GetSlotId("A")); EXPECT_FALSE(numberAddNode->GetSlotId("A").IsValid()); // execute post-remove of "A" slot graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); if (auto result = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set")) { SC_EXPECT_DOUBLE_EQ(4.0 + 8.0 + 16.0, *result); } else { ADD_FAILURE(); } graphEntity.reset(); } TEST_F(ScriptCanvasTestFixture, AddRemoveSlotNotifications) { RegisterComponentDescriptor<AddNodeWithRemoveSlot>(); using namespace ScriptCanvas; using namespace Nodes; AZStd::unique_ptr<AZ::Entity> numberAddEntity = AZStd::make_unique<AZ::Entity>("numberAddEntity"); auto numberAddNode = numberAddEntity->CreateComponent<AddNodeWithRemoveSlot>(); numberAddEntity->Init(); ScriptUnitTestNodeNotificationHandler nodeNotifications(numberAddNode->GetEntityId()); SlotId testSlotId = numberAddNode->AddSlot("test"); EXPECT_EQ(1U, nodeNotifications.GetSlotsAdded()); numberAddNode->RemoveSlot(testSlotId); EXPECT_EQ(1U, nodeNotifications.GetSlotsRemoved()); testSlotId = numberAddNode->AddSlot("duplicate"); EXPECT_EQ(2U, nodeNotifications.GetSlotsAdded()); // This should not signal the NodeNotification::OnSlotAdded event as the slot already exist on the node SlotId duplicateSlotId = numberAddNode->AddSlot("duplicate"); EXPECT_EQ(2U, nodeNotifications.GetSlotsAdded()); EXPECT_EQ(testSlotId, duplicateSlotId); numberAddNode->RemoveSlot(testSlotId); EXPECT_EQ(2U, nodeNotifications.GetSlotsRemoved()); // This should not signal the NodeNotification::OnSlotRemoved event as the slot no longer exist on the node numberAddNode->RemoveSlot(testSlotId); EXPECT_EQ(2U, nodeNotifications.GetSlotsRemoved()); numberAddEntity.reset(); } TEST_F(ScriptCanvasTestFixture, InsertSlot) { RegisterComponentDescriptor<InsertSlotConcatNode>(); using namespace ScriptCanvas; using namespace Nodes; AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("RemoveSlotGraph"); graphEntity->Init(); SystemRequestBus::Broadcast(&SystemRequests::CreateEngineComponentsOnEntity, graphEntity.get()); Graph* graph = AZ::EntityUtils::FindFirstDerivedComponent<Graph>(graphEntity.get()); AZ::EntityId graphUniqueId = graph->GetUniqueId(); AZ::EntityId outId; auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outId); auto insertSlotConcatNode = CreateTestNode<InsertSlotConcatNode>(graphUniqueId, outId); auto setVariableNode = CreateTestNode<Nodes::Core::SetVariableNode>(graphUniqueId, outId); VariableId resultVarId = CreateVariable(graphUniqueId, Data::StringType(), "result"); VariableId middleValueVarId = CreateVariable(graphUniqueId, Data::StringType(" Ice Cream"), "middleValue"); setVariableNode->SetId(resultVarId); EXPECT_TRUE(setVariableNode->GetDataInSlotId().IsValid()); //logic connections EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", insertSlotConcatNode->GetEntityId(), "In")); EXPECT_TRUE(Connect(*graph, insertSlotConcatNode->GetEntityId(), "Out", setVariableNode->GetEntityId(), "In")); // insert slots auto concatSlotId = insertSlotConcatNode->InsertSlot(-1, "A"); auto slotAId = concatSlotId; insertSlotConcatNode->SetInput_UNIT_TEST(concatSlotId, Data::StringType("Hello")); concatSlotId = insertSlotConcatNode->InsertSlot(-1, "B"); auto slotBId = concatSlotId; insertSlotConcatNode->SetInput_UNIT_TEST(concatSlotId, Data::StringType(" World")); // data connections EXPECT_TRUE(graph->Connect(insertSlotConcatNode->GetEntityId(), insertSlotConcatNode->GetSlotId("Result"), setVariableNode->GetEntityId(), setVariableNode->GetDataInSlotId())); graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); const VariableDatum* resultDatum{}; VariableRequestBus::EventResult(resultDatum, resultVarId, &VariableRequests::GetVariableDatumConst); ASSERT_NE(nullptr, resultDatum); EXPECT_EQ("Hello World", resultDatum->GetData().ToString()); // insert additional slot between A and B auto slotIndexOutcome = insertSlotConcatNode->FindSlotIndex(slotBId); EXPECT_TRUE(slotIndexOutcome); concatSlotId = insertSlotConcatNode->InsertSlot(slotIndexOutcome.GetValue(), "Alpha"); NodeRequestBus::Event(insertSlotConcatNode->GetEntityId(), &NodeRequests::SetSlotVariableId, concatSlotId, middleValueVarId); // re-execute the graph graphEntity->Activate(); ReportErrors(graph); graphEntity->Deactivate(); // the new concatenated string should be in the middle EXPECT_EQ("Hello Ice Cream World", resultDatum->GetData().ToString()); graphEntity.reset(); } TEST_F(ScriptCanvasTestFixture, NativeProperties) { using namespace ScriptCanvas; using namespace Nodes; AZ::Entity* graphEntity = aznew AZ::Entity("Graph"); graphEntity->Init(); SystemRequestBus::Broadcast(&SystemRequests::CreateGraphOnEntity, graphEntity); auto graph = graphEntity->FindComponent<Graph>(); EXPECT_NE(nullptr, graph); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId addId; CreateTestNode<Vector3Nodes::AddNode>(graphUniqueId, addId); AZ::EntityId vector3IdA, vector3IdB, vector3IdC; auto vector3NodeA = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdA); auto vector3NodeB = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdB); auto vector3NodeC = CreateTestNode<Nodes::Math::Vector3>(graphUniqueId, vector3IdC); AZ::EntityId number1Id, number2Id, number3Id, number4Id, number5Id, number6Id, number7Id, number8Id, number9Id; Node* number1Node = CreateDataNode<Data::NumberType>(graphUniqueId, 1, number1Id); Node* number2Node = CreateDataNode<Data::NumberType>(graphUniqueId, 2, number2Id); Node* number3Node = CreateDataNode<Data::NumberType>(graphUniqueId, 3, number3Id); Node* number4Node = CreateDataNode<Data::NumberType>(graphUniqueId, 4, number4Id); Node* number5Node = CreateDataNode<Data::NumberType>(graphUniqueId, 5, number5Id); Node* number6Node = CreateDataNode<Data::NumberType>(graphUniqueId, 6, number6Id); Node* number7Node = CreateDataNode<Data::NumberType>(graphUniqueId, 7, number7Id); Node* number8Node = CreateDataNode<Data::NumberType>(graphUniqueId, 8, number8Id); Node* number9Node = CreateDataNode<Data::NumberType>(graphUniqueId, 0, number9Id); // data EXPECT_TRUE(Connect(*graph, number1Id, "Get", vector3IdA, "Number: x")); EXPECT_TRUE(Connect(*graph, number2Id, "Get", vector3IdA, "Number: y")); EXPECT_TRUE(Connect(*graph, number3Id, "Get", vector3IdA, "Number: z")); EXPECT_TRUE(Connect(*graph, number4Id, "Get", vector3IdB, "Number: x")); EXPECT_TRUE(Connect(*graph, number5Id, "Get", vector3IdB, "Number: y")); EXPECT_TRUE(Connect(*graph, number6Id, "Get", vector3IdB, "Number: z")); EXPECT_TRUE(Connect(*graph, vector3IdA, "Get", addId, "Vector3: A")); EXPECT_TRUE(Connect(*graph, vector3IdB, "Get", addId, "Vector3: B")); EXPECT_TRUE(Connect(*graph, addId, "Result: Vector3", vector3IdC, "Set")); EXPECT_TRUE(Connect(*graph, vector3IdC, "x: Number", number7Id, "Set")); EXPECT_TRUE(Connect(*graph, vector3IdC, "y: Number", number8Id, "Set")); EXPECT_TRUE(Connect(*graph, vector3IdC, "z: Number", number9Id, "Set")); // code EXPECT_TRUE(Connect(*graph, startID, "Out", addId, "In")); graphEntity->Activate(); ReportErrors(graph); if (auto result = vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set")) { EXPECT_EQ(AZ::Vector3(5, 7, 9), *result); } else { ADD_FAILURE(); } if (auto result = number7Node->GetInput_UNIT_TEST<Data::NumberType>("Set")) { EXPECT_EQ(5, *result); } else { ADD_FAILURE(); } if (auto result = number8Node->GetInput_UNIT_TEST<Data::NumberType>("Set")) { EXPECT_EQ(7, *result); } else { ADD_FAILURE(); } if (auto result = number9Node->GetInput_UNIT_TEST<Data::NumberType>("Set")) { EXPECT_EQ(9, *result); } else { ADD_FAILURE(); } graphEntity->Deactivate(); delete graphEntity; } TEST_F(ScriptCanvasTestFixture, ExtractPropertiesNativeType) { // TODO: Add Extract test for all Native Types using namespace ScriptCanvas; using namespace Nodes; AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("PropertyGraph"); Graph* graph{}; SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get()); ASSERT_NE(nullptr, graph); AZ::EntityId propertyEntityId = graphEntity->GetId(); AZ::EntityId graphUniqueId = graph->GetUniqueId(); graphEntity->Init(); // Create Extract Property Node AZ::EntityId outID; auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID); auto extractPropertyNode = CreateTestNode<Nodes::Core::ExtractProperty>(graphUniqueId, outID); auto printNode = CreateTestNode<TestResult>(graphUniqueId, outID); // Test Native Vector3 Properties auto vector3Node = CreateDataNode(graphUniqueId, Data::Vector3Type(10.0f, 23.3f, 77.45f), outID); auto numberResultNode1 = CreateDataNode(graphUniqueId, 0.0f, outID); auto numberResultNode2 = CreateDataNode(graphUniqueId, 0.0f, outID); auto numberResultNode3 = CreateDataNode(graphUniqueId, 0.0f, outID); // data EXPECT_EQ(0, extractPropertyNode->GetPropertyFields().size()); EXPECT_FALSE(extractPropertyNode->GetSourceSlotDataType().IsValid()); EXPECT_TRUE(Connect(*graph, vector3Node->GetEntityId(), "Get", extractPropertyNode->GetEntityId(), "Source")); auto propertyFields = extractPropertyNode->GetPropertyFields(); EXPECT_EQ(3, propertyFields.size()); EXPECT_TRUE(extractPropertyNode->GetSourceSlotDataType().IS_A(Data::Type::Vector3())); // Vector3::x auto propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "x"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode1->GetEntityId(), numberResultNode1->GetSlotId("Set"))); // Vector3::y propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "y"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode2->GetEntityId(), numberResultNode2->GetSlotId("Set"))); // Vector3::z propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "z"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode3->GetEntityId(), numberResultNode3->GetSlotId("Set"))); // Print the z value to console EXPECT_TRUE(graph->Connect(numberResultNode3->GetEntityId(), numberResultNode3->GetSlotId("Get"), printNode->GetEntityId(), printNode->GetSlotId("Value"))); // logic EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", extractPropertyNode->GetEntityId(), "In")); EXPECT_TRUE(Connect(*graph, extractPropertyNode->GetEntityId(), "Out", printNode->GetEntityId(), "In")); // execute { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graphEntity->Activate(); } ReportErrors(graph); graphEntity->Deactivate(); AZ::Entity* connectionEntity{}; EXPECT_TRUE(graph->FindConnection(connectionEntity, { vector3Node->GetEntityId(), vector3Node->GetSlotId("Get") }, { extractPropertyNode->GetEntityId(), extractPropertyNode->GetSlotId("Source") })); EXPECT_TRUE(graph->DisconnectById(connectionEntity->GetId())); const float tolerance = 0.001f; // x result auto vectorElementResult = numberResultNode1->GetInput_UNIT_TEST<Data::NumberType>("Set"); ASSERT_NE(nullptr, vectorElementResult); EXPECT_NEAR(10.0f, *vectorElementResult, tolerance); // y result vectorElementResult = numberResultNode2->GetInput_UNIT_TEST<Data::NumberType>("Set"); ASSERT_NE(nullptr, vectorElementResult); EXPECT_NEAR(23.3f, *vectorElementResult, tolerance); // z result vectorElementResult = numberResultNode3->GetInput_UNIT_TEST<Data::NumberType>("Set"); ASSERT_NE(nullptr, vectorElementResult); EXPECT_NEAR(77.45f, *vectorElementResult, tolerance); graphEntity.reset(); } TEST_F(ScriptCanvasTestFixture, ExtractPropertiesBehaviorType) { TestBehaviorContextProperties::Reflect(m_serializeContext); TestBehaviorContextProperties::Reflect(m_behaviorContext); using namespace ScriptCanvas; using namespace Nodes; AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("PropertyGraph"); Graph* graph{}; SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get()); ASSERT_NE(nullptr, graph); AZ::EntityId propertyEntityId = graphEntity->GetId(); AZ::EntityId graphUniqueId = graph->GetUniqueId(); graphEntity->Init(); // Create Extract Property Node AZ::EntityId outID; auto startNode = CreateTestNode<Nodes::Core::Start>(graphUniqueId, outID); auto extractPropertyNode = CreateTestNode<Nodes::Core::ExtractProperty>(graphUniqueId, outID); auto printNode = CreateTestNode<TestResult>(graphUniqueId, outID); // Test BehaviorContext Properties TestBehaviorContextProperties behaviorContextProperties; behaviorContextProperties.m_booleanProp = true; behaviorContextProperties.m_numberProp = 11.90f; behaviorContextProperties.m_stringProp = "String Property"; auto behaviorContextPropertyNode = CreateDataNode(graphUniqueId, behaviorContextProperties, outID); auto booleanResultNode = CreateDataNode(graphUniqueId, false, outID); auto numberResultNode = CreateDataNode(graphUniqueId, 0.0f, outID); auto stringResultNode = CreateDataNode(graphUniqueId, Data::StringType("Uninitialized"), outID); // data EXPECT_EQ(0, extractPropertyNode->GetPropertyFields().size()); EXPECT_FALSE(extractPropertyNode->GetSourceSlotDataType().IsValid()); EXPECT_TRUE(Connect(*graph, behaviorContextPropertyNode->GetEntityId(), "Get", extractPropertyNode->GetEntityId(), "Source")); auto propertyFields = extractPropertyNode->GetPropertyFields(); EXPECT_EQ(4, propertyFields.size()); EXPECT_TRUE(extractPropertyNode->GetSourceSlotDataType().IS_A(Data::FromAZType<TestBehaviorContextProperties>())); // TestBehaviorContextProperties::boolean auto propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "boolean"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, booleanResultNode->GetEntityId(), booleanResultNode->GetSlotId("Set"))); // TestBehaviorContextProperties::number propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "number"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, numberResultNode->GetEntityId(), numberResultNode->GetSlotId("Set"))); // TestBehaviorContextProperties::string propIt = AZStd::find_if(propertyFields.begin(), propertyFields.end(), [](const AZStd::pair<AZStd::string_view, SlotId> propertyField) { return propertyField.first == "string"; }); ASSERT_NE(propIt, propertyFields.end()); EXPECT_TRUE(graph->Connect(extractPropertyNode->GetEntityId(), propIt->second, stringResultNode->GetEntityId(), stringResultNode->GetSlotId("Set"))); // Print the string value to console EXPECT_TRUE(graph->Connect(stringResultNode->GetEntityId(), stringResultNode->GetSlotId("Get"), printNode->GetEntityId(), printNode->GetSlotId("Value"))); // logic EXPECT_TRUE(Connect(*graph, startNode->GetEntityId(), "Out", extractPropertyNode->GetEntityId(), "In")); EXPECT_TRUE(Connect(*graph, extractPropertyNode->GetEntityId(), "Out", printNode->GetEntityId(), "In")); // execute { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graphEntity->Activate(); } ReportErrors(graph); graphEntity->Deactivate(); AZ::Entity* connectionEntity{}; EXPECT_TRUE(graph->FindConnection(connectionEntity, { behaviorContextPropertyNode->GetEntityId(), behaviorContextPropertyNode->GetSlotId("Get") }, { extractPropertyNode->GetEntityId(), extractPropertyNode->GetSlotId("Source") })); EXPECT_TRUE(graph->DisconnectById(connectionEntity->GetId())); // boolean result auto booleanResult = booleanResultNode->GetInput_UNIT_TEST<Data::BooleanType>("Set"); ASSERT_NE(nullptr, booleanResult); EXPECT_TRUE(booleanResult); // number result const float tolerance = 0.001f; auto numberResult = numberResultNode->GetInput_UNIT_TEST<Data::NumberType>("Set"); ASSERT_NE(nullptr, numberResult); EXPECT_NEAR(11.90f, *numberResult, tolerance); // string result auto stringResult = stringResultNode->GetInput_UNIT_TEST<Data::StringType>("Set"); ASSERT_NE(nullptr, stringResult); EXPECT_EQ("String Property", *stringResult); graphEntity.reset(); m_serializeContext->EnableRemoveReflection(); TestBehaviorContextProperties::Reflect(m_serializeContext); m_serializeContext->DisableRemoveReflection(); m_behaviorContext->EnableRemoveReflection(); TestBehaviorContextProperties::Reflect(m_behaviorContext); m_behaviorContext->DisableRemoveReflection(); } TEST_F(ScriptCanvasTestFixture, IsNullCheck) { using namespace ScriptCanvas; EventTestHandler::Reflect(m_serializeContext); EventTestHandler::Reflect(m_behaviorContext); TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); Graph* graph(nullptr); SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityID = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId isNullFalseID; CreateTestNode<Nodes::Logic::IsNull>(graphUniqueId, isNullFalseID); AZ::EntityId isNullTrueID; CreateTestNode<Nodes::Logic::IsNull>(graphUniqueId, isNullTrueID); AZ::EntityId isNullResultFalseID; auto isNullResultFalse = CreateDataNode(graphUniqueId, true, isNullResultFalseID); AZ::EntityId isNullResultTrueID; auto isNullResultTrue = CreateDataNode(graphUniqueId, false, isNullResultTrueID); AZ::EntityId normalizeID; Nodes::Core::Method* normalize = CreateTestNode<Nodes::Core::Method>(graphUniqueId, normalizeID); Namespaces empty; normalize->InitializeClass(empty, "TestBehaviorContextObject", "Normalize"); AZ::EntityId vectorID; Nodes::Core::BehaviorContextObjectNode* vector = CreateTestNode<Nodes::Core::BehaviorContextObjectNode>(graphUniqueId, vectorID); const AZStd::string vector3("TestBehaviorContextObject"); vector->InitializeObject(vector3); if (auto vector3 = vector->ModInput_UNIT_TEST<TestBehaviorContextObject>("Set")) { EXPECT_FALSE(vector3->IsNormalized()); } else { ADD_FAILURE(); } // test the reference type contract { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; EXPECT_FALSE(Connect(*graph, isNullResultFalseID, "Get", isNullTrueID, "Reference")); } // data EXPECT_TRUE(Connect(*graph, vectorID, "Get", normalizeID, "TestBehaviorContextObject: 0")); EXPECT_TRUE(Connect(*graph, vectorID, "Get", isNullFalseID, "Reference")); EXPECT_TRUE(Connect(*graph, isNullTrueID, "Is Null", isNullResultTrueID, "Set")); EXPECT_TRUE(Connect(*graph, isNullFalseID, "Is Null", isNullResultFalseID, "Set")); // execution EXPECT_TRUE(Connect(*graph, startID, "Out", isNullTrueID, "In")); EXPECT_TRUE(Connect(*graph, isNullTrueID, "True", isNullFalseID, "In")); EXPECT_TRUE(Connect(*graph, isNullFalseID, "False", normalizeID, "In")); AZ::Entity* graphEntity = graph->GetEntity(); { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graphEntity->Activate(); } ReportErrors(graph); if (auto vector3 = vector->GetInput_UNIT_TEST<TestBehaviorContextObject>("Set")) { EXPECT_TRUE(vector3->IsNormalized()); } else { ADD_FAILURE(); } if (auto shouldBeFalse = isNullResultFalse->GetInput_UNIT_TEST<bool>("Set")) { EXPECT_FALSE(*shouldBeFalse); } else { ADD_FAILURE(); } if (auto shouldBeTrue = isNullResultTrue->GetInput_UNIT_TEST<bool>("Set")) { EXPECT_TRUE(*shouldBeTrue); } else { ADD_FAILURE(); } graphEntity->Deactivate(); delete graphEntity; m_serializeContext->EnableRemoveReflection(); m_behaviorContext->EnableRemoveReflection(); EventTestHandler::Reflect(m_serializeContext); EventTestHandler::Reflect(m_behaviorContext); TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); m_serializeContext->DisableRemoveReflection(); m_behaviorContext->DisableRemoveReflection(); } TEST_F(ScriptCanvasTestFixture, NullThisPointerDoesNotCrash) { using namespace ScriptCanvas; EventTestHandler::Reflect(m_serializeContext); EventTestHandler::Reflect(m_behaviorContext); TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); Graph* graph(nullptr); SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityID = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId normalizeID; Nodes::Core::Method* normalize = CreateTestNode<Nodes::Core::Method>(graphUniqueId, normalizeID); Namespaces empty; normalize->InitializeClass(empty, "TestBehaviorContextObject", "Normalize"); EXPECT_TRUE(Connect(*graph, startID, "Out", normalizeID, "In")); AZ::Entity* graphEntity = graph->GetEntity(); { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graphEntity->Activate(); } // just don't crash, but be in error const bool expectError = true; const bool expectIrrecoverableError = true; ReportErrors(graph, expectError, expectIrrecoverableError); graphEntity->Deactivate(); delete graphEntity; m_serializeContext->EnableRemoveReflection(); m_behaviorContext->EnableRemoveReflection(); EventTestHandler::Reflect(m_serializeContext); EventTestHandler::Reflect(m_behaviorContext); TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); m_serializeContext->DisableRemoveReflection(); m_behaviorContext->DisableRemoveReflection(); } TEST_F(ScriptCanvasTestFixture, ValueTypes) { using namespace ScriptCanvas; Datum number0(Datum(0)); int number0Value = *number0.GetAs<int>(); Datum number1(Datum(1)); int number1Value = *number1.GetAs<int>(); Datum numberFloat(Datum(2.f)); float numberFloatValue = *numberFloat.GetAs<float>(); Datum numberDouble(Datum(3.0)); double numberDoubleValue = *numberDouble.GetAs<double>(); Datum numberHex(Datum(0xff)); int numberHexValue = *numberHex.GetAs<int>(); Datum numberPi(Datum(3.14f)); float numberPiValue = *numberPi.GetAs<float>(); Datum numberSigned(Datum(-100)); int numberSignedValue = *numberSigned.GetAs<int>(); Datum numberUnsigned(Datum(100u)); unsigned int numberUnsignedValue = *numberUnsigned.GetAs<unsigned int>(); Datum numberDoublePi(Datum(6.28)); double numberDoublePiValue = *numberDoublePi.GetAs<double>(); EXPECT_EQ(number0Value, 0); EXPECT_EQ(number1Value, 1); EXPECT_TRUE(AZ::IsClose(numberFloatValue, 2.f, std::numeric_limits<float>::epsilon())); EXPECT_TRUE(AZ::IsClose(numberDoubleValue, 3.0, std::numeric_limits<double>::epsilon())); EXPECT_NE(number0Value, number1Value); SC_EXPECT_FLOAT_EQ(numberPiValue, 3.14f); EXPECT_NE(number0Value, numberPiValue); EXPECT_NE(numberPiValue, numberDoublePiValue); Datum boolTrue(Datum(true)); EXPECT_TRUE(*boolTrue.GetAs<bool>()); Datum boolFalse(Datum(false)); EXPECT_FALSE(*boolFalse.GetAs<bool>()); boolFalse = boolTrue; EXPECT_TRUE(*boolFalse.GetAs<bool>()); Datum boolFalse2(Datum(false)); boolTrue = boolFalse2; EXPECT_FALSE(*boolTrue.GetAs<bool>()); { const int k_count(10000); AZStd::vector<Datum> objects; for (int i = 0; i < k_count; ++i) { objects.push_back(Datum("Vector3", Datum::eOriginality::Original)); } } GTEST_SUCCEED(); } namespace { using namespace ScriptCanvas; using namespace ScriptCanvas::Nodes; bool GraphHasVectorWithValue(const Graph& graph, const AZ::Vector3& vector) { for (auto nodeId : graph.GetNodes()) { AZ::Entity* entity{}; AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId); if (entity) { if (auto node = AZ::EntityUtils::FindFirstDerivedComponent<Core::BehaviorContextObjectNode>(entity)) { if (auto candidate = node->GetInput_UNIT_TEST<AZ::Vector3>("Set")) { if (*candidate == vector) { return true; } } } } } return false; } } TEST_F(ScriptCanvasTestFixture, SerializationSaveTest) { using namespace ScriptCanvas; using namespace ScriptCanvas::Nodes; ////////////////////////////////////////////////////////////////////////// // Make the graph. Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); // Make the nodes. // Start AZ::Entity* startEntity{ aznew AZ::Entity }; startEntity->Init(); AZ::EntityId startNode{ startEntity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, startNode, graphUniqueId, Nodes::Core::Start::TYPEINFO_Uuid()); // Constant 0 AZ::Entity* constant0Entity{ aznew AZ::Entity }; constant0Entity->Init(); AZ::EntityId constant0Node{ constant0Entity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, constant0Node, graphUniqueId, Nodes::Math::Number::TYPEINFO_Uuid()); // Get the node and set the value Nodes::Math::Number* constant0NodePtr = nullptr; SystemRequestBus::BroadcastResult(constant0NodePtr, &SystemRequests::GetNode<Nodes::Math::Number>, constant0Node); EXPECT_TRUE(constant0NodePtr != nullptr); if (constant0NodePtr) { constant0NodePtr->SetInput_UNIT_TEST("Set", 4); } // Constant 1 AZ::Entity* constant1Entity{ aznew AZ::Entity }; constant1Entity->Init(); AZ::EntityId constant1Node{ constant1Entity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, constant1Node, graphUniqueId, Nodes::Math::Number::TYPEINFO_Uuid()); // Get the node and set the value Nodes::Math::Number* constant1NodePtr = nullptr; SystemRequestBus::BroadcastResult(constant1NodePtr, &SystemRequests::GetNode<Nodes::Math::Number>, constant1Node); EXPECT_TRUE(constant1NodePtr != nullptr); if (constant1NodePtr) { constant1NodePtr->SetInput_UNIT_TEST("Set", 12); } // Sum AZ::Entity* sumEntity{ aznew AZ::Entity }; sumEntity->Init(); AZ::EntityId sumNode{ sumEntity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, sumNode, graphUniqueId, Nodes::Math::Sum::TYPEINFO_Uuid()); AZ::EntityId printID; auto printNode = CreateTestNode<TestResult>(graphUniqueId, printID); // Connect, disconnect and reconnect to validate disconnection graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get")); graph->Disconnect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get")); graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_lhsName), constant0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant0Entity)->GetSlotId("Get")); { auto* sumNodePtr = AZ::EntityUtils::FindFirstDerivedComponent<Nodes::Math::Sum>(sumEntity); EXPECT_NE(nullptr, sumNodePtr); EXPECT_EQ(1, graph->GetConnectedEndpoints({ sumNode, sumNodePtr->GetSlotId(BinaryOperator::k_lhsName) }).size()); } graph->Connect(sumNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(sumEntity)->GetSlotId(BinaryOperator::k_rhsName), constant1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(constant1Entity)->GetSlotId("Get")); EXPECT_TRUE(Connect(*graph, sumNode, "Result", printID, "Value")); EXPECT_TRUE(Connect(*graph, startNode, "Out", sumNode, Nodes::BinaryOperator::k_evaluateName)); EXPECT_TRUE(Connect(*graph, sumNode, Nodes::BinaryOperator::k_outName, printID, "In")); AZ::EntityId vector3IdA, vector3IdB, vector3IdC; const AZ::Vector3 allOne(1, 1, 1); const AZ::Vector3 allTwo(2, 2, 2); const AZ::Vector3 allThree(3, 3, 3); const AZ::Vector3 allFour(4, 4, 4); Core::BehaviorContextObjectNode* vector3NodeA = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdA); vector3NodeA->InitializeObject(azrtti_typeid<AZ::Vector3>()); *vector3NodeA->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allOne; Core::BehaviorContextObjectNode* vector3NodeB = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdB); vector3NodeB->InitializeObject(azrtti_typeid<AZ::Vector3>()); *vector3NodeB->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allTwo; Core::BehaviorContextObjectNode* vector3NodeC = CreateTestNode<Core::BehaviorContextObjectNode>(graphUniqueId, vector3IdC); vector3NodeC->InitializeObject(azrtti_typeid<AZ::Vector3>()); *vector3NodeC->ModInput_UNIT_TEST<AZ::Vector3>("Set") = allFour; AZ::EntityId add3IdA; CreateTestNode<Vector3Nodes::AddNode>(graphUniqueId, add3IdA); EXPECT_TRUE(Connect(*graph, printID, "Out", add3IdA, "In")); EXPECT_TRUE(Connect(*graph, vector3IdA, "Get", add3IdA, "Vector3: A")); EXPECT_TRUE(Connect(*graph, vector3IdB, "Get", add3IdA, "Vector3: B")); EXPECT_TRUE(Connect(*graph, vector3IdC, "Set", add3IdA, "Result: Vector3")); AZStd::unique_ptr<AZ::Entity> graphEntity{ graph->GetEntity() }; EXPECT_EQ(allOne, *vector3NodeA->GetInput_UNIT_TEST<AZ::Vector3>("Set")); EXPECT_EQ(allTwo, *vector3NodeB->GetInput_UNIT_TEST<AZ::Vector3>("Set")); auto vector3C = *vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set"); EXPECT_EQ(allFour, vector3C); auto nodeIDs = graph->GetNodes(); EXPECT_EQ(9, nodeIDs.size()); ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, true); graphEntity->Activate(); ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, false); ReportErrors(graph); vector3C = *vector3NodeC->GetInput_UNIT_TEST<AZ::Vector3>("Set"); EXPECT_EQ(allThree, vector3C); if (auto result = printNode->GetInput_UNIT_TEST<float>("Value")) { SC_EXPECT_FLOAT_EQ(*result, 16.0f); } else { ADD_FAILURE(); } graphEntity->Deactivate(); auto* fileIO = AZ::IO::LocalFileIO::GetInstance(); EXPECT_TRUE(fileIO != nullptr); auto pathResult = fileIO->CreatePath(k_tempCoreAssetDir);; EXPECT_EQ(pathResult.GetResultCode(), AZ::IO::ResultCode::Success) << "Path failed to create"; // Save it bool result = false; AZ::IO::FileIOStream outFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeWrite); if (outFileStream.IsOpen()) { RuntimeAssetHandler runtimeAssetHandler; AZ::Data::Asset<RuntimeAsset> runtimeAsset = CreateRuntimeAsset(graph); EXPECT_TRUE(runtimeAssetHandler.SaveAssetData(runtimeAsset, &outFileStream)) << "Asset failed to save"; auto* fileIO = AZ::IO::LocalFileIO::GetInstance(); EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath)); } else { ADD_FAILURE() << "File stream not open"; } outFileStream.Close(); } TEST_F(ScriptCanvasTestFixture, SerializationLoadTest_Graph) { using namespace ScriptCanvas; ////////////////////////////////////////////////////////////////////////// // Make the graph. Graph* graph = nullptr; AZStd::unique_ptr<AZ::Entity> graphEntity = AZStd::make_unique<AZ::Entity>("Loaded Graph"); SystemRequestBus::BroadcastResult(graph, &SystemRequests::CreateGraphOnEntity, graphEntity.get()); auto* fileIO = AZ::IO::LocalFileIO::GetInstance(); ASSERT_NE(nullptr, fileIO); EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath)); // Load it AZ::IO::FileIOStream inFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeRead); if (inFileStream.IsOpen()) { // Serialize the graph entity back in. RuntimeAssetHandler runtimeAssetHandler; AZ::Data::Asset<RuntimeAsset> runtimeAsset; runtimeAsset.Create(AZ::Uuid::CreateRandom()); EXPECT_TRUE(runtimeAssetHandler.LoadAssetData(runtimeAsset, &inFileStream, {})); GraphData& assetGraphData = runtimeAsset.Get()->GetData().m_graphData; AZStd::unordered_map<AZ::EntityId, AZ::EntityId> idRemap; AZ::IdUtils::Remapper<AZ::EntityId>::GenerateNewIdsAndFixRefs(&assetGraphData, idRemap, m_serializeContext); graph->AddGraphData(assetGraphData); // Clear GraphData on asset to prevent it from deleting the graph data, the Graph component takes care of cleaning it up assetGraphData.Clear(); // Close the file inFileStream.Close(); // Initialize the entity graphEntity->Init(); ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, true); graphEntity->Activate(); ScriptCanvasEditor::TraceSuppressionBus::Broadcast(&ScriptCanvasEditor::TraceSuppressionRequests::SuppressPrintf, false); // Run the graph component graph = graphEntity->FindComponent<Graph>(); EXPECT_TRUE(graph != nullptr); // "Graph entity did not have the graph component."); ReportErrors(graph); const AZ::Vector3 allOne(1, 1, 1); const AZ::Vector3 allTwo(2, 2, 2); const AZ::Vector3 allThree(3, 3, 3); const AZ::Vector3 allFour(4, 4, 4); auto nodeIDs = graph->GetNodes(); EXPECT_EQ(9, nodeIDs.size()); // Graph result should be still 16 // Serialized graph has new remapped entity ids auto nodes = graph->GetNodes(); auto sumNodeIt = AZStd::find_if(nodes.begin(), nodes.end(), [](const AZ::EntityId& nodeId) -> bool { AZ::Entity* entity{}; AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId); return entity ? AZ::EntityUtils::FindFirstDerivedComponent<TestResult>(entity) ? true : false : false; }); EXPECT_NE(nodes.end(), sumNodeIt); TestResult* printNode = nullptr; SystemRequestBus::BroadcastResult(printNode, &SystemRequests::GetNode<TestResult>, *sumNodeIt); EXPECT_TRUE(printNode != nullptr); if (auto result = printNode->GetInput_UNIT_TEST<float>("Value")) { SC_EXPECT_FLOAT_EQ(*result, 16.0f); } else { ADD_FAILURE(); } EXPECT_TRUE(GraphHasVectorWithValue(*graph, allOne)); EXPECT_TRUE(GraphHasVectorWithValue(*graph, allTwo)); EXPECT_TRUE(GraphHasVectorWithValue(*graph, allThree)); EXPECT_FALSE(GraphHasVectorWithValue(*graph, allFour)); } else { ADD_FAILURE() << "in stream did not open"; } } TEST_F(ScriptCanvasTestFixture, SerializationLoadTest_RuntimeComponent) { using namespace ScriptCanvas; ////////////////////////////////////////////////////////////////////////// // Make the graph. AZStd::unique_ptr<AZ::Entity> executionEntity = AZStd::make_unique<AZ::Entity>("Loaded Graph"); auto executionComponent = executionEntity->CreateComponent<ScriptCanvas::RuntimeComponent>(); auto* fileIO = AZ::IO::LocalFileIO::GetInstance(); EXPECT_NE(nullptr, fileIO); EXPECT_TRUE(fileIO->Exists(k_tempCoreAssetPath)); // Load it AZ::IO::FileIOStream inFileStream(k_tempCoreAssetPath, AZ::IO::OpenMode::ModeRead); if (inFileStream.IsOpen()) { // Serialize the runtime asset back in. RuntimeAssetHandler runtimeAssetHandler; AZ::Data::Asset<ScriptCanvas::RuntimeAsset> runtimeAsset; runtimeAsset.Create(AZ::Uuid::CreateRandom()); EXPECT_TRUE(runtimeAssetHandler.LoadAssetData(runtimeAsset, &inFileStream, {})); runtimeAssetHandler.InitAsset(runtimeAsset, true, false); // Close the file inFileStream.Close(); // Initialize the entity executionComponent->SetRuntimeAsset(runtimeAsset); executionEntity->Init(); { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; executionEntity->Activate(); // Dispatch the AssetBus events to force onAssetReady event AZ::Data::AssetManager::Instance().DispatchEvents(); } EXPECT_FALSE(executionComponent->IsInErrorState()); const AZ::Vector3 allOne(1, 1, 1); const AZ::Vector3 allTwo(2, 2, 2); const AZ::Vector3 allThree(3, 3, 3); const AZ::Vector3 allFour(4, 4, 4); auto nodeIds = executionComponent->GetNodes(); EXPECT_EQ(9, nodeIds.size()); // Graph result should be still 16 // Serialized graph has new remapped entity ids auto sumNodeIt = AZStd::find_if(nodeIds.begin(), nodeIds.end(), [](const AZ::EntityId& nodeId) -> bool { AZ::Entity* entity{}; AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId); return entity ? AZ::EntityUtils::FindFirstDerivedComponent<TestResult>(entity) ? true : false : false; }); EXPECT_NE(nodeIds.end(), sumNodeIt); TestResult* printNode = nullptr; SystemRequestBus::BroadcastResult(printNode, &SystemRequests::GetNode<TestResult>, *sumNodeIt); EXPECT_TRUE(printNode != nullptr); if (auto result = printNode->GetInput_UNIT_TEST<float>("Value")) { SC_EXPECT_FLOAT_EQ(*result, 16.0f); } else { ADD_FAILURE(); } AZStd::vector<AZ::Vector3> vector3Results; for (auto nodeId : nodeIds) { AZ::Entity* entity{}; AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, nodeId); auto behaviorContextNode = entity ? AZ::EntityUtils::FindFirstDerivedComponent<Core::BehaviorContextObjectNode>(entity) : nullptr; auto rawVector3 = behaviorContextNode ? behaviorContextNode->GetInput_UNIT_TEST<AZ::Vector3>(PureData::k_setThis) : nullptr; if (rawVector3) { vector3Results.push_back(*rawVector3); } } auto allOneFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allOne](const AZ::Vector3& vector3Result) { return allOne == vector3Result; }); auto allTwoFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allTwo](const AZ::Vector3& vector3Result) { return allTwo == vector3Result; }); auto allThreeFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allThree](const AZ::Vector3& vector3Result) { return allThree == vector3Result; }); auto allFourFound = AZStd::any_of(vector3Results.begin(), vector3Results.end(), [allFour](const AZ::Vector3& vector3Result) { return allFour == vector3Result; }); EXPECT_TRUE(allOneFound); EXPECT_TRUE(allTwoFound); EXPECT_TRUE(allThreeFound); EXPECT_FALSE(allFourFound); } } TEST_F(ScriptCanvasTestFixture, Contracts) { using namespace ScriptCanvas; RegisterComponentDescriptor<ContractNode>(); ////////////////////////////////////////////////////////////////////////// // Make the graph. Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); // Make the nodes. // Start AZ::Entity* startEntity{ aznew AZ::Entity("Start") }; startEntity->Init(); AZ::EntityId startNode{ startEntity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, startNode, graphUniqueId, Nodes::Core::Start::TYPEINFO_Uuid()); // ContractNode 0 AZ::Entity* contract0Entity{ aznew AZ::Entity("Contract 0") }; contract0Entity->Init(); AZ::EntityId contract0Node{ contract0Entity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, contract0Node, graphUniqueId, ContractNode::TYPEINFO_Uuid()); // ContractNode 1 AZ::Entity* contract1Entity{ aznew AZ::Entity("Contract 1") }; contract1Entity->Init(); AZ::EntityId contract1Node{ contract1Entity->GetId() }; SystemRequestBus::Broadcast(&SystemRequests::CreateNodeOnEntity, contract1Node, graphUniqueId, ContractNode::TYPEINFO_Uuid()); // invalid { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Out"))); EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In"))); EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Get String"))); EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Get String"))); EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("In"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"))); EXPECT_FALSE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"))); EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set String"))); EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set Number"))); EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get Number"))); EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Set String"))); EXPECT_FALSE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In"))); } // valid EXPECT_TRUE(graph->Connect(startNode, AZ::EntityUtils::FindFirstDerivedComponent<Node>(startEntity)->GetSlotId("Out"), contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In"))); EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set String"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get String"))); EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("In"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Out"))); EXPECT_TRUE(graph->Connect(contract0Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract0Entity)->GetSlotId("Set Number"), contract1Node, AZ::EntityUtils::FindFirstDerivedComponent<Node>(contract1Entity)->GetSlotId("Get Number"))); // Execute it graph->GetEntity()->Activate(); ReportErrors(graph); graph->GetEntity()->Deactivate(); delete graph->GetEntity(); } #if defined (SCRIPTCANVAS_ERRORS_ENABLED) TEST_F(ScriptCanvasTestFixture, Error) { using namespace ScriptCanvas; RegisterComponentDescriptor<UnitTestErrorNode>(); RegisterComponentDescriptor<InfiniteLoopNode>(); Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); UnitTestEventsHandler unitTestHandler; unitTestHandler.BusConnect(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZStd::string description = "Unit test error!"; AZ::EntityId stringNodeID; CreateDataNode(graphUniqueId, description, stringNodeID); AZStd::string sideFX1 = "Side FX 1"; AZ::EntityId sideFX1NodeID; CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID); AZ::EntityId errorNodeID; CreateTestNode<UnitTestErrorNode>(graphUniqueId, errorNodeID); AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0")); EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In")); EXPECT_TRUE(Connect(*graph, errorNodeID, "Out", sideEffectID, "In")); // test to make sure the graph received an error { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graph->GetEntity()->Activate(); } const bool expectErrors = true; const bool expectIrrecoverableErrors = true; ReportErrors(graph, expectErrors, expectIrrecoverableErrors); EXPECT_EQ(description, graph->GetLastErrorDescription()); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 0); graph->GetEntity()->Deactivate(); delete graph->GetEntity(); } TEST_F(ScriptCanvasTestFixture, ErrorHandled) { using namespace ScriptCanvas; RegisterComponentDescriptor<UnitTestErrorNode>(); Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); UnitTestEventsHandler unitTestHandler; unitTestHandler.BusConnect(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZStd::string description = "Unit test error!"; AZ::EntityId stringNodeID; CreateDataNode(graphUniqueId, description, stringNodeID); AZStd::string sideFX1 = "Side FX 1"; AZ::EntityId sideFX1NodeID; CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID); AZStd::string sideFX2 = "Side FX 2"; AZ::EntityId sideFX2NodeID; CreateDataNode(graphUniqueId, sideFX2, sideFX2NodeID); AZ::EntityId errorNodeID; CreateTestNode<UnitTestErrorNode>(graphUniqueId, errorNodeID); AZ::EntityId sideEffectID1 = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); AZ::EntityId sideEffectID2 = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); AZ::EntityId errorHandlerID; CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID); EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID1, "String: 0")); EXPECT_TRUE(Connect(*graph, sideFX2NodeID, "Get", sideEffectID2, "String: 0")); EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In")); EXPECT_TRUE(Connect(*graph, errorNodeID, "Out", sideEffectID1, "In")); EXPECT_TRUE(Connect(*graph, errorHandlerID, "Source", errorNodeID, "This")); EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectID2, "In")); { ScriptCanvasEditor::ScopedOutputSuppression supressOutput; // temporarily suppress the output, since we don't fully support error handling correction, yet graph->GetEntity()->Activate(); } ReportErrors(graph); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 0); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX2), 1); delete graph->GetEntity(); } TEST_F(ScriptCanvasTestFixture, ErrorNode) { using namespace ScriptCanvas; Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); UnitTestEventsHandler unitTestHandler; unitTestHandler.BusConnect(); // Start AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZStd::string description = "Test Error Report"; AZ::EntityId stringNodeID; CreateDataNode(graphUniqueId, description, stringNodeID); AZStd::string sideFX1 = "Side FX 1"; AZ::EntityId sideFX1NodeID; CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID); AZ::EntityId errorNodeID; CreateTestNode<Nodes::Core::Error>(graphUniqueId, errorNodeID); AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); EXPECT_TRUE(Connect(*graph, startID, "Out", sideEffectID, "In")); EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0")); EXPECT_TRUE(Connect(*graph, sideEffectID, "Out", errorNodeID, "In")); EXPECT_TRUE(Connect(*graph, stringNodeID, "Get", errorNodeID, "Description")); // test to make sure the graph received an error { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graph->GetEntity()->Activate(); } const bool expectErrors = true; const bool expectIrrecoverableErrors = true; ReportErrors(graph, expectErrors, expectIrrecoverableErrors); EXPECT_EQ(description, graph->GetLastErrorDescription()); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1); graph->GetEntity()->Deactivate(); // test to make sure the graph did to retry execution graph->GetEntity()->Activate(); ReportErrors(graph, expectErrors, expectIrrecoverableErrors); // if the graph was allowed to execute, the side effect counter should be higher EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1); delete graph->GetEntity(); } TEST_F(ScriptCanvasTestFixture, ErrorNodeHandled) { using namespace ScriptCanvas; Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); UnitTestEventsHandler unitTestHandler; unitTestHandler.BusConnect(); AZStd::string description = "Test Error Report"; AZ::EntityId stringNodeID; CreateDataNode(graphUniqueId, description, stringNodeID); AZStd::string sideFX1 = "Side FX 1"; AZ::EntityId sideFX1NodeID; CreateDataNode(graphUniqueId, sideFX1, sideFX1NodeID); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId errorNodeID; CreateTestNode<Nodes::Core::Error>(graphUniqueId, errorNodeID); AZ::EntityId errorHandlerID; CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID); AZ::EntityId sideEffectID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); EXPECT_TRUE(Connect(*graph, startID, "Out", errorNodeID, "In")); EXPECT_TRUE(Connect(*graph, errorHandlerID, "Source", errorNodeID, "This")); EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectID, "In")); EXPECT_TRUE(Connect(*graph, sideFX1NodeID, "Get", sideEffectID, "String: 0")); { ScriptCanvasEditor::ScopedOutputSuppression supressOutput; // temporarily suppress the output, since we don't fully support error handling correction, yet graph->GetEntity()->Activate(); } ReportErrors(graph); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 1); graph->GetEntity()->Deactivate(); graph->GetEntity()->Activate(); ReportErrors(graph); EXPECT_EQ(unitTestHandler.SideEffectCount(sideFX1), 2); delete graph->GetEntity(); } TEST_F(ScriptCanvasTestFixture, InfiniteLoopDetected) { using namespace ScriptCanvas; RegisterComponentDescriptor<InfiniteLoopNode>(); Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); UnitTestEventsHandler unitTestHandler; unitTestHandler.BusConnect(); AZStd::string sideFXpass = "Side FX Infinite Loop Error Handled"; AZ::EntityId sideFXpassNodeID; CreateDataNode(graphUniqueId, sideFXpass, sideFXpassNodeID); AZStd::string sideFXfail = "Side FX Infinite Loop Node Failed"; AZ::EntityId sideFXfailNodeID; CreateDataNode(graphUniqueId, sideFXfail, sideFXfailNodeID); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId infiniteLoopNodeID; CreateTestNode<InfiniteLoopNode>(graphUniqueId, infiniteLoopNodeID); AZ::EntityId errorHandlerID; CreateTestNode<Nodes::Core::ErrorHandler>(graphUniqueId, errorHandlerID); AZ::EntityId sideEffectPassID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); AZ::EntityId sideEffectFailID = CreateClassFunctionNode(graphUniqueId, "UnitTestEventsBus", "SideEffect"); EXPECT_TRUE(Connect(*graph, sideFXpassNodeID, "Get", sideEffectPassID, "String: 0")); EXPECT_TRUE(Connect(*graph, sideFXfailNodeID, "Get", sideEffectFailID, "String: 0")); EXPECT_TRUE(Connect(*graph, startID, "Out", infiniteLoopNodeID, "In")); EXPECT_TRUE(Connect(*graph, infiniteLoopNodeID, "In", infiniteLoopNodeID, "Before Infinity")); EXPECT_TRUE(Connect(*graph, infiniteLoopNodeID, "After Infinity", sideEffectFailID, "In")); EXPECT_TRUE(Connect(*graph, errorHandlerID, "Out", sideEffectPassID, "In")); { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graph->GetEntity()->Activate(); } const bool expectError = true; const bool expectIrrecoverableError = true; ReportErrors(graph, expectError, expectIrrecoverableError); EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXpass)); EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXfail)); graph->GetEntity()->Deactivate(); graph->GetEntity()->Activate(); ReportErrors(graph, expectError, expectIrrecoverableError); EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXpass)); EXPECT_EQ(0, unitTestHandler.SideEffectCount(sideFXfail)); delete graph->GetEntity(); } #endif // SCRIPTCANAS_ERRORS_ENABLED TEST_F(ScriptCanvasTestFixture, BinaryOperationTest) { using namespace ScriptCanvas::Nodes; using namespace ScriptCanvas::Nodes::Comparison; TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); BinaryOpTest<EqualTo>(1, 1, true); BinaryOpTest<EqualTo>(1, 0, false); BinaryOpTest<EqualTo>(0, 1, false); BinaryOpTest<EqualTo>(0, 0, true); BinaryOpTest<NotEqualTo>(1, 1, false); BinaryOpTest<NotEqualTo>(1, 0, true); BinaryOpTest<NotEqualTo>(0, 1, true); BinaryOpTest<NotEqualTo>(0, 0, false); BinaryOpTest<Greater>(1, 1, false); BinaryOpTest<Greater>(1, 0, true); BinaryOpTest<Greater>(0, 1, false); BinaryOpTest<Greater>(0, 0, false); BinaryOpTest<GreaterEqual>(1, 1, true); BinaryOpTest<GreaterEqual>(1, 0, true); BinaryOpTest<GreaterEqual>(0, 1, false); BinaryOpTest<GreaterEqual>(0, 0, true); BinaryOpTest<Less>(1, 1, false); BinaryOpTest<Less>(1, 0, false); BinaryOpTest<Less>(0, 1, true); BinaryOpTest<Less>(0, 0, false); BinaryOpTest<LessEqual>(1, 1, true); BinaryOpTest<LessEqual>(1, 0, false); BinaryOpTest<LessEqual>(0, 1, true); BinaryOpTest<LessEqual>(0, 0, true); BinaryOpTest<EqualTo>(true, true, true); BinaryOpTest<EqualTo>(true, false, false); BinaryOpTest<EqualTo>(false, true, false); BinaryOpTest<EqualTo>(false, false, true); BinaryOpTest<NotEqualTo>(true, true, false); BinaryOpTest<NotEqualTo>(true, false, true); BinaryOpTest<NotEqualTo>(false, true, true); BinaryOpTest<NotEqualTo>(false, false, false); AZStd::string string0("a string"); AZStd::string string1("b string"); BinaryOpTest<EqualTo>(string1, string1, true); BinaryOpTest<EqualTo>(string1, string0, false); BinaryOpTest<EqualTo>(string0, string1, false); BinaryOpTest<EqualTo>(string0, string0, true); BinaryOpTest<NotEqualTo>(string1, string1, false); BinaryOpTest<NotEqualTo>(string1, string0, true); BinaryOpTest<NotEqualTo>(string0, string1, true); BinaryOpTest<NotEqualTo>(string0, string0, false); BinaryOpTest<Greater>(string1, string1, false); BinaryOpTest<Greater>(string1, string0, true); BinaryOpTest<Greater>(string0, string1, false); BinaryOpTest<Greater>(string0, string0, false); BinaryOpTest<GreaterEqual>(string1, string1, true); BinaryOpTest<GreaterEqual>(string1, string0, true); BinaryOpTest<GreaterEqual>(string0, string1, false); BinaryOpTest<GreaterEqual>(string0, string0, true); BinaryOpTest<Less>(string1, string1, false); BinaryOpTest<Less>(string1, string0, false); BinaryOpTest<Less>(string0, string1, true); BinaryOpTest<Less>(string0, string0, false); BinaryOpTest<LessEqual>(string1, string1, true); BinaryOpTest<LessEqual>(string1, string0, false); BinaryOpTest<LessEqual>(string0, string1, true); BinaryOpTest<LessEqual>(string0, string0, true); const AZ::Vector3 vectorOne(1.0f, 1.0f, 1.0f); const AZ::Vector3 vectorZero(0.0f, 0.0f, 0.0f); BinaryOpTest<EqualTo>(vectorOne, vectorOne, true); BinaryOpTest<EqualTo>(vectorOne, vectorZero, false); BinaryOpTest<EqualTo>(vectorZero, vectorOne, false); BinaryOpTest<EqualTo>(vectorZero, vectorZero, true); BinaryOpTest<NotEqualTo>(vectorOne, vectorOne, false); BinaryOpTest<NotEqualTo>(vectorOne, vectorZero, true); BinaryOpTest<NotEqualTo>(vectorZero, vectorOne, true); BinaryOpTest<NotEqualTo>(vectorZero, vectorZero, false); const TestBehaviorContextObject zero(0); const TestBehaviorContextObject one(1); const TestBehaviorContextObject otherOne(1); BinaryOpTest<EqualTo>(one, one, true); BinaryOpTest<EqualTo>(one, zero, false); BinaryOpTest<EqualTo>(zero, one, false); BinaryOpTest<EqualTo>(zero, zero, true); BinaryOpTest<NotEqualTo>(one, one, false); BinaryOpTest<NotEqualTo>(one, zero, true); BinaryOpTest<NotEqualTo>(zero, one, true); BinaryOpTest<NotEqualTo>(zero, zero, false); BinaryOpTest<Greater>(one, one, false); BinaryOpTest<Greater>(one, zero, true); BinaryOpTest<Greater>(zero, one, false); BinaryOpTest<Greater>(zero, zero, false); BinaryOpTest<GreaterEqual>(one, one, true); BinaryOpTest<GreaterEqual>(one, zero, true); BinaryOpTest<GreaterEqual>(zero, one, false); BinaryOpTest<GreaterEqual>(zero, zero, true); BinaryOpTest<Less>(one, one, false); BinaryOpTest<Less>(one, zero, false); BinaryOpTest<Less>(zero, one, true); BinaryOpTest<Less>(zero, zero, false); BinaryOpTest<LessEqual>(one, one, true); BinaryOpTest<LessEqual>(one, zero, false); BinaryOpTest<LessEqual>(zero, one, true); BinaryOpTest<LessEqual>(zero, zero, true); BinaryOpTest<EqualTo>(one, otherOne, true); BinaryOpTest<EqualTo>(otherOne, one, true); BinaryOpTest<NotEqualTo>(one, otherOne, false); BinaryOpTest<NotEqualTo>(otherOne, one, false); BinaryOpTest<Greater>(one, otherOne, false); BinaryOpTest<Greater>(otherOne, one, false); BinaryOpTest<GreaterEqual>(one, otherOne, true); BinaryOpTest<GreaterEqual>(otherOne, one, true); BinaryOpTest<Less>(one, otherOne, false); BinaryOpTest<Less>(otherOne, one, false); BinaryOpTest<LessEqual>(one, otherOne, true); BinaryOpTest<LessEqual>(otherOne, one, true); // force failures, to verify crash proofiness BinaryOpTest<EqualTo>(one, zero, false, true); BinaryOpTest<NotEqualTo>(one, zero, true, true); BinaryOpTest<Greater>(one, zero, true, true); BinaryOpTest<GreaterEqual>(one, zero, true, true); BinaryOpTest<Less>(one, zero, false, true); BinaryOpTest<LessEqual>(one, zero, false, true); m_serializeContext->EnableRemoveReflection(); m_behaviorContext->EnableRemoveReflection(); TestBehaviorContextObject::Reflect(m_serializeContext); TestBehaviorContextObject::Reflect(m_behaviorContext); m_serializeContext->DisableRemoveReflection(); m_behaviorContext->DisableRemoveReflection(); } TEST_F(ScriptCanvasTestFixture, EntityRefTest) { using namespace ScriptCanvas; using namespace ScriptCanvas::Nodes; // Fake "world" entities AZ::Entity first("First"); first.CreateComponent<ScriptCanvasTests::TestComponent>(); first.Init(); first.Activate(); AZ::Entity second("Second"); second.CreateComponent<ScriptCanvasTests::TestComponent>(); second.Init(); second.Activate(); // Script Canvas Graph Graph* graph = nullptr; SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); m_entityContext.AddEntity(first.GetId()); m_entityContext.AddEntity(second.GetId()); m_entityContext.AddEntity(graph->GetEntityId()); graph->GetEntity()->SetName("Graph Owner Entity"); graph->GetEntity()->CreateComponent<ScriptCanvasTests::TestComponent>(); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityId = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); // EntityRef node to some specific entity #1 AZ::EntityId selfEntityIdNode; auto selfEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, selfEntityIdNode); selfEntityRef->SetEntityRef(first.GetId()); // EntityRef node to some specific entity #2 AZ::EntityId otherEntityIdNode; auto otherEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, otherEntityIdNode); otherEntityRef->SetEntityRef(second.GetId()); // Explicitly set an EntityRef node with this graph's entity Id. AZ::EntityId graphEntityIdNode; auto graphEntityRef = CreateTestNode<Nodes::Entity::EntityRef>(graphUniqueId, graphEntityIdNode); graphEntityRef->SetEntityRef(graph->GetEntity()->GetId()); // First test: directly set an entity Id on the EntityID: 0 slot AZ::EntityId eventAid; Nodes::Core::Method* nodeA = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventAid); nodeA->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent"); if (auto entityId = nodeA->ModInput_UNIT_TEST<AZ::EntityId>("EntityID: 0")) { *entityId = first.GetId(); } // Second test: Will connect the slot to an EntityRef node AZ::EntityId eventBid; Nodes::Core::Method* nodeB = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventBid); nodeB->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent"); // Third test: Set the slot's EntityId: 0 to GraphOwnerId, this should result in the same Id as graph->GetEntityId() AZ::EntityId eventCid; Nodes::Core::Method* nodeC = CreateTestNode<Nodes::Core::Method>(graphUniqueId, eventCid); nodeC->InitializeEvent({ {} }, "EntityRefTestEventBus", "TestEvent"); if (auto entityId = nodeC->ModInput_UNIT_TEST<AZ::EntityId>("EntityID: 0")) { *entityId = ScriptCanvas::GraphOwnerId; } // True AZ::EntityId trueNodeId; CreateDataNode<Data::BooleanType>(graphUniqueId, true, trueNodeId); // False AZ::EntityId falseNodeId; CreateDataNode<Data::BooleanType>(graphUniqueId, false, falseNodeId); // Start -> TestEvent // O EntityId: 0 (not connected, it was set directly on the slot) // EntityRef: first -O EntityId: 1 // False -O Boolean: 2 EXPECT_TRUE(Connect(*graph, startID, "Out", eventAid, "In")); EXPECT_TRUE(Connect(*graph, eventAid, "EntityID: 1", selfEntityIdNode, "Get")); EXPECT_TRUE(Connect(*graph, eventAid, "Boolean: 2", falseNodeId, "Get")); // Start -> TestEvent // EntityRef: second -O EntityId: 0 // EntityRef: second -O EntityId: 1 // False -O Boolean: 2 EXPECT_TRUE(Connect(*graph, startID, "Out", eventBid, "In")); EXPECT_TRUE(Connect(*graph, eventBid, "EntityID: 0", otherEntityIdNode, "Get")); EXPECT_TRUE(Connect(*graph, eventBid, "EntityID: 1", otherEntityIdNode, "Get")); EXPECT_TRUE(Connect(*graph, eventBid, "Boolean: 2", falseNodeId, "Get")); // Start -> TestEvent // -O EntityId: 0 (not connected, slot is set to GraphOwnerId) // graphEntityIdNode -O EntityId: 1 // True -O Boolean: 2 EXPECT_TRUE(Connect(*graph, startID, "Out", eventCid, "In")); EXPECT_TRUE(Connect(*graph, eventCid, "EntityID: 1", graphEntityIdNode, "Get")); EXPECT_TRUE(Connect(*graph, eventCid, "Boolean: 2", trueNodeId, "Get")); // Execute the graph { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graph->GetEntity()->Activate(); } ReportErrors(graph); delete graph->GetEntity(); } const int k_executionCount = 998; TEST_F(ScriptCanvasTestFixture, ExecutionLength) { using namespace ScriptCanvas; Graph* graph(nullptr); SystemRequestBus::BroadcastResult(graph, &SystemRequests::MakeGraph); EXPECT_TRUE(graph != nullptr); graph->GetEntity()->Init(); const AZ::EntityId& graphEntityID = graph->GetEntityId(); const AZ::EntityId& graphUniqueId = graph->GetUniqueId(); AZ::EntityId startID; CreateTestNode<Nodes::Core::Start>(graphUniqueId, startID); AZ::EntityId previousID = startID; for (int i = 0; i < k_executionCount; ++i) { AZ::EntityId printNodeID; TestResult* printNode = CreateTestNode<TestResult>(graphUniqueId, printNodeID); printNode->SetInput_UNIT_TEST<int>("Value", i); EXPECT_TRUE(Connect(*graph, previousID, "Out", printNodeID, "In")); previousID = printNodeID; } AZ::Entity* graphEntity = graph->GetEntity(); { ScriptCanvasEditor::ScopedOutputSuppression suppressOutput; graphEntity->Activate(); } ReportErrors(graph); graphEntity->Deactivate(); delete graphEntity; } TEST_F(ScriptCanvasTestFixture, AnyNode) { RunUnitTestGraph("LY_SC_UnitTest_Any"); }
75,794
24,105
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int t; cin >> t; while(t--){ int n, x; cin >> n >> x; int cnt = 0; for(int i=1; i<n; ++i){ int a, b; cin >> a >> b; if(a == x or b == x) cnt++; } if(cnt <= 1) cout << "Ayush" << endl; else{ int till = n-2; if(till%2) cout << "Ashish" << endl; else cout << "Ayush" << endl; } } return 0; }
565
204
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2021 www.open3d.org // // 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 "open3d/visualization/gui/Button.h" #include <imgui.h> #include <cmath> #include <string> #include "open3d/visualization/gui/Theme.h" #include "open3d/visualization/gui/Util.h" namespace open3d { namespace visualization { namespace gui { namespace { static int g_next_button_id = 1; } // namespace struct Button::Impl { std::string id_; std::string title_; std::shared_ptr<UIImage> image_; float padding_horizontal_em_ = 0.5f; float padding_vertical_em_ = 0.5f; bool is_toggleable_ = false; bool is_on_ = false; std::function<void()> on_clicked_; }; Button::Button(const char* title) : impl_(new Button::Impl()) { impl_->id_ = std::string("##button") + std::to_string(g_next_button_id++); impl_->title_ = title; } Button::Button(std::shared_ptr<UIImage> image) : impl_(new Button::Impl()) { impl_->image_ = image; } Button::~Button() {} const char* Button::GetText() const { return impl_->title_.c_str(); } void Button::SetText(const char* text) { impl_->title_ = text; } float Button::GetHorizontalPaddingEm() const { return impl_->padding_horizontal_em_; } float Button::GetVerticalPaddingEm() const { return impl_->padding_vertical_em_; } void Button::SetPaddingEm(float horiz_ems, float vert_ems) { impl_->padding_horizontal_em_ = horiz_ems; impl_->padding_vertical_em_ = vert_ems; } bool Button::GetIsToggleable() const { return impl_->is_toggleable_; } void Button::SetToggleable(bool toggles) { impl_->is_toggleable_ = toggles; } bool Button::GetIsOn() const { return impl_->is_on_; } void Button::SetOn(bool is_on) { if (impl_->is_toggleable_) { impl_->is_on_ = is_on; } } void Button::SetOnClicked(std::function<void()> on_clicked) { impl_->on_clicked_ = on_clicked; } Size Button::CalcPreferredSize(const LayoutContext& context, const Constraints& constraints) const { auto em = float(context.theme.font_size); auto padding_horiz = int(std::ceil(impl_->padding_horizontal_em_ * em)); auto padding_vert = int(std::ceil(impl_->padding_vertical_em_ * em)); if (impl_->image_) { auto size = impl_->image_->CalcPreferredSize(context, constraints); return Size(size.width + 2 * padding_horiz, size.height + 2 * padding_vert); } else { auto font = ImGui::GetFont(); auto imguiVertPadding = ImGui::GetTextLineHeightWithSpacing() - ImGui::GetTextLineHeight(); auto size = font->CalcTextSizeA(float(context.theme.font_size), float(constraints.width), 10000, impl_->title_.c_str()); // When ImGUI draws text, it draws text in a box of height // font_size + spacing. The padding on the bottom is essentially the // descender height, and the box height ends up giving a visual padding // of descender_height on the top and bottom. So while we only need to // 1 * imguiVertPadding on the bottom, we need to add 2x on the sides. // Note that padding of 0 doesn't actually produce a padding of zero, // because that would look horrible. (And also because if we do that, // ImGUI will position the text so that the descender is cut off, // because it is assuming that it gets a little extra on the bottom. // This looks really bad...) return Size( int(std::ceil(size.x + 2.0f + imguiVertPadding)) + 2 * padding_horiz, int(std::ceil(ImGui::GetTextLineHeight() + imguiVertPadding)) + 2 * padding_vert); } } Widget::DrawResult Button::Draw(const DrawContext& context) { auto& frame = GetFrame(); auto result = Widget::DrawResult::NONE; ImGui::SetCursorScreenPos(ImVec2(float(frame.x), float(frame.y))); bool was_on = impl_->is_on_; if (was_on) { ImGui::PushStyleColor(ImGuiCol_Text, colorToImgui(context.theme.button_on_text_color)); ImGui::PushStyleColor(ImGuiCol_Button, colorToImgui(context.theme.button_on_color)); ImGui::PushStyleColor( ImGuiCol_ButtonHovered, colorToImgui(context.theme.button_on_hover_color)); ImGui::PushStyleColor( ImGuiCol_ButtonActive, colorToImgui(context.theme.button_on_active_color)); } DrawImGuiPushEnabledState(); bool pressed = false; if (impl_->image_) { auto params = impl_->image_->CalcDrawParams(context.renderer, frame); ImTextureID image_id = reinterpret_cast<ImTextureID>(params.texture.GetId()); pressed = ImGui::ImageButton( image_id, ImVec2(params.width, params.height), ImVec2(params.u0, params.v0), ImVec2(params.u1, params.v1)); } else { pressed = ImGui::Button( (impl_->title_ + impl_->id_).c_str(), ImVec2(float(GetFrame().width), float(GetFrame().height))); } if (pressed) { if (impl_->is_toggleable_) { impl_->is_on_ = !impl_->is_on_; } if (impl_->on_clicked_) { impl_->on_clicked_(); } result = Widget::DrawResult::REDRAW; } DrawImGuiPopEnabledState(); DrawImGuiTooltip(); if (was_on) { ImGui::PopStyleColor(4); } return result; } } // namespace gui } // namespace visualization } // namespace open3d
7,030
2,160
#include "../includes/SymtabEntry.h" #include <cstring> SymtabEntry::SymtabEntry(Information* info) { this->info = info; this->next = NULL; } SymtabEntry::~SymtabEntry() { } SymtabEntry* SymtabEntry::getNext() { return this->next; } void SymtabEntry::setNext(SymtabEntry* next) { this->next = next; } Information* SymtabEntry::getInfo() { return this->info; }
370
139
#if defined(_MSC_VER) && !defined(NDEBUG) #define DISABLE_WARNING_PUSH __pragma(warning(push)) #define DISABLE_WARNING_PUSH_ALL __pragma(warning(push, 0)) #define DISABLE_WARNING_POP __pragma(warning(pop)) #define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber)) #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(4100) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505) #define DISABLE_WARNING_PRAGMAS #define DISABLE_WARNING_SIGN_CONVERSION #define DISABLE_WARNING_OLD_STYLE_CAST #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION #define DISABLE_WARNING_SHORTEN_64_TO_32 #define DISABLE_WARNING_MISSING_PROTOTYPES #define DISABLE_WARNING_SHADOW #define DISABLE_WARNING_ENUM_ENUM_CONVERSION #define DISABLE_WARNING_USELESS_CAST #define DISABLE_WARNING_PEDANTIC #define DISABLE_WARNING_IGNORED_QUALIFIERS #define DISABLE_WARNING_REORDER #define DISABLE_WARNING_NON_VIRTUAL_DTOR #elif (defined(__GNUC__) || defined(__clang__)) && !defined(NDEBUG) #define DO_PRAGMA(X) _Pragma(#X) #define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) #define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) #define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) #define DISABLE_WARNING_PRAGMAS DISABLE_WARNING(-Wpragmas) #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(-Wunused-parameter) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function) #define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING(-Wsign-conversion) #define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING(-Wold-style-cast) #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING(-Wimplicit-int-conversion) #define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING(-Wshorten-64-to-32) #define DISABLE_WARNING_MISSING_PROTOTYPES DISABLE_WARNING(-Wmissing-prototypes) #define DISABLE_WARNING_SHADOW DISABLE_WARNING(-Wshadow) #define DISABLE_WARNING_ENUM_ENUM_CONVERSION DISABLE_WARNING(-Wenum-enum-conversion) #define DISABLE_WARNING_USELESS_CAST DISABLE_WARNING(-Wuseless-cast) #define DISABLE_WARNING_PEDANTIC DISABLE_WARNING(-Wpedantic) #define DISABLE_WARNING_IGNORED_QUALIFIERS DISABLE_WARNING(-Wignored-qualifiers) #define DISABLE_WARNING_REORDER DISABLE_WARNING(-Wreorder) #define DISABLE_WARNING_NON_VIRTUAL_DTOR DISABLE_WARNING(-Wnon-virtual-dtor) #define DISABLE_WARNING_PUSH_ALL \ DISABLE_WARNING_PRAGMAS \ DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER \ DISABLE_WARNING_UNREFERENCED_FUNCTION \ DISABLE_WARNING_SIGN_CONVERSION \ DISABLE_WARNING_OLD_STYLE_CAST \ DISABLE_WARNING_IMPLICIT_INT_CONVERSION \ DISABLE_WARNING_SHORTEN_64_TO_32 \ DISABLE_WARNING_MISSING_PROTOTYPES \ DISABLE_WARNING_SHADOW \ DISABLE_WARNING_ENUM_ENUM_CONVERSION \ DISABLE_WARNING_USELESS_CAST \ DISABLE_WARNING_PEDANTIC \ DISABLE_WARNING_IGNORED_QUALIFIERS \ DISABLE_WARNING_REORDER \ DISABLE_WARNING_NON_VIRTUAL_DTOR #else #define DISABLE_WARNING_PUSH_ALL #define DISABLE_WARNING_PUSH #define DISABLE_WARNING_POP #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER #define DISABLE_WARNING_UNREFERENCED_FUNCTION #define DISABLE_WARNING_PRAGMAS #define DISABLE_WARNING_SIGN_CONVERSION #define DISABLE_WARNING_OLD_STYLE_CAST #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION #define DISABLE_WARNING_SHORTEN_64_TO_32 #define DISABLE_WARNING_MISSING_PROTOTYPES #define DISABLE_WARNING_SHADOW #define DISABLE_WARNING_ENUM_ENUM_CONVERSION #define DISABLE_WARNING_USELESS_CAST #define DISABLE_WARNING_PEDANTIC #define DISABLE_WARNING_IGNORED_QUALIFIERS #define DISABLE_WARNING_REORDER #define DISABLE_WARNING_NON_VIRTUAL_DTOR #endif
4,625
1,622
#ifndef __MATRIX_OPERATIONS_H_ #define __MATRIX_OPERATIONS_H_ #include "Matrix.hh" #include "PhaseVector.hh" #include "Bunch.hh" namespace OrbitUtils{ /** The collection of the static methods for matrices. */ class MatrixOperations{ public: /** Inverts the 2D array as a matrix. */ static int invert(double **a, int n); /** Inversts the matrix in place. */ static int invert(Matrix* matrix); /** Multiplies a vector with the transposed matrix. */ static int mult(PhaseVector* v, Matrix* mtrx, PhaseVector* v_res); /** Multiplies a vector with the matrix. */ static int mult(Matrix* mtrx, PhaseVector* v, PhaseVector* v_res); /** Calculates determinant of the matrix. */ static int det(Matrix* mtrx_in, double& det); /** Tracks the bunch through the transport matrix. The matrix should be 6x6 or 7x7. */ static void track(Bunch* bunch,Matrix* mtrx); }; }; #endif
934
365
// license:BSD-3-Clause // copyright-holders:Andrew Gardner, Couriersud #include "netlist/devices/net_lib.h" #ifdef NLBASE_H_ #error Somehow nl_base.h made it into the include chain. #endif #define USE_FRONTIERS 1 /* if we use frontiers, use fixed STV for smaller matrix sizes */ #if (USE_FRONTIERS) #define USE_FIXED_STV 1 #else #define USE_FIXED_STV 0 #endif /* * Schematic errors: * * The kungfu master schematics differ from the kidnik schematics in wiring * D4, D5 and Q4 with other components. The manual corrections to the * kungfu master schematics make sense and thus are used here. * * opamp XU1.B according to schematics has no feedback loop between output and * inputs. The arrangement of components in the schematic however indicate that * this is not the case and indeed a connection exists. This results in sounds * at output XU1.14 to contain more detail. * * You can observe sounds at XU1.14 by doing * * NL_LOGS=XU1.14 ./mame kidniki * nlwav -o x.wav log_XU1.14.log * play x.wav * * VERIFICATION NEEDED: Are D4 and D5 Cathodes connected? * * This has quite some impact on the drums. * */ #define FIX_SCHEMATIC_ERRORS (1) #define D4_AND_D5_CONNECTED (1) /* On M62 boards with pcb pictures available * D6 is missing, although the pcb print exists. * We are replacing this with a 10m Resistor. */ #define D6_EXISTS (0) /* * J4 connects channel C either to sound_ic or sound. * * 1: Connect C to channel to sound_ic * */ #define J4 (1) /* ---------------------------------------------------------------------------- * Library section header START * ---------------------------------------------------------------------------*/ #ifndef __PLIB_PREPROCESSOR__ #endif /* ---------------------------------------------------------------------------- * Library section header END * ---------------------------------------------------------------------------*/ /* ---------------------------------------------------------------------------- * Kidniki schematics * ---------------------------------------------------------------------------*/ static NETLIST_START(kidniki_schematics) // EESCHEMA NETLIST VERSION 1.1 (SPICE FORMAT) CREATION DATE: SAT 06 JUN 2015 01:06:26 PM CEST // TO EXCLUDE A COMPONENT FROM THE SPICE NETLIST ADD [SPICE_NETLIST_ENABLED] USER FIELD SET TO: N // TO REORDER THE COMPONENT SPICE NODE SEQUENCE ADD [SPICE_NODE_SEQUENCE] USER FIELD AND DEFINE SEQUENCE: 2,1,0 // SHEET NAME:/ // IGNORED O_AUDIO0: O_AUDIO0 49 0 // .END #if FIX_SCHEMATIC_ERRORS NET_C(XU1.7, C40.1) #endif CAP(C200, CAP_N(100)) CAP(C28, CAP_U(1)) CAP(C31, CAP_N(470)) CAP(C32, CAP_N(3.3)) CAP(C33, CAP_U(1)) CAP(C34, CAP_N(1)) CAP(C35, CAP_N(1)) CAP(C36, CAP_N(6.8)) CAP(C37, CAP_N(22)) CAP(C38, CAP_N(1)) CAP(C39, CAP_N(1)) CAP(C40, CAP_P(12)) CAP(C41, CAP_U(1)) CAP(C42, CAP_N(1.2)) CAP(C43, CAP_N(1.2)) CAP(C44, CAP_U(1)) CAP(C45, CAP_N(22)) CAP(C47, CAP_U(1)) CAP(C48, CAP_N(470)) CAP(C49, CAP_N(3.3)) CAP(C50, CAP_N(22)) CAP(C51, CAP_N(22)) CAP(C52, CAP_N(27)) CAP(C53, CAP_N(27)) CAP(C56, CAP_N(6.8)) CAP(C57, CAP_N(6.8)) CAP(C59, CAP_N(6.8)) CAP(C60, CAP_N(22)) CAP(C61, CAP_N(22)) CAP(C62, CAP_N(6.8)) CAP(C63, CAP_N(1)) CAP(C64, CAP_N(68)) CAP(C65, CAP_N(68)) CAP(C66, CAP_N(68)) CAP(C67, CAP_N(15)) CAP(C68, CAP_N(15)) CAP(C69, CAP_N(10)) CAP(C70, CAP_N(22)) CAP(C72, CAP_N(12)) CAP(C73, CAP_N(10)) CAP(C76, CAP_N(68)) CAP(C77, CAP_N(12)) DIODE(D3, "1S1588") DIODE(D4, "1S1588") DIODE(D5, "1S1588") POT(RV1, RES_K(50)) QBJT_EB(Q10, "2SC945") QBJT_EB(Q3, "2SC945") QBJT_EB(Q4, "2SC945") QBJT_EB(Q5, "2SC945") QBJT_EB(Q6, "2SC945") QBJT_EB(Q7, "2SC945") QBJT_EB(Q9, "2SC945") LM2902_DIP(XU1) LM358_DIP(XU2) MC14584B_DIP(XU3) RES(R100, RES_K(560)) RES(R101, RES_K(150)) RES(R102, RES_K(150)) RES(R103, RES_K(470)) RES(R104, RES_K(22)) RES(R105, RES_K(470)) RES(R106, RES_K(150)) RES(R107, RES_K(150)) RES(R108, RES_K(560)) RES(R119, RES_K(22)) RES(R200, RES_K(100)) RES(R201, RES_K(100)) RES(R27, RES_K(6.8)) RES(R28, RES_K(150)) RES(R29, RES_K(2.7)) RES(R30, RES_K(10)) RES(R31, RES_K(5.1)) RES(R32, RES_K(4.7)) RES(R34, RES_K(100)) RES(R35, RES_K(100)) RES(R36, RES_K(100)) RES(R37, RES_K(47)) RES(R38, 820) RES(R39, RES_K(22)) RES(R40, RES_K(10)) RES(R41, RES_K(10)) RES(R42, RES_K(150)) RES(R43, 470) RES(R44, RES_K(100)) RES(R45, RES_K(1)) RES(R46, RES_K(12)) RES(R48, 470) RES(R48_2, RES_K(100)) RES(R49, RES_K(10)) RES(R50, RES_K(2.2)) RES(R51, RES_K(150)) RES(R52, RES_K(100)) RES(R53, RES_K(100)) RES(R54, 680) RES(R55, RES_K(510)) RES(R57, 560) RES(R58, RES_K(39)) RES(R59, 560) RES(R60, RES_K(39)) RES(R61, RES_K(100)) RES(R62, RES_K(100)) RES(R63, RES_K(1)) RES(R65, RES_K(1)) RES(R65_1, RES_K(27)) RES(R66, RES_M(1)) RES(R67, RES_K(100)) RES(R68, RES_K(100)) RES(R69, RES_K(1)) RES(R70, RES_K(10)) RES(R71, RES_K(100)) RES(R72, RES_K(100)) RES(R73, RES_K(10)) RES(R74, RES_K(10)) RES(R75, RES_K(10)) RES(R76, RES_K(47)) RES(R81, 220) RES(R82, RES_M(2.2)) RES(R83, RES_K(12)) RES(R84, RES_K(1)) RES(R85, RES_M(2.2)) RES(R86, RES_K(10)) RES(R87, RES_K(68)) RES(R89, RES_K(22)) RES(R90, RES_K(390)) RES(R91, RES_K(100)) RES(R92, RES_K(22)) RES(R93, RES_K(1)) RES(R94, RES_K(22)) RES(R95, RES_K(330)) RES(R96, RES_K(150)) RES(R97, RES_K(150)) RES(R98, RES_K(680)) #if USE_FIXED_STV ANALOG_INPUT(STV, 2) #else RES(R78, RES_K(3.3)) RES(R77, RES_K(2.2)) CAP(C58, CAP_U(47)) NET_C(R77.2, C58.1, I_V0.Q) NET_C(R78.1, I_V5.Q) #endif NET_C(R95.1, XU3.2, R96.2) NET_C(R95.2, XU3.1, C69.1) NET_C(XU3.3, R103.2, C73.1) NET_C(XU3.4, R103.1, R102.2) NET_C(XU3.5, R105.2, C72.1) NET_C(XU3.6, R105.1, R106.2) NET_C(XU3.7, C69.2, C73.2, C72.2, C77.2, C67.2, C68.2, R65.2, R38.2, XU1.11, R54.2, Q4.E, R63.2, C47.2, R72.2, R67.2, R71.2, R68.2, C48.2, R46.2, C28.1, C32.1, R43.2, XU2.4, C56.1, C52.1, R48.2, R93.2, R94.2, R119.2, R104.2, R53.2, R34.2, R81.2, R92.2, R89.2, C33.1, R37.2, R36.1, R91.1, I_V0.Q, RV1.3) NET_C(XU3.8, R108.1, R107.2) NET_C(XU3.9, R108.2, C77.1) NET_C(XU3.10, R100.1, R101.2) NET_C(XU3.11, R100.2, C67.1) NET_C(XU3.12, R98.1, R97.2) NET_C(XU3.13, R98.2, C68.1) NET_C(XU3.14, XU1.4, R66.1, R70.1, Q6.C, Q5.C, XU2.8, R86.1, R83.1, Q3.C, I_V5.Q) NET_C(R96.1, R102.1, R106.1, R107.1, R101.1, R97.1, R65.1, C63.2) NET_C(C63.1, R65_1.2) NET_C(R65_1.1, R44.2, C38.2, C40.2, XU1.6) #if USE_FIXED_STV NET_C(R30.1, R41.1, R40.1, R76.2, /* R78.2, R77.1, C58.2*/ STV) #else NET_C(R30.1, R41.1, R40.1, R76.2, R78.2, R77.1, C58.2) #endif NET_C(R30.2, XU1.5) NET_C(R44.1, C39.1, C40.1, R48_2.2) NET_C(C38.1, C39.2, R38.1) NET_C(XU1.1, XU1.2, R39.1, R32.2) NET_C(XU1.3, C34.1, R41.2) NET_C(XU1.7, R45.2) NET_C(XU1.8, XU1.9, R31.2, C36.2) NET_C(XU1.10, R42.1, C32.2) NET_C(XU1.12, C49.1, C31.1, R40.2, C61.1, C60.1) NET_C(XU1.13, R27.1, R28.2) NET_C(XU1.14, R28.1, R29.2, I_SINH0) NET_C(R48_2.1, C45.2, R54.1) NET_C(C45.1, R55.1, Q7.B) NET_C(R55.2, R90.2, C33.2, R37.1, Q3.E) NET_C(R45.1, C44.2) NET_C(C44.1, R66.2, Q4.B) #if FIX_SCHEMATIC_ERRORS #if D4_AND_D5_CONNECTED /* needs verification */ NET_C(Q4.C, D4.K, D5.K) NET_C(C42.1, C43.1, R46.1, C35.2) #else NET_C(Q4.C, D5.K) NET_C(C42.1, C43.1, R46.1, C35.2, D4.K) #endif #else NET_C(Q4.C, C42.1, C43.1, R46.1, C35.2, D4.K, D5.K) #endif NET_C(R70.2, R69.2, Q7.C) NET_C(R63.1, Q7.E) NET_C(R69.1, C49.2) NET_C(C42.2, R58.1, D5.A) NET_C(R58.2, R57.1, C47.1) NET_C(R57.2, Q6.E) NET_C(Q6.B, R61.1) NET_C(C50.1, R67.1, R61.2) NET_C(C50.2, R72.1, I_OH0.Q) NET_C(C51.1, R68.1, R62.2) NET_C(C51.2, R71.1, I_CH0.Q) NET_C(R62.1, Q5.B) NET_C(Q5.E, R59.2) NET_C(R60.1, C43.2, D4.A) NET_C(R60.2, R59.1, C48.1) NET_C(C35.1, C34.2, R39.2) NET_C(R32.1, C31.2) NET_C(R27.2, C28.2) NET_C(R29.1, R31.1, R50.2, R49.1, RV1.1) NET_C(R42.2, R51.1, C36.1) NET_C(R51.2, C41.1) NET_C(C41.2, R43.1, I_SOUNDIC0) NET_C(XU2.1, XU2.2, R73.1) NET_C(XU2.3, R76.1, C200.2) NET_C(XU2.5, C56.2, R75.1) NET_C(XU2.6, XU2.7, R50.1, C53.2) NET_C(R75.2, R74.1, C53.1) NET_C(R74.2, C52.2, R73.2) NET_C(R49.2, R48.1, I_SOUND0) NET_C(Q9.E, R81.1) NET_C(Q9.C, R84.2, R83.2, R82.1, C59.1) NET_C(Q9.B, R82.2, C62.1) NET_C(Q10.E, R93.1) NET_C(Q10.C, R87.2, R86.2, R85.1, C76.1) NET_C(Q10.B, R85.2, C64.1) NET_C(R84.1, C61.2) NET_C(C60.2, R87.1) NET_C(C64.2, C65.1, R94.1, D3.K) NET_C(C65.2, C66.1, R119.1) NET_C(C66.2, C76.2, R104.1) NET_C(R53.1, R52.2, C37.1) NET_C(R34.1, C37.2, I_BD0.Q) NET_C(R52.1, D3.A) NET_C(R92.1, C62.2, C57.1) NET_C(R89.1, C57.2, C59.2, R90.1) NET_C(Q3.B, R35.1) NET_C(R35.2, R36.2, C70.1) NET_C(R91.2, C70.2, I_SD0.Q) NET_C(I_MSM3K0.Q, R200.2) NET_C(I_MSM2K0.Q, R201.2) NET_C(R200.1, R201.1, C200.1) /* Amplifier stage */ CAP(C26, CAP_U(1)) RES(R25, 560) RES(R26, RES_K(47)) CAP(C29, CAP_U(0.01)) NET_C(RV1.2, C26.1) NET_C(C26.2, R25.1) NET_C(R25.2, R26.1, C29.1) NET_C(R26.2, C29.2, GND) NETLIST_END() /* ---------------------------------------------------------------------------- * Kidniki audio * ---------------------------------------------------------------------------*/ NETLIST_START(kidniki) #if (1 || USE_FRONTIERS) SOLVER(Solver, 48000) PARAM(Solver.ACCURACY, 1e-7) PARAM(Solver.NR_LOOPS, 300) PARAM(Solver.GS_LOOPS, 10) //PARAM(Solver.METHOD, "SOR") PARAM(Solver.METHOD, "MAT_CR") PARAM(Solver.FPTYPE, "DOUBLE") //PARAM(Solver.METHOD, "MAT") //PARAM(Solver.PIVOT, 1) //PARAM(Solver.Solver_0.METHOD, "GMRES") PARAM(Solver.SOR_FACTOR, 1.313) PARAM(Solver.DYNAMIC_TS, 0) PARAM(Solver.DYNAMIC_LTE, 5e-4) PARAM(Solver.DYNAMIC_MIN_TIMESTEP, 20e-6) PARAM(Solver.SORT_TYPE, "PREFER_IDENTITY_TOP_LEFT") //PARAM(Solver.SORT_TYPE, "PREFER_BAND_MATRIX") #else //PARAM(Solver.SORT_TYPE, "PREFER_BAND_MATRIX") SOLVER(Solver, 48000) PARAM(Solver.ACCURACY, 1e-7) PARAM(Solver.NR_LOOPS, 10000) PARAM(Solver.GS_LOOPS, 100) //PARAM(Solver.METHOD, "MAT_CR") PARAM(Solver.METHOD, "GMRES") #endif #if (USE_FRONTIERS) PARAM(Solver.PARALLEL, 2) // More does not help #else PARAM(Solver.PARALLEL, 0) #endif LOCAL_SOURCE(kidniki_schematics) ANALOG_INPUT(I_V5, 5) //ANALOG_INPUT(I_V0, 0) ALIAS(I_V0.Q, GND) /* AY 8910 internal resistors */ RES(R_AY45L_A, 1000) RES(R_AY45L_B, 1000) RES(R_AY45L_C, 1000) RES(R_AY45M_A, 1000) RES(R_AY45M_B, 1000) RES(R_AY45M_C, 1000) NET_C(I_V5, R_AY45L_A.1, R_AY45L_B.1, R_AY45L_C.1, R_AY45M_A.1, R_AY45M_B.1, R_AY45M_C.1) NET_C(R_AY45L_A.2, R_AY45L_B.2, R_AY45M_A.2, R_AY45M_B.2, R_AY45M_C.2) #if (J4) ALIAS(I_SOUNDIC0, R_AY45L_C.2) #else NET_C(R_AY45L_A.2, R_AY45L_C.2) ALIAS(I_SOUNDIC0, I_V0.Q) #endif ALIAS(I_SOUND0, R_AY45L_A.2) TTL_INPUT(SINH, 1) #if (D6_EXISTS) DIODE(D6, "1N914") NET_C(D6.K, SINH) ALIAS(I_SINH0, D6.A) #else RES(SINH_DUMMY, RES_M(10)) NET_C(SINH_DUMMY.1, SINH) ALIAS(I_SINH0, SINH_DUMMY.2) #endif NET_MODEL("AY8910PORT FAMILY(TYPE=NMOS OVL=0.05 OVH=0.05 ORL=100.0 ORH=0.5k)") LOGIC_INPUT(I_SD0, 1, "AY8910PORT") LOGIC_INPUT(I_BD0, 1, "AY8910PORT") LOGIC_INPUT(I_CH0, 1, "AY8910PORT") LOGIC_INPUT(I_OH0, 1, "AY8910PORT") NET_C(I_V5, I_SD0.VCC, I_BD0.VCC, I_CH0.VCC, I_OH0.VCC, SINH.VCC) NET_C(GND, I_SD0.GND, I_BD0.GND, I_CH0.GND, I_OH0.GND, SINH.GND) ANALOG_INPUT(I_MSM2K0, 0) ANALOG_INPUT(I_MSM3K0, 0) INCLUDE(kidniki_schematics) #if (USE_FRONTIERS) OPTIMIZE_FRONTIER(C63.2, RES_K(27), RES_K(1)) OPTIMIZE_FRONTIER(R31.2, RES_K(5.1), 50) OPTIMIZE_FRONTIER(R29.2, RES_K(2.7), 50) OPTIMIZE_FRONTIER(R87.2, RES_K(68), 50) OPTIMIZE_FRONTIER(R50.1, RES_K(2.2), 50) OPTIMIZE_FRONTIER(R55.2, RES_K(1000), 50) OPTIMIZE_FRONTIER(R84.2, RES_K(50), RES_K(5)) #endif NETLIST_END()
11,669
7,842
#include "api/farage.h" #include <unordered_map> #include <unordered_set> #include <fstream> using namespace Farage; #define VERSION "v0.0.4" extern "C" Info Module { "User Roles", "Madison", "User Role Granting System", VERSION, "http://farage.justca.me/", FARAGE_API_VERSION }; namespace role { std::unordered_map<std::string,std::unordered_set<std::string>> roles; } int addroleCmd(Handle&,int,const std::string[],const Message&); int delroleCmd(Handle&,int,const std::string[],const Message&); int giveroleCmd(Handle&,int,const std::string[],const Message&); extern "C" int onModuleStart(Handle &handle, Global *global) { recallGlobal(global); handle.createGlobVar("roles_version",VERSION,"User Roles Version",GVAR_CONSTANT); handle.regChatCmd("addrole",&addroleCmd,ROLE,"Allow an already existing role to the roster."); handle.regChatCmd("delrole",&delroleCmd,ROLE,"Remove a role from the roster."); handle.regChatCmd("role",&giveroleCmd,NOFLAG,"Grant a role for yourself."); return 0; } extern "C" int onReady(Handle &handle, Event event, void *data, void *nil, void *foo, void *bar) { Ready* readyData = (Ready*)data; for (auto it = readyData->guilds.begin(), ite = readyData->guilds.end();it != ite;++it) { std::unordered_set<std::string> r; std::ifstream file ("roles/" + *it); if (file.is_open()) { std::string line; while (std::getline(file,line)) r.emplace(line); file.close(); } role::roles.emplace(*it,std::move(r)); } return PLUGIN_CONTINUE; } int addroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if (roles == role::roles.end()) { role::roles.emplace(message.guild_id,std::unordered_set<std::string>()); roles = role::roles.find(message.guild_id); } if (argc < 2) { sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`"); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); std::string name = strlower(role); if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); bool found = false; for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if ((strlower(it->name) == name) || (it->id == role)) { role = it->id; name = it->name; found = true; break; } } if ((found) && (roles->second.find(role) == roles->second.end())) { roles->second.emplace(role); std::ofstream file ("roles/" + message.guild_id); if (file.is_open()) { for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) file<<*it<<std::endl; file.close(); } sendMessage(message.channel_id,"Added the role: `" + name + "`!"); } else if (found) sendMessage(message.channel_id,"Role is already registered: `" + name + "`!"); else sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } int delroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if (argc < 2) { sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`"); return PLUGIN_HANDLED; } if ((roles == role::roles.end()) || (roles->second.size() == 0)) { sendMessage(message.channel_id,"There are no registered roles!"); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); std::string name = strlower(role); if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if ((strlower(it->name) == name) || (it->id == role)) { role = it->id; name = it->name; break; } } auto r = roles->second.find(role); if (r == roles->second.end()) { sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } roles->second.erase(r); std::ofstream file ("roles/" + message.guild_id); if (file.is_open()) { for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) file<<*it<<std::endl; file.close(); } sendMessage(message.channel_id,"Removed the role: `" + name + "`!"); return PLUGIN_HANDLED; } int giveroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if ((roles == role::roles.end()) || (roles->second.size() == 0)) { sendMessage(message.channel_id,"There are no registered roles!"); return PLUGIN_HANDLED; } if (argc < 2) { Embed out; out.color = 11614177; out.title = "Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>` to give yourself a role."; for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) for (auto sit = server.roles.begin(), site = server.roles.end();sit != site;++sit) if (sit->id == *it) out.description.append(1,'\n').append(sit->name); sendEmbed(message.channel_id,out); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); std::string name = strlower(role); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); else { if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if (strlower(it->name) == name) { role = it->id; name = it->name; break; } } } if (roles->second.find(role) == roles->second.end()) { sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } else { auto mroles = message.member.roles; for (auto it = mroles.begin(), ite = mroles.end();it != ite;++it) { if (*it == role) { mroles.erase(it); editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles); sendMessage(message.channel_id,"You have left the `" + name + "` role."); return PLUGIN_HANDLED; } } mroles.push_back(role); editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles); sendMessage(message.channel_id,"You have joined the `" + name + "` role."); } return PLUGIN_HANDLED; }
7,936
2,727
//===-- Unittests for strdup ----------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "src/string/strdup.h" #include "utils/UnitTest/Test.h" #include <stdlib.h> TEST(LlvmLibcStrDupTest, EmptyString) { const char *empty = ""; char *result = __llvm_libc::strdup(empty); ASSERT_NE(result, static_cast<char *>(nullptr)); ASSERT_NE(empty, const_cast<const char *>(result)); ASSERT_STREQ(empty, result); ::free(result); } TEST(LlvmLibcStrDupTest, AnyString) { const char *abc = "abc"; char *result = __llvm_libc::strdup(abc); ASSERT_NE(result, static_cast<char *>(nullptr)); ASSERT_NE(abc, const_cast<const char *>(result)); ASSERT_STREQ(abc, result); ::free(result); } TEST(LlvmLibcStrDupTest, NullPtr) { char *result = __llvm_libc::strdup(nullptr); ASSERT_EQ(result, static_cast<char *>(nullptr)); }
1,125
413
// Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.org) // // 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 <crtdbg.h> #include "detour.h" #include "main.h" #include <tchar.h> #include <windows.h> using namespace std; namespace micro_profiler { namespace { collector_app_instance *g_instance_singleton = nullptr; shared_ptr<void> *g_exit_process_detour = nullptr; void WINAPI ExitProcessHooked(UINT exit_code) { if (g_exit_process_detour) g_exit_process_detour->reset(); g_instance_singleton->terminate(); ::ExitProcess(exit_code); } } void collector_app_instance::platform_specific_init() { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); static shared_ptr<void> exit_process_detour; g_instance_singleton = this; g_exit_process_detour = &exit_process_detour; HMODULE hmodule; ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, _T("kernel32"), &hmodule); const auto exit_process = ::GetProcAddress(hmodule, "ExitProcess"); ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, reinterpret_cast<LPCTSTR>(&ExitProcessHooked), &hmodule); exit_process_detour = detour(exit_process, &ExitProcessHooked); } }
2,312
895
#include "HTTPProxy.h" void Payload() { run(DEFAULT_PROXY_PORT); }
68
30
#include "opendrive_dynamic_mesh.h" #include "engine/core/log/log.h" #include "engine/core/scene/node_tree.h" #include "base/renderer.h" #include "base/shader/shader_program.h" #include "engine/core/main/Engine.h" namespace Echo { OpenDriveDynamicMesh::OpenDriveDynamicMesh() : Render() { setRenderType("3d"); } OpenDriveDynamicMesh::~OpenDriveDynamicMesh() { reset(); } void OpenDriveDynamicMesh::bindMethods() { CLASS_BIND_METHOD(OpenDriveDynamicMesh, getStepLength); CLASS_BIND_METHOD(OpenDriveDynamicMesh, setStepLength); CLASS_BIND_METHOD(OpenDriveDynamicMesh, getMaterial); CLASS_BIND_METHOD(OpenDriveDynamicMesh, setMaterial); CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "StepLength", Variant::Type::Real, getStepLength, setStepLength); CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "Material", Variant::Type::Object, getMaterial, setMaterial); CLASS_REGISTER_PROPERTY_HINT(OpenDriveDynamicMesh, "Material", PropertyHintType::ObjectType, "Material"); } void OpenDriveDynamicMesh::reset() { m_controlPoints.clear(); m_renderable.reset(); m_mesh.reset(); } void OpenDriveDynamicMesh::add(const Vector3& position, const Vector3& forward, const Vector3& up, float width, const Color& color, bool separator) { ControlPoint controlPoint; controlPoint.m_position = position; controlPoint.m_forward = forward; controlPoint.m_up = up; controlPoint.m_width = width; controlPoint.m_length = m_controlPoints.empty() ? 0.f : m_controlPoints.back().m_length + (m_controlPoints.back().m_position - position).len(); controlPoint.m_color = color; controlPoint.m_separator = separator; m_controlPoints.emplace_back(controlPoint); m_isRenderableDirty = true; } void OpenDriveDynamicMesh::setStepLength(float stepLength) { if (m_stepLength != stepLength) { m_stepLength = stepLength; m_isRenderableDirty = true; } } void OpenDriveDynamicMesh::setMaterial(Object* material) { m_material = (Material*)material; m_isRenderableDirty = true; } void OpenDriveDynamicMesh::buildRenderable() { if (m_isRenderableDirty) { if (!m_material) { StringArray macros = { "HAS_NORMALS" }; ShaderProgramPtr shader = ShaderProgram::getDefault3D(macros); m_material = ECHO_CREATE_RES(Material); m_material->setShaderPath(shader->getPath()); } // mesh updateMeshBuffer(); // create render able m_renderable = RenderProxy::create(m_mesh, m_material, this, true); m_isRenderableDirty = false; } } void OpenDriveDynamicMesh::updateInternal(float elapsedTime) { if (isNeedRender()) buildRenderable(); if (m_renderable) m_renderable->setSubmitToRenderQueue(isNeedRender()); } void OpenDriveDynamicMesh::updateMeshBuffer() { if (!m_mesh) { if (m_controlPoints.size()>1) m_mesh = Mesh::create(true, true); } if (m_mesh) { IndiceArray indices; VertexArray vertices; for (size_t i = 0; i < m_controlPoints.size(); i++) { const ControlPoint& controlPoint = m_controlPoints[i]; Vector3 halfRightDir = controlPoint.m_forward.cross(controlPoint.m_up) * controlPoint.m_width * 0.5f; // Update Vertices VertexFormat v0; v0.m_position = controlPoint.m_position + halfRightDir; v0.m_normal = controlPoint.m_up; //v0.m_color = controlPoint.Color; v0.m_uv = Vector2(0.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale; VertexFormat v1; v1.m_position = controlPoint.m_position - halfRightDir; v1.m_normal = controlPoint.m_up; //v1.Color = controlPoint.Color; v1.m_uv = Vector2(1.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale; vertices.push_back(v0); vertices.push_back(v1); // Update Indices if (i != 0 && !controlPoint.m_separator) { i32 base = vertices.size() - 4; indices.push_back(base); indices.push_back(base + 3); indices.push_back(base + 2); indices.push_back(base); indices.push_back(base + 1); indices.push_back(base + 3); } } // format MeshVertexFormat define; define.m_isUseNormal = true; define.m_isUseUV = true; m_mesh->updateIndices(static_cast<ui32>(indices.size()), sizeof(ui32), indices.data()); m_mesh->updateVertexs(define, static_cast<ui32>(vertices.size()), (const Byte*)vertices.data()); m_localAABB = m_mesh->getLocalBox(); } } void* OpenDriveDynamicMesh::getGlobalUniformValue(const String& name) { if (name == "u_WorldMatrix") return (void*)(&Matrix4::IDENTITY); return Render::getGlobalUniformValue(name); } }
4,568
1,908
// C++ code for Marxan // version 2.3 introduced multiple connectivity files and their associated weighting file // version 2.4.3 introduced 1D and 2D probability // version 3.0.0 is refactoring of code in 2019 #include <algorithm> #include <chrono> #include <ctime> #include <cfloat> #include <iostream> #include <omp.h> #include <chrono> // load the required function definition modules #include "utils.hpp" #include "algorithms.hpp" #include "computation.hpp" #include "clumping.hpp" #include "anneal.hpp" #include "heuristics.hpp" #include "probability.hpp" #include "input.hpp" #include "output.hpp" #include "score_change.hpp" #include "iterative_improvement.hpp" #include "quantum_annealing.hpp" #include "thermal_annealing.hpp" #include "hill_climbing.hpp" #include "marxan.hpp" #include "defines.hpp" namespace marxan { using namespace algorithms; using namespace utils; // Initialize global constants double delta; long int RandSeed1; int iMemoryUsed = 0; int fSpecPROPLoaded = 0; int iProbFieldPresent = 0; int iOptimisationCalcPenalties = 1; int savelog; int verbosity = 0; int asymmetricconnectivity = 0; string sVersionString = "Marxan v 4.0.6"; string sMarxanWebSite = "https://marxansolutions.org/"; string sTraceFileName; string sApplicationPathName; string savelogname; FILE* fsavelog; // init global structures sanneal anneal_global; vector<sconnections> connections; sfname fnames; vector<spu> SMGlobal; vector<spusporder> SMsporder; vector<spustuff> pu; map<int, int> PULookup, SPLookup; vector<sspecies> specGlobal, bestSpec; chrono::high_resolution_clock::time_point startTime; double rProbabilityWeighting = 1; double rStartDecThresh = 0.7, rEndDecThresh = 0.3, rStartDecMult = 3, rEndDecMult = 1; int fProb2D = 0, fProb1D = 0, fUserPenalties = 0; int fOptimiseConnectivityIn = 0; // number of the best solution int bestRun = 1; // score of the best solution double bestScore; // R vector of planning unit status for the best solution vector<int> bestR; // is marxan being called by another program? int marxanIsSecondary = 0; // runs the loop for each "solution" marxan is generating void executeRunLoop(long int repeats, int puno, int spno, double cm, int aggexist, double prop, int clumptype, double misslevel, string savename, double costthresh, double tpf1, double tpf2, int heurotype, srunoptions& runoptions, int itimptype, vector<int>& sumsoln, rng_engine& rngEngineGlobal) { string bestRunString; vector<string> summaries(repeats); // stores individual summaries for each run bestR.resize(puno); bestScore = DBL_MAX; bestSpec.resize(spno); // best species config // Locks for bestR and bestScore as it will be read/written by multiple threads omp_lock_t bestR_write_lock; omp_init_lock(&bestR_write_lock); // Locks for solution matrix append omp_lock_t solution_matrix_append_lock; omp_init_lock(&solution_matrix_append_lock); // Locks for sumsoln omp_lock_t solution_sum_lock; omp_init_lock(&solution_sum_lock); // for each repeat run int maxThreads = omp_get_max_threads(); printf("Running multithreaded over number of threads: %d\n", maxThreads); displayProgress1("Running multithreaded over number of threads: " + to_string(maxThreads) + "\n"); displayProgress1("Runs will be printed as they complete, and may not be in order due to parallelisation.\n"); //create seeds for local rng engines vector<unsigned int> seeds(repeats); for (int run_id = 1; run_id <= repeats; run_id++) seeds[run_id - 1] = rngEngineGlobal(); bool quitting_loop = false; #pragma omp parallel for schedule(dynamic) for (int run_id = 1; run_id <= repeats; run_id++) { if(quitting_loop) continue; //skipping iterations. It is not allowed to break or throw out omp for loop. // Create run specific structures int thread = omp_get_thread_num(); rng_engine rngEngine(seeds[run_id - 1]); string tempname2; stringstream appendLogBuffer; // stores the trace file log stringstream runConsoleOutput; // stores the console message for the run. This is needed for more organized printing output due to multithreading. sanneal anneal = anneal_global; scost reserve; scost change; vector<int> R(puno); vector<sspecies> spec = specGlobal; // make local copy of original spec vector<spu_out> SM_out; // make local copy output part of SMGlobal. //if (aggexist) SM_out.resize(SMGlobal.size()); appendLogBuffer << "\n Start run loop run " << run_id << endl; try { if (runoptions.ThermalAnnealingOn) { // Annealing Setup if (anneal.type == 2) { appendLogBuffer << "before initialiseConnollyAnnealing run " << run_id << endl; initialiseConnollyAnnealing(puno, spno, pu, connections, spec, SMGlobal, SM_out, cm, anneal, aggexist, R, prop, clumptype, run_id, appendLogBuffer, rngEngine); appendLogBuffer << "after initialiseConnollyAnnealing run " << run_id << endl; } if (anneal.type == 3) { appendLogBuffer << "before initialiseAdaptiveAnnealing run " << run_id << endl; initialiseAdaptiveAnnealing(puno, spno, prop, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, anneal, clumptype, appendLogBuffer, rngEngine); appendLogBuffer << "after initialiseAdaptiveAnnealing run " << run_id << endl; } if (verbosity > 1) runConsoleOutput << "\nRun " << run_id << ": Using Calculated Tinit = " << anneal.Tinit << " Tcool = " << anneal.Tcool << "\n"; anneal.temp = anneal.Tinit; } appendLogBuffer << "before computeReserveValue run " << run_id << endl; initialiseReserve(prop, pu, R, rngEngine); // Create Initial Reserve SpeciesAmounts(spno, puno, spec, pu, SMGlobal, R, clumptype); // Re-added this from v2.4 because spec amounts need to be refreshed when initializing if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); appendLogBuffer << "after computeReserveValue run " << run_id << endl; if (verbosity > 1) { runConsoleOutput << "Run " << run_id << " Init: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } if (verbosity > 5) { displayTimePassed(startTime); } if (runoptions.ThermalAnnealingOn) { appendLogBuffer << "before thermalAnnealing run " << run_id << endl; thermalAnnealing(spno, puno, connections, R, cm, spec, pu, SMGlobal, SM_out, reserve, repeats, run_id, savename, misslevel, aggexist, costthresh, tpf1, tpf2, clumptype, anneal, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " ThermalAnnealing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after thermalAnnealing run " << run_id << endl; } if (runoptions.HillClimbingOn) { appendLogBuffer << "before hill climbing run " << run_id << endl; hill_climbing( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2, clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after hill climbing run " << run_id << endl; } if (runoptions.TwoStepHillClimbingOn) { appendLogBuffer << "before two step hill climbing run " << run_id << endl; hill_climbing_two_steps( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2, clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Two Step Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after hill climbing run " << run_id << endl; } if (runoptions.HeuristicOn) { appendLogBuffer << "before Heuristics run " << run_id << endl; Heuristics(spno, puno, pu, connections, R, cm, spec, SMGlobal, SM_out, reserve, costthresh, tpf1, tpf2, heurotype, clumptype, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Heuristic: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after Heuristics run " << run_id << endl; } if (runoptions.ItImpOn) { appendLogBuffer << "before iterativeImprovement run " << run_id << endl; iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine); if (itimptype == 3) iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine); appendLogBuffer << "after iterativeImprovement run " << run_id << endl; if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Iterative Improvement: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } } // Activate Iterative Improvement appendLogBuffer << "before file output run " << run_id << endl; string fileNumber = utils::intToPaddedString(run_id, 5); if (fnames.saverun) { tempname2 = savename + "_r" + fileNumber + getFileNameSuffix(fnames.saverun); writeSolution(puno, R, pu, tempname2, fnames.saverun, fnames); } if (fnames.savespecies && fnames.saverun) { tempname2 = savename + "_mv" + fileNumber + getFileNameSuffix(fnames.savespecies); writeSpecies(spno, spec, tempname2, fnames.savespecies, misslevel); } if (fnames.savesum) { // summaries get stored and aggregated to prevent race conditions. summaries[run_id - 1] = computeSummary(puno, spno, R, spec, reserve, run_id, misslevel, fnames.savesum); } // Print results from run. displayProgress1(runConsoleOutput.str()); // compute and store objective function score for this reserve system computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, change, clumptype, appendLogBuffer); // remember the bestScore and bestRun if (change.total < bestScore) { omp_set_lock(&bestR_write_lock); // After locking, do another check in case bestScore has changed if (change.total < bestScore) { // this is best run so far bestScore = change.total; bestRun = run_id; // store bestR bestR = R; bestRunString = runConsoleOutput.str(); bestSpec = spec; // make a copy of best spec. } omp_unset_lock(&bestR_write_lock); } if (fnames.savesolutionsmatrix) { appendLogBuffer << "before appendSolutionsMatrix savename " << run_id << endl; tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix); omp_set_lock(&solution_matrix_append_lock); appendSolutionsMatrix(run_id, puno, R, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders); omp_unset_lock(&solution_matrix_append_lock); appendLogBuffer << "after appendSolutionsMatrix savename " << run_id << endl; } // Save solution sum if (fnames.savesumsoln) { omp_set_lock(&solution_sum_lock); for (int k = 0; k < puno; k++) { if (R[k] == 1 || R[k] == 2) { sumsoln[k]++; } } omp_unset_lock(&solution_sum_lock); } if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); } catch (const exception& e) { // On exceptions, append exception to log file in addition to existing buffer. displayProgress1(runConsoleOutput.str()); appendLogBuffer << "Exception occurred on run " << run_id << ": " << e.what() << endl; displayProgress1(appendLogBuffer.str()); appendTraceFile(appendLogBuffer.str()); //cannot throw or break out of omp loop quitting_loop = true; continue; } appendLogBuffer << "after file output run " << run_id << endl; appendLogBuffer << "end run " << run_id << endl; appendTraceFile(appendLogBuffer.str()); if (marxanIsSecondary == 1) writeSecondarySyncFileRun(run_id); if (verbosity > 1) { stringstream done_message; done_message << "Run " << run_id << " is finished (out of " << repeats << "). "; #pragma omp critical { displayProgress1(done_message.str()); displayTimePassed(startTime); } } } if(quitting_loop) { displayProgress1("\nRuns were aborted due to error.\n"); throw runtime_error("Runs were aborted due to error.\n"); } // Write all summaries for each run. if (fnames.savesum) { string tempname2 = savename + "_sum" + getFileNameSuffix(fnames.savesum); writeSummary(tempname2, summaries, fnames.saverun); } stringstream bestOut; bestOut << "\nBest run: " << bestRun << " Best score: " << bestScore << "\n" << bestRunString; cout << bestOut.str(); displayProgress1(bestOut.str()); } // executeRunLoop int executeMarxan(string sInputFileName) { long int repeats; int puno, spno, gspno; double cm, prop; int heurotype, clumptype, itimptype; string savename, tempname2; double misslevel; int iseed = time(NULL), seedinit; int aggexist = 0, sepexist = 0; vector<int> R_CalcPenalties; vector<int> sumsoln; double costthresh, tpf1, tpf2; long int itemp; int isp; int maxThreads = omp_get_max_threads(); srunoptions runoptions; displayStartupMessage(); startTime = chrono::high_resolution_clock::now(); // set program start time. readInputOptions(cm, prop, anneal_global, iseed, repeats, savename, fnames, sInputFileName, runoptions, misslevel, heurotype, clumptype, itimptype, verbosity, costthresh, tpf1, tpf2); sTraceFileName = savename + "_TraceFile.txt"; createTraceFile(); appendTraceFile("%s begin execution\n\n", sVersionString.c_str()); appendTraceFile("LoadOptions\n"); #ifdef DEBUGCHECKCHANGE createDebugFile("debug_MarOpt_CheckChange.csv", "ipu,puid,R,total,cost,connection,penalty,threshpen,probability\n", fnames); #endif #ifdef DEBUGCHANGEPEN createDebugFile("debug_MarOpt_ChangePen.csv", "ipu,puid,isp,spid,penalty,target,targetocc,occurrence,sepnum,amount,newamount,fractionAmount\n", fnames); #endif #ifdef DEBUGCALCPENALTIES createDebugFile("debug_MarZone_CalcPenalties.csv", "\n", fnames); #endif if (fnames.savelog) { tempname2 = savename + "_log.dat"; createLogFile(fnames.savelog, tempname2); } delta = 1e-14; // This would more elegantly be done as a constant // init rng engine rng_engine rngEngine(iseed); RandSeed1 = iseed; seedinit = iseed; appendTraceFile("RandSeed iseed %i RandSeed1 %li\n", iseed, RandSeed1); // read the data files displayProgress1("\nEntering in the data files \n"); displayProgress3(" Reading in the Planning Unit names \n"); appendTraceFile("before readPlanningUnits\n"); itemp = readPlanningUnits(puno, pu, fnames); appendTraceFile("after readPlanningUnits\n"); if (iProbFieldPresent == 1) appendTraceFile("prob field present\n"); else appendTraceFile("prob field not present\n"); #ifdef DEBUG_PROB1D if (iProbFieldPresent == 1) writeProbData(puno, pu, fnames); #endif displayProgress1(" There are %i Planning units.\n %i Planning Unit names read in \n", puno, itemp); displayProgress3(" Reading in the species file \n"); appendTraceFile("before readSpecies\n"); itemp = readSpecies(spno, specGlobal, fnames); appendTraceFile("after readSpecies\n"); displayProgress1(" %i species read in \n", itemp); appendTraceFile("before build search arrays\n"); // create the fast lookup tables for planning units and species names populateLookupTables(puno, spno, pu, specGlobal, PULookup, SPLookup); appendTraceFile("after build search arrays\n"); if (fnames.savesumsoln) sumsoln.resize(puno); connections.resize(puno); displayProgress3(" Reading in the Connection file :\n"); itemp = 0; if (!fnames.connectionname.empty()) { appendTraceFile("before readConnections\n"); if (!fnames.connectionfilesname.empty()) writeWeightedConnectivityFile(fnames); itemp = readConnections(puno, connections, pu, PULookup, fnames); appendTraceFile("after readConnections\n"); if (asymmetricconnectivity) { appendTraceFile("Asymmetric connectivity is on.\n"); writeAsymmetricConnectionFile(puno, connections, pu, fnames); } if (fOptimiseConnectivityIn) appendTraceFile("Optimising 'Connectivity In'.\n"); } displayProgress1(" %i connections entered \n", itemp); if (asymmetricconnectivity) displayProgress1(" Asymmetric connectivity is on.\n"); if (fOptimiseConnectivityIn) displayProgress1(" Optimising 'Connectivity In'.\n"); displayProgress3(" Reading in the Planning Unit versus Species File \n"); appendTraceFile("before readSparseMatrix\n"); readSparseMatrix(SMGlobal, puno, spno, pu, PULookup, SPLookup, fnames); appendTraceFile("after readSparseMatrix\n"); if (fProb2D == 1) appendTraceFile("Prob2D is on\n"); else appendTraceFile("Prob2D is off\n"); #ifdef DEBUG_PROB2D writeSparseMatrix(iSparseMatrixFileLength, puno, pu, spec, SM, fnames); #endif if (fnames.saverichness) { tempname2 = savename + "_richness" + getFileNameSuffix(fnames.saverichness); writeRichness(puno, pu, tempname2, fnames.saverichness); } if (!fnames.matrixspordername.empty()) { appendTraceFile("before readSparseMatrixSpOrder\n"); displayWarningMessage("input.dat option: MATRIXSPORDERNAME is no longer needed, however the supplied file will still be read and processed. Please refer to the version 4 feature changelog.md."); readSparseMatrixSpOrder(SMsporder, puno, spno, PULookup, SPLookup, specGlobal, fnames); appendTraceFile("after readSparseMatrixSpOrder\n"); } appendTraceFile("before process block definitions\n"); if (!fnames.blockdefname.empty()) { displayProgress1(" Reading in the Block Definition File \n"); vector<sgenspec> gspec; // declare within this scope of usage readSpeciesBlockDefinition(gspno, gspec, fnames); setBlockDefinitions(gspno, spno, puno, gspec, specGlobal, pu, SMGlobal); } setDefaultTargets(specGlobal); appendTraceFile("after process block definitions\n"); appendTraceFile("before computeTotalAreas\n"); computeTotalAreas(puno, spno, pu, specGlobal, SMGlobal); appendTraceFile("after computeTotalAreas\n"); if (fnames.savetotalareas) { tempname2 = savename + "totalareas" + getFileNameSuffix(fnames.savetotalareas); writeTotalAreas(puno, spno, pu, specGlobal, SMGlobal, tempname2, fnames.savepenalty); } if (fSpecPROPLoaded > 0) { appendTraceFile("before computeSpecProp\n"); // species have prop value specified computeSpecProp(spno, specGlobal, puno, pu, SMGlobal); appendTraceFile("after computeSpecProp\n"); } displayProgress2("Checking to see if there are aggregating or separating species.\n"); for (isp = 0; isp < spno; isp++) { if (specGlobal[isp].target2 > 0) aggexist = 1; if (specGlobal[isp].sepdistance > 0) sepexist = 1; } if (fnames.savesen) { appendTraceFile("before writeScenario\n"); tempname2 = savename + "_sen.dat"; writeScenario(puno, spno, prop, cm, anneal_global, seedinit, repeats, clumptype, runoptions, heurotype, costthresh, tpf1, tpf2, tempname2); appendTraceFile("after writeScenario\n"); } if (verbosity > 1) displayTimePassed(startTime); // ******* Pre-processing ************ displayProgress1("\nPre-processing Section. \n"); displayProgress2(" Calculating all the penalties \n"); R_CalcPenalties.resize(puno); // load penalties from file if they are present if (!fnames.penaltyname.empty()) { fUserPenalties = 1; appendTraceFile("before readPenalties\n"); readPenalties(specGlobal, spno, fnames, SPLookup); appendTraceFile("after readPenalties\n"); } if (runoptions.CalcPenaltiesOn == 0) { // if penalties have not been loaded, then stop error message if (fUserPenalties == 0) { appendTraceFile("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n"); displayProgress1("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n"); exit(EXIT_FAILURE); } // transfer loaded penalties to correct data structrure applyUserPenalties(specGlobal); } else { vector<spu_out> SM_out; // make local copy output part of SMGlobal. //if (aggexist) SM_out.resize(SMGlobal.size()); // we are computing penalties if (fnames.matrixspordername.empty()) { appendTraceFile("before CalcPenalties\n"); // we don't have sporder matrix available, so use slow CalcPenalties method itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenalties\n"); } else { // we have sporder matrix available, so use optimised CalcPenalties method if (iOptimisationCalcPenalties == 1) { appendTraceFile("before CalcPenaltiesOptimise\n"); itemp = computePenaltiesOptimise(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, SMsporder, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenaltiesOptimise\n"); } else { appendTraceFile("before CalcPenalties\n"); // we have optimise calc penalties switched off, so use slow CalcPenalties method itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenalties\n"); } } } if (itemp > 0) displayProgress("%d species cannot meet target%c.\n", itemp, itemp == 1 ? ' ' : 's'); if (runoptions.ThermalAnnealingOn) { displayProgress2(" Calculating temperatures.\n"); if (!anneal_global.Titns) displayErrorMessage("Initial Temperature is set to zero. Fatal Error \n"); anneal_global.Tlen = anneal_global.iterations / anneal_global.Titns; displayProgress2(" Temperature length %ld \n", anneal_global.Tlen); displayProgress2(" iterations %lld, repeats %ld \n", anneal_global.iterations, repeats); } // Annealing Preprocessing. Should be moved to SetAnnealingOptions if (fnames.savepenalty) { tempname2 = savename + "_penalty" + getFileNameSuffix(fnames.savepenalty); writePenalty(spno, specGlobal, tempname2, fnames.savepenalty); tempname2 = savename + "_penalty_planning_units" + getFileNameSuffix(fnames.savepenalty); writePenaltyPlanningUnits(puno, pu, R_CalcPenalties, tempname2, fnames.savepenalty); } //free(R_CalcPenalties); if (fnames.savespec) { tempname2 = savename + "_spec.csv"; writeSpec(spno, specGlobal, tempname2); } if (fnames.savepu) { tempname2 = savename + "_pu.csv"; writePu(puno, pu, tempname2); } // If we are in a runmode with only CalcPenalties, we stop/exit here gracefully because we are finished. if (runoptions.HeuristicOn == 0 && runoptions.ThermalAnnealingOn == 0 && runoptions.HillClimbingOn == 0 && runoptions.ItImpOn == 0 && runoptions.TwoStepHillClimbingOn == 0) { appendTraceFile("end final file output\n"); appendTraceFile("\nMarxan end execution\n"); displayShutdownMessage(startTime); if (marxanIsSecondary == 1) secondaryExit(); exit(EXIT_FAILURE); } if (fnames.savesolutionsmatrix) { tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix); #ifdef DEBUG_CLUSTERANALYSIS appendTraceFile("before createSolutionsMatrix savename %s\n", savename); #endif createSolutionsMatrix(puno, pu, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders); #ifdef DEBUG_CLUSTERANALYSIS appendTraceFile("after createSolutionsMatrix savename %s\n", savename); #endif } if (fProb1D == 1) { tempname2 = savename + "_ComputeP_AllPUsSelected_1D.csv"; ComputeP_AllPUsSelected_1D(tempname2, puno, spno, pu, SMGlobal, specGlobal); } if (fProb2D == 1) { tempname2 = savename + "_ComputeP_AllPUsSelected_2D.csv"; ComputeP_AllPUsSelected_2D(tempname2, puno, spno, pu, SMGlobal, specGlobal); } try { executeRunLoop(repeats, puno, spno, cm, aggexist, prop, clumptype, misslevel, savename, costthresh, tpf1, tpf2, heurotype, runoptions, itimptype, sumsoln, rngEngine); } catch (const exception& e) { appendTraceFile("Error during main loop.\n"); exit(EXIT_FAILURE); } appendTraceFile("before final file output\n"); if (fnames.savebest) { tempname2 = savename + "_best" + getFileNameSuffix(fnames.savebest); writeSolution(puno, bestR, pu, tempname2, fnames.savebest, fnames); appendTraceFile("Best solution is run %i\n", bestRun); displayProgress1("\nBest solution is run %i\n", bestRun); } if (fnames.savespecies && fnames.savebest) { tempname2 = savename + "_mvbest" + getFileNameSuffix(fnames.savespecies); // TODO ADBAI - need to write best spec, NOT spec_global writeSpecies(spno, bestSpec, tempname2, fnames.savespecies, misslevel); } if (fnames.savesumsoln) { tempname2 = savename + "_ssoln" + getFileNameSuffix(fnames.savesumsoln); writeSumSoln(puno, sumsoln, pu, tempname2, fnames.savesumsoln); } if (fnames.savesolutionsmatrix) { if (fnames.rexecutescript) { if (marxanIsSecondary == 1) secondaryExit(); } } displayShutdownMessage(startTime); appendTraceFile("end final file output\n"); appendTraceFile("\nMarxan end execution. Press any key to continue\n"); return 0; } // executeMarxan // handle command line parameters for the marxan executable void handleOptions(int argc, char* argv[], string& sInputFileName, int& marxanIsSecondary) { if (argc > 4) { // if more than one commandline argument then exit displayUsage(argv[0]); exit(1); } for (int i = 1; i < argc; i++) { // Deal with all arguments if (argv[i][0] == '/' || argv[i][0] == '-') { switch (argv[i][1]) { case 'C': case 'c': case 'S': case 's': marxanIsSecondary = 1; break; default: fprintf(stderr, "unknown option %s\n", argv[i]); break; } } else { sInputFileName = argv[i]; /* If not a -option then must be input.dat name */ } } } // marxan is running as a secondary process and has finished. create a sync file so the calling software will know marxan has finished creating the output files // secondaryExit does not deliver a message prior to exiting, but creates a file so C-Plan/Zonae Cogito/etc knows marxan has exited void secondaryExit(void) { writeSecondarySyncFile(); } } // namespace marxan // main needs to be defined outside of namespace int main(int argc, char* argv[]) { std::string sInputFileName = "input.dat"; // store application name marxan::sApplicationPathName = argv[0]; if (argc > 1) { // handle the program options marxan::handleOptions(argc, argv, sInputFileName, marxan::marxanIsSecondary); } try { if (marxan::executeMarxan(sInputFileName)) // Calls the main annealing unit { if (marxan::marxanIsSecondary == 1) { marxan::secondaryExit(); } return 1; } // Abnormal Exit } catch(const std::exception& e) { std::cerr << "Error during Marxan execution." << '\n'; exit(EXIT_FAILURE); } if (marxan::marxanIsSecondary == 1) { marxan::secondaryExit(); } return 0; }
34,650
10,280
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bluetooth/bluetooth_extension.h" #if defined(TIZEN_CAPI_BT) #include "bluetooth/bluetooth_instance_capi.h" #else #include "bluetooth/bluetooth_instance.h" #endif common::Extension* CreateExtension() { return new BluetoothExtension; } // This will be generated from bluetooth_api.js. extern const char kSource_bluetooth_api[]; BluetoothExtension::BluetoothExtension() { const char* entry_points[] = { NULL }; SetExtraJSEntryPoints(entry_points); SetExtensionName("tizen.bluetooth"); SetJavaScriptAPI(kSource_bluetooth_api); } BluetoothExtension::~BluetoothExtension() {} common::Instance* BluetoothExtension::CreateInstance() { return new BluetoothInstance; }
854
278
/* FileName: myping.cpp * Author: Hover * E-Mail: hover@hust.edu.cn * GitHub: HoverWings * Description: the Hover's impletation of ping * Attention: you may need sudo to run this code */ #include <cstdio> #include <iostream> #include <algorithm> #include <iomanip> #include <vector> #include <getopt.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/time.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netdb.h> #include <setjmp.h> #include <errno.h> using namespace std; #define MAX_WAIT_TIME 5 #define PACKET_SIZE 4096 int max_no_packets=5; int interval=1; char sendpacket[PACKET_SIZE]; char recvpacket[PACKET_SIZE]; pid_t pid; int sockfd; int datalen = 56; int nsend = 0; int nreceived = 0; struct sockaddr_in dest_addr; struct sockaddr_in from_addr; struct timeval tvrecv; vector<double> rtt_vec; void statistics(int signo); unsigned short cal_chksum(unsigned short *addr,int len); int pack(int pack_no); void send_packet(void); void recv_packet(void); int unpack(char *buf,int len); void timediff(struct timeval *out,struct timeval *in); bool opt_t = false; // set ttl bool opt_i = false; // interval void Stop(int signo) { statistics(signo); _exit(0); } int main(int argc,char *argv[]) { signal(SIGINT, Stop); //set exit function char opt; int option_index = 0; static struct option long_options[] = { {"help", no_argument, NULL, 'h'} }; char str[256]; strcpy(str,argv[1]); while ((opt = getopt_long(argc, argv, "t:i:h", long_options, &option_index)) != -1) { //printf("%c",opt); //cout<<argv[optind - 1]; switch (opt) { case 't': max_no_packets=atoi(argv[optind - 1]); opt_t = true; break; case 'i': interval==atoi(argv[optind - 1]); opt_i = true; break; case 'h': opt_i = true; break; } } struct hostent *host; //host entry struct protoent *protocol; unsigned long inaddr = 0l; int size = 50*1024; //50k if(argc < 2) { printf("use : %s hostname/IP address \n", argv[0]); exit(1); } if((protocol = getprotobyname("icmp")) == NULL) { perror("getprotobyname"); exit(1); } // setuid(getpid()); // need root to create socket if((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0){ perror("socket error"); exit(1); } setuid(getuid()); // recycle root privilage // case: broadcast address then there will be a lot of reply // so the buf need enough size setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size) ); bzero(&dest_addr, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; // domain or address judge printf("%s",str); if((inaddr=inet_addr(str)) == INADDR_NONE) { if((host = gethostbyname(str)) == NULL) { perror("gethostbyname error"); exit(1); } memcpy((char*)&dest_addr.sin_addr, host->h_addr, host->h_length); } else { memcpy((char*)&dest_addr.sin_addr, (char*)&inaddr, sizeof(inaddr)); } pid = getpid(); printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr), datalen); send_packet(); statistics(SIGALRM); return 0; } void statistics(int signo) { printf("\n--------------------PING statistics-------------------\n"); printf("%d packets transmitted, %d received , %%%d lost\n",nsend, nreceived, (nsend-nreceived)/nsend*100); printf("rtt min/avg/max/mdev = "); sort(rtt_vec.begin(), rtt_vec.end()); double min=rtt_vec.front(); double max=rtt_vec[rtt_vec.size()-1]; double total; for(vector<double>::iterator iter=rtt_vec.begin();iter!=rtt_vec.end();iter++) { // cout << (*iter) << endl; total+=*iter; } double avg=total/nsend; double mdev=max-min; cout<<fixed<<setprecision(3) <<min<<"/"<<avg<<"/"<<max<<"/"<<mdev<<"ms"<<endl; close(sockfd); exit(1); } /* I: addr: check data buffer check data len(byte) */ unsigned short cal_chksum(unsigned short *addr,int len) { int sum=0; int nleft = len; unsigned short *w = addr; unsigned short answer = 0; while(nleft > 1) { sum += *w++; nleft -= 2; } //if the ICMP head len is odd, then the final data is high bit and add it if(nleft == 1) { *(unsigned char *)(&answer) = *(unsigned char *)w; sum += answer; //transfer answer to int } sum = (sum >> 16) + (sum & 0xffff); // add high bit and low bit sum += (sum >> 16); // add overflow answer = ~sum; // 16 bit checksum return answer; } /* I: icmp struct sequence O: packed icmp */ int pack(int pack_no) { int packsize; struct icmp *icmp; struct timeval *tval; icmp = (struct icmp*)sendpacket; icmp->icmp_type = ICMP_ECHO; // type of service icmp->icmp_code = 0; icmp->icmp_cksum = 0; icmp->icmp_seq = pack_no; icmp->icmp_id = pid; packsize = 8 + datalen; //64=8(head)+56 tval = (struct timeval *)icmp->icmp_data; // 获得icmp结构中最后的数据部分的指针 gettimeofday(tval, NULL); // 将发送的时间填入icmp结构中最后的数据部分 icmp->icmp_cksum = cal_chksum((unsigned short *)icmp, packsize);/*填充发送方的校验和*/ return packsize; } void send_packet() { int packetsize; while(nsend < max_no_packets) { nsend++; packetsize = pack(nsend); // set ICMP message head if(sendto(sockfd, sendpacket, packetsize, 0,(struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) { perror("sendto error"); continue; } recv_packet(); sleep((uint)interval); } } void recv_packet() { int n; extern int errno; signal(SIGALRM,statistics); int from_len = sizeof(from_addr); while(nreceived < nsend) { alarm(MAX_WAIT_TIME); if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0,(struct sockaddr *)&from_addr, (socklen_t *)&from_len)) < 0) { if(errno == EINTR) { continue; } perror("recvfrom error"); continue; } gettimeofday(&tvrecv, NULL); // get receive time if(unpack(recvpacket, n) == -1) continue; nreceived++; } } /* I:buf IP buf len IP message len addr ICMP dest address O:error code */ int unpack(char *buf, int len) { int iphdrlen; struct ip *ip; struct icmp *icmp; struct timeval *tvsend; double rtt; ip = (struct ip *)buf; iphdrlen = ip->ip_hl << 2; //ip head len icmp = (struct icmp *)(buf + iphdrlen); // seek to IP message len -= iphdrlen; if(len < 8) // less than ICMP head len { printf("ICMP packets\'s length is less than 8\n"); return -1; } // check ICMP reply if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == pid)) { tvsend = (struct timeval *)icmp->icmp_data; timediff(&tvrecv, tvsend); rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0; rtt_vec.push_back(rtt); printf("%d byte from %s: icmp_seq=%u ttl=%d time=%.3f ms\n", len, // total message len inet_ntoa(from_addr.sin_addr), icmp->icmp_seq, ip->ip_ttl, rtt); //ms rtt return 0; } else return -1; } /* I:begin_time endtime O:ms diff */ void timediff(struct timeval *recv, struct timeval *send) { if((recv->tv_usec -= send->tv_usec) < 0) { --recv->tv_sec; recv->tv_usec += 1000000; } recv->tv_sec -= send->tv_sec; }
8,699
3,108
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lakeformation/model/DatabaseResource.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LakeFormation { namespace Model { DatabaseResource::DatabaseResource() : m_catalogIdHasBeenSet(false), m_nameHasBeenSet(false) { } DatabaseResource::DatabaseResource(JsonView jsonValue) : m_catalogIdHasBeenSet(false), m_nameHasBeenSet(false) { *this = jsonValue; } DatabaseResource& DatabaseResource::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("CatalogId")) { m_catalogId = jsonValue.GetString("CatalogId"); m_catalogIdHasBeenSet = true; } if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } return *this; } JsonValue DatabaseResource::Jsonize() const { JsonValue payload; if(m_catalogIdHasBeenSet) { payload.WithString("CatalogId", m_catalogId); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } return payload; } } // namespace Model } // namespace LakeFormation } // namespace Aws
1,279
457
#pragma once #include "motion/generator/Generator.hpp" class ClippedGenerator : Generator { public: explicit ClippedGenerator(Generator* g); ~ClippedGenerator(); virtual JointValues makeJoints(ActionCommand::All* request, Odometry* odometry, const SensorValues &sensors, BodyModel &bodyModel, float ballX, float ballY); virtual bool isActive(); void reset(); void readOptions(const boost::program_options::variables_map &config); private: Generator* generator; JointValues old_j; bool old_exists; };
748
182
int diameterOfBinaryTree(TreeNode* root) { int d=0; rec(root, d); return d; } int rec(TreeNode* root, int &d) { if(root == NULL) return 0; int ld = rec(root->left, d); int rd = rec(root->right, d); d=max(d,ld+rd); return max(ld,rd)+1; }
318
120
/** Copyright (c) 2017, Philip Deegan. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Philip Deegan nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "maiken/app.hpp" #include "maiken/env.hpp" maiken::Application* maiken::Applications::getOrCreate(maiken::Project const& proj, std::string const& _profile, bool setup) KTHROW(mkn::kul::Exception) { std::string pDir(proj.dir().real()); std::string profile = _profile.empty() ? "@" : _profile; if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) { auto app = std::make_unique<Application>(proj, _profile); auto pp = app.get(); m_appPs.push_back(std::move(app)); m_apps[pDir][profile] = pp; if (setup) { mkn::kul::os::PushDir pushd(proj.dir()); pp->setup(); } } return m_apps[pDir][profile]; } maiken::Application* maiken::Applications::getOrCreateRoot(maiken::Project const& proj, std::string const& _profile, bool setup) KTHROW(mkn::kul::Exception) { std::string pDir(proj.dir().real()); std::string profile = _profile.empty() ? "@" : _profile; if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) { auto* pp = getOrCreate(proj, _profile, /*setup = */ false); pp->ro = 1; if (setup) { mkn::kul::os::PushDir pushd(proj.dir()); pp->setup(); } } return m_apps[pDir][profile]; } maiken::Application* maiken::Applications::getOrNullptr(std::string const& project) { uint32_t count = 0; Application* app = nullptr; for (auto const& p1 : m_apps) for (auto const& p2 : p1.second) { if (p2.second->project().root()[STR_NAME].Scalar() == project) { count++; app = p2.second; } } if (count > 1) { KEXIT(1, "Cannot deduce project version as") << " there are multiple versions in the dependency tree"; } return app; } mkn::kul::cli::EnvVar maiken::Application::PARSE_ENV_NODE(YAML::Node const& n, Application const& app) { return maiken::PARSE_ENV_NODE(n, app, app.project().file()); }
3,456
1,197
// c:/Users/user/Documents/Programming/Music/OnMei/Pitch/OnDo/a_Alias.hpp #pragma once using DoSuu = uint;
114
50
// genrollups.cpp : Defines the entry point for the console application. // #include "stdafx.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #if _WIN32 #include "../libbiokanga/commhdrs.h" #else #include "../libbiokanga/commhdrs.h" #endif const unsigned int cProgVer = 304; // increment with each release const int cRUmaxSpecies = 50; // max number of species handled // Caution: check genhyperconserved before changing the following.... const int cMaxNumRangeClasses = 28; // max number of range classes const int cMaxMatchDistSegments = 100; // max match distribution profile segments (applies if eProcModeOutspecies) const int cMaxNumIdentityClasses = 101; // 0-100% identity classes CStopWatch gStopWatch; CDiagnostics gDiagnostics; // for writing diagnostics messages to log file char gszProcName[_MAX_FNAME]; // process name // user selects one of following bin class range sets with '-c<rangeclass>' typedef enum eRCClass { eRCCFull = 0, // 20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+ eRCCReduced, // 20-49,50-99,100-149,150-199,200-249,250-299,300+ eRCCMinimal, // 20-49,50-99,100-199,200-299,300+ eRCCMinimalA, // 20-99,100-199,200+ eRCCMinimalB, // 20-49,50-99,100+ eRCCMinimalC // 100+ } etRCClass; // user selects one of following processing modes with '-m<mode>' typedef enum eRPMode { eRPMTotals = 0, eRPMRegional, eRPMLociBases, eRPMLociRegional, eRPMOutspeciesSummary } etRPMode; // user selects one of following generated results layout with '-l<layout>' // only applies if processing mode is eRPMOutspeciesSummary typedef enum eRPRsltLayout { eRPRsltStandard = 0, eRPRsltTable, eRPRsltSegDistRows, eRPRsltSegDistTables, eRPRsltSegDistCols, eRPRsltIdentDistCols, eRPRsltRegionTableA, eRPRsltRegionTable } etRPRsltLayout; // processing parameters passsed between functions typedef struct TAG_sProcParams { etRPMode Mode; // processing mode teFuncRegion Region; // genomic functional region to filter on bool bSegsExcludeMatch; // true if cores which 100% match outspecies are to be excluded from segment distributions etRCClass RangeClass; // into which range class characterisation bool bPercentages; // output as percentages int hRsltsFile; // results file handle char *pszRsltsFile; // results file name bool bHeaderOut; // true if results header has been written etRPRsltLayout RsltsLayout; // layout format to use if processing eRPMOutspeciesSummary int NumDistSegs; // number of distribution segments int NumSpecies; // number of species in szSpecies following char szSpecies[cRUmaxSpecies][cMaxDatasetSpeciesChrom]; // species names of interest int Align2Core; // must be at least this number of bases in alignment to count as aligned to a core double PCAlign2Core; // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 0%)"); double IDAlign2Core; // minimum identity (1..100) aligned to core to count as as aligned to core (default is 0%)"); double IDOSIdentity; // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)"); } tsProcParams; int InitRangeClasses(etRCClass RangeClass); char *RangeClass2Txt(etRCClass RangeClass); int Process(etRPMode Mode, // processing mode etRPRsltLayout RsltsLayout, // table layout to generate results into bool bSegsExcludeMatch, // true if cores which 100% match outspecies are to be excluded from segment distributions etRCClass RangeClass, // length range class teFuncRegion Region, // process this genomic functional region bool bPercentages, // results as percentages instead of counts int Align2Core, // must be at least this number of bases in alignment to count as aligned to a core double PCAlign2Core, // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 1%)"); double IDAlign2Core, // minimum identity (1..100) aligned to core to count as as aligned to core (default is 1%)"); double dIDOSIdentity, // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)"); char *pszInputFiles, // process from this/these inputfiles - can contain wildcards char *pszOutputFile); // results into this file bool ProcessThisFile(char *pszFile,void *pParams); // will be ptr to tsProcParams int WriteRsltsHeader(tsProcParams *pParams); int ParseFileNameSpecies(char *pszFile, // filename to parse for ref+rel species char *pszClass, // user supplied buffer to hold element class (NULL allowed) char *pszRefSpecies, // user supplied buffer to hold ref species name char *pszRelSpecies, // user supplied buffer to hold rel species names char *pszType); // user supplied buffer to hold element type (NULL allowed) char *Mode2Text(etRPMode Mode); char *Region2Text(int Region); int ProcessLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams); int ProcessLociLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams); int ProcessRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams); int ProcessLociRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams); int ProcessOutspeciesSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams); #ifdef _WIN32 int _tmain(int argc, char* argv[]) { // determine my process name _splitpath(argv[0],NULL,NULL,gszProcName,NULL); #else int main(int argc, const char** argv) { // determine my process name CUtility::splitpath((char *)argv[0],NULL,gszProcName); #endif int iScreenLogLevel; // level of screen diagnostics int iFileLogLevel; // level of file diagnostics char szLogFile[_MAX_PATH]; // write diagnostics to this file int Rslt; char szOutputFile[_MAX_PATH]; char szInputFile[_MAX_PATH]; etRPMode iMode; int iRegion; bool bPercentages; etRCClass RangeClass; bool bSegsExcludeMatch; etRPRsltLayout iRsltsLayout; // out species processing file format to generate int iAlign2Core; // at least this many bases aligned in outspecies for it to count as aligned to core double dPCAlign2Core; // minimum percentage (1..100) aligned to core to count as as aligned to core (default is 1%)"); double dIDAlign2Core; // minimum identity (1..100) aligned to core to count as as aligned to core (default is 1%)"); double dIDOSIdentity; // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 1%)"); // command line args struct arg_lit *help = arg_lit0("hH","help", "print this help and exit"); struct arg_lit *version = arg_lit0("v","version,ver", "print version information and exit"); struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug"); struct arg_int *ScreenLogLevel=arg_int0("S", "ScreenLogLevel", "<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug"); struct arg_file *LogFile = arg_file0("F","log","<file>", "diagnostics log file"); struct arg_file *InFile = arg_file1("i",NULL,"<file>", "input from .csv files"); struct arg_file *OutFile = arg_file1("o",NULL,"<file>", "output to rollup statistics file as CSV"); struct arg_int *Mode = arg_int0("m","mode","<int>", "processing mode - 0:Totals,1:Regional,2:Loci bases Totals, 3: Loci bases Regional, 4: Outspecies totals"); struct arg_int *Region = arg_int0("r","region","<int>", "which region, 0:IG,1:5'US,2:5'UTR,3:CDS,4:Intronic,5:3'UTR,6:3'DS,7:All (default is 7:All)"); struct arg_lit *SegsExcludeMatch = arg_lit0("s","segsmatchprof","exclude 100% match cores in segment distribution profiles"); struct arg_lit *Percentages = arg_lit0("p","percent", "generate results as percentages"); struct arg_int *Range = arg_int0("c","binclass","<int>", "range bin class characterisation - 0: full, 1: reduced, 2: minimal, 3: UCSCUltra 200+"); struct arg_int *RsltsLayout = arg_int0("l","layout","<int>", "File layout for results if out species processing - 0: row values, 1: column values, 2: Segment Distribution rows, 3: Segment Distribution tables, 4: Segment Distribution columns, 5: core identity columns, 6: regions"); struct arg_int *Align2Core = arg_int0("a","align2core","<int>","minimum bases in outspecies for alignment to count as aligned to core (default is 1)"); struct arg_dbl *PCAlign2Core = arg_dbl0("P","pcalign2core","<dbl>","minimum percentage bases aligned to core to count as as aligned to core (default is 0%)"); struct arg_dbl *IDAlign2Core = arg_dbl0("A","idalign2core","<dbl>","minimum identity to count as as aligned to core (default is 0%)"); struct arg_dbl *IDOSIdentity = arg_dbl0("k","osidentity","<dbl>","minimum outspecies identity ,matches/(matches+mismatches), to count as as aligned to core (default is 0%)"); struct arg_end *end = arg_end(20); void *argtable[] = {help,version,FileLogLevel,ScreenLogLevel,LogFile, InFile,OutFile, Mode,Region,SegsExcludeMatch,Percentages,Range,RsltsLayout, Align2Core,PCAlign2Core,IDAlign2Core,IDOSIdentity, end}; char **pAllArgs; int argerrors; argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs); if(argerrors >= 0) argerrors = arg_parse(argerrors,pAllArgs,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("\n%s ", gszProcName); arg_print_syntax(stdout,argtable,"\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); printf("\nNote: Parameters can be entered into a parameter file, one parameter per line."); printf("\n To invoke this parameter file then precede its name with '@'"); printf("\n e.g. %s @myparams.txt\n\n",gszProcName); exit(1); } /* special case: '--version' takes precedence error reporting */ if (version->count > 0) { printf("\n%s Version %d.%2.2d",gszProcName,cProgVer/100,cProgVer%100); exit(1); } if (!argerrors) { iScreenLogLevel = ScreenLogLevel->count ? ScreenLogLevel->ival[0] : eDLInfo; if(iScreenLogLevel < eDLNone || iScreenLogLevel > eDLDebug) { printf("\nError: ScreenLogLevel '-S%d' specified outside of range %d..%d",iScreenLogLevel,eDLNone,eDLDebug); exit(1); } if(FileLogLevel->count && !LogFile->count) { printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>'",FileLogLevel->ival[0]); exit(1); } iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo; if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug) { printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d",iFileLogLevel,eDLNone,eDLDebug); exit(1); } if(LogFile->count) { strncpy(szLogFile,LogFile->filename[0],_MAX_PATH); szLogFile[_MAX_PATH-1] = '\0'; } else { iFileLogLevel = eDLNone; szLogFile[0] = '\0'; } iMode = (etRPMode)(Mode->count ? Mode->ival[0] : eRPMTotals); if(iMode < eRPMTotals || iMode > eRPMOutspeciesSummary) { printf("\nError: Processing mode '-m%d' is not supported\n",(int)iMode); exit(1); } if(iMode == eRPMRegional || iMode == eRPMLociRegional) { iRegion = Region->count ? Region->ival[0] : eFRAuto; if(iRegion < eFRIntergenic || iRegion > eFRAuto) { printf("\nError: Region '-r%d' is not supported\n",iRegion); exit(1); } } else iRegion = eFRAuto; if(iMode == eRPMOutspeciesSummary) { iRsltsLayout = RsltsLayout->count ? (etRPRsltLayout)RsltsLayout->ival[0] : eRPRsltStandard; if(iRsltsLayout < eRPRsltStandard || iRsltsLayout > eRPRsltRegionTable) { printf("\nError: Results layout format '-x%d' is not supported\n",iRsltsLayout); exit(1); } iAlign2Core = Align2Core->count ? Align2Core->ival[0] : 1; if(iAlign2Core < 1) { printf("\nError: Aligned bases to core '-a%d' must be >= 1",iAlign2Core); exit(1); } dPCAlign2Core = PCAlign2Core->count ? PCAlign2Core->dval[0] : 0.0; if(dPCAlign2Core < 0.0 || dPCAlign2Core > 100.0) { printf("\nError: Minimum percentage aligned bases to core '-P%f' must be in range 0.0 to 100.0",dPCAlign2Core); exit(1); } dIDAlign2Core = IDAlign2Core->count ? IDAlign2Core->dval[0] : 0.0; if(dIDAlign2Core < 0.0 || dIDAlign2Core > 100.0) { printf("\nError: Minimum identity to core '-A%f' must be in range 0.0 to 100.0",dIDAlign2Core); exit(1); } dIDOSIdentity = IDOSIdentity->count ? IDOSIdentity->dval[0] : 0.0; if(dIDOSIdentity < 0.0 || dIDOSIdentity > 100.0) { printf("\nError: Minimum outspecies identity '-k%f' must be in range 0.0 to 100.0",dIDOSIdentity); exit(1); } } else { iRsltsLayout = eRPRsltStandard; iAlign2Core = 1; dIDAlign2Core = 0.0; dPCAlign2Core = 0.0; dIDOSIdentity = 0.0; } bSegsExcludeMatch = SegsExcludeMatch->count ? true : false; RangeClass = Range->count ? (etRCClass)Range->ival[0] : eRCCFull; if(RangeClass < eRCCFull || RangeClass > eRCCMinimalC) { printf("\nError: Range class characterisation '-c%d' is not supported\n",RangeClass); exit(1); } if(!InFile->count) { printf("\nError: Input files to process '-i<inputfilespec>' is not specified\n"); exit(1); } strcpy(szInputFile,InFile->filename[0]); if(!OutFile->count) { printf("\nError: Output file to generate '-o<outputfilespec>' is not specified\n"); exit(1); } strcpy(szOutputFile,OutFile->filename[0]); bPercentages = Percentages->count ? true : false; // now that command parameters have been parsed then initialise diagnostics log system if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true)) { printf("\nError: Unable to start diagnostics subsystem."); if(szLogFile[0] != '\0') printf(" Most likely cause is that logfile '%s' can't be opened/created",szLogFile); exit(1); } gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %d.%2.2d Processing parameters:",cProgVer/100,cProgVer%100); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing Mode: '%s'",Mode2Text(iMode)); if(iMode == eRPMOutspeciesSummary) { gDiagnostics.DiagOutMsgOnly(eDLInfo,"Segment distribution profiles to exclude 100%% identity cores: %s", bSegsExcludeMatch ? "yes" : "no"); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Generated processed results layout format: %d",iRsltsLayout); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Alignments must have at least : %d bases",iAlign2Core); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum percentage bases must be least : %1.2f%% ",dPCAlign2Core); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum identity at least : %1.2f%%",dIDAlign2Core); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum outspecies identity at least : %1.2f%%",dIDOSIdentity); } gDiagnostics.DiagOutMsgOnly(eDLInfo,"Range Classes: %s",RangeClass2Txt(RangeClass)); if(iMode == eRPMRegional || iMode == eRPMLociRegional) gDiagnostics.DiagOutMsgOnly(eDLInfo,"Region: %d - '%s'",iMode,Region2Text(iRegion)); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Results as percentages: '%s'",bPercentages ? "yes" : "no"); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input filespec: '%s'",szInputFile); gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output file: '%s'",szOutputFile); gStopWatch.Start(); #ifdef _WIN32 SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); #endif Rslt = Process(iMode,iRsltsLayout,bSegsExcludeMatch,RangeClass,(teFuncRegion)iRegion,bPercentages,iAlign2Core,dPCAlign2Core,dIDAlign2Core,dIDOSIdentity,szInputFile,szOutputFile); gStopWatch.Stop(); Rslt = Rslt < 0 ? 1 : 0; gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit Code: %d Total processing time: %s",Rslt,gStopWatch.Read()); exit(Rslt); } else { arg_print_errors(stdout,end,gszProcName); arg_print_syntax(stdout,argtable,"\nend of help\n"); exit(1); } } char * RangeClass2Txt(etRCClass RangeClass) { switch(RangeClass) { case eRCCFull: return((char *)"20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+"); case eRCCReduced: return((char *)"20-49,50-99,100-149,150-199,200-249,250-299,300+"); case eRCCMinimal: return((char *)"20-49,50-99,100-199,200-299,300+"); case eRCCMinimalA: return((char *)"20-99,100-199,200+"); case eRCCMinimalB: return((char *)"20-49,50-99,100+"); case eRCCMinimalC: return((char *)"100+"); default: return((char *)"Undefined"); } } int Process(etRPMode Mode, // processing mode etRPRsltLayout RsltsLayout, // table layout to generate results into bool bSegsExcludeMatch, // true if cores which 100% match outspecies are to be excluded from segment distributions etRCClass RangeClass, // length range class teFuncRegion Region, // process this genomic functional region bool bPercentages, // results as percentages instead of counts int Align2Core, // must be at least this many bases in alignment to count as an alignment double PCAlign2Core, // minimum percentage (0..100) aligned to core to count as as aligned to core (default is 0%)"); double IDAlign2Core, // minimum identity (0..100) aligned to core to count as as aligned to core (default is 0%)"); double IDOSIdentity, // minimum outspecies (matches/matchesPlusmismatches) (1..100) aligned to core to count as as aligned to core (default is 0%)"); char *pszInputFiles, // process from this/these inputfiles - can contain wildcards char *pszOutputFile) // results into this file { int Rslt; char szDirPath[_MAX_PATH]; char szFileSpec[_MAX_PATH]; #ifndef _WIN32 struct stat FileStat; #endif tsProcParams ProcParams; memset(&ProcParams,0,sizeof(tsProcParams)); ProcParams.Mode = Mode; ProcParams.RsltsLayout = RsltsLayout; ProcParams.bSegsExcludeMatch = bSegsExcludeMatch; ProcParams.RangeClass = RangeClass; ProcParams.pszRsltsFile = pszOutputFile; ProcParams.bPercentages = bPercentages; ProcParams.Align2Core = Align2Core; ProcParams.PCAlign2Core = PCAlign2Core; ProcParams.IDAlign2Core= IDAlign2Core; ProcParams.IDOSIdentity = IDOSIdentity; #ifdef _WIN32 char szDrive[_MAX_DRIVE]; char szDir[_MAX_DIR]; char szFname[_MAX_FNAME]; char szExt[_MAX_EXT]; _splitpath(pszInputFiles,szDrive,szDir,szFname,szExt); _makepath(szDirPath,szDrive,szDir,"",""); if(!szFname[0]) strcpy(szFname,"*"); if(!szExt[0]) strcpy(szExt,".*"); sprintf(szFileSpec,"%s%s",szFname,szExt); #else CUtility::splitpath(pszInputFiles,szDirPath,szFileSpec); if(!szFileSpec[0]) strcpy(szFileSpec,"*"); #endif #ifdef _WIN32 if((ProcParams.hRsltsFile = open(pszOutputFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1) #else if((ProcParams.hRsltsFile = open(pszOutputFile,O_RDWR | O_CREAT |O_TRUNC, S_IREAD | S_IWRITE ))==-1) #endif { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to create %s - %s",pszOutputFile,strerror(errno)); return(eBSFerrCreateFile); } ProcParams.Region = Region; if((Mode == eRPMRegional || Mode == eRPMLociRegional) && Region == eFRAuto) // process all regions { Rslt = eBSFSuccess; for(int iRegion = eFRIntergenic; iRegion <= eFRDnstream; iRegion++) { ProcParams.Region = (teFuncRegion)iRegion; CSimpleGlob glob(SG_GLOB_FULLSORT); if (glob.Add(pszInputFiles) >= SG_SUCCESS) { for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n) gDiagnostics.DiagOut(eDLInfo,gszProcName,"Will process in this order: %d '%s", n+1,glob.File(n)); for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n) Rslt = ProcessThisFile(glob.File(n),&ProcParams); } else { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to glob '%s",pszInputFiles); Rslt = eBSFerrOpnFile; // treat as though unable to open file } if(Rslt < eBSFSuccess) break; } } else { Rslt = eBSFSuccess; CSimpleGlob glob(SG_GLOB_FULLSORT); if (glob.Add(pszInputFiles) >= SG_SUCCESS) { for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n) gDiagnostics.DiagOut(eDLInfo,gszProcName,"Will process in this order: %d '%s", n+1,glob.File(n)); for (int n = 0; Rslt >= eBSFSuccess && n < glob.FileCount(); ++n) Rslt = ProcessThisFile(glob.File(n),&ProcParams); } else { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to glob '%s",pszInputFiles); Rslt = eBSFerrOpnFile; // treat as though unable to open file } } if(ProcParams.hRsltsFile != -1) close(ProcParams.hRsltsFile); return(Rslt); } bool ProcessThisFile(char *pszFile,void *pParams) { tsProcParams *pProcParams = (tsProcParams *)pParams; CCSVFile *pCSV = new CCSVFile; int Rslt; InitRangeClasses(pProcParams->RangeClass); pCSV->SetMaxFields(15 + (cMaxMatchDistSegments*4)); if((Rslt=pCSV->Open(pszFile))!=eBSFSuccess) { while(pCSV->NumErrMsgs()) gDiagnostics.DiagOut(eDLFatal,gszProcName,pCSV->GetErrMsg()); gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open file: %s",pszFile); return(false); } gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing File: %s",pszFile); switch(pProcParams->Mode) { case eRPMTotals: // process length summary files Rslt = ProcessLengthSummary(pszFile,pCSV,pProcParams); break; case eRPMRegional: Rslt = ProcessRegionalLengthSummary(pszFile,pCSV,pProcParams); break; case eRPMLociBases: // process loci length summary files Rslt = ProcessLociLengthSummary(pszFile,pCSV,pProcParams); break; case eRPMLociRegional: Rslt = ProcessLociRegionalLengthSummary(pszFile,pCSV,pProcParams); break; case eRPMOutspeciesSummary: Rslt = ProcessOutspeciesSummary(pszFile,pCSV,pProcParams); break; } delete pCSV; return(Rslt >= eBSFSuccess ? true : false); } // ParseFileNameSpecies // parse filename to determine reference and relative species --- UGH!!! // Expected filename format is - // <Class><RefSpecies><RelSpecies>_<Type>*.csv // <Class> 'L' or 'S' but could be some other single char // <RefSpecies> species name with the last one or two chars digits e.g. hg17 // <RelSpecies> concatenated species names, last species name is terminated by an underscore '_' // <Type> currently 'u' for ultra or 'h' for hyper int ParseFileNameSpecies(char *pszFile, // filename to parse for ref+rel species char *pszClass, // user supplied buffer to hold element class char *pszRefSpecies, // user supplied buffer to hold ref species name char *pszRelSpecies, // user supplied buffer to hold rel species names char *pszType) // user supplied buffer to hold element type { char *pSrcChr; char *pDstChr; char Chr; bool bParseRef; bool bParsedRef; bool bParseRel; bool bParsedRel; bool bDigit; char szFname[256]; char szDir[256]; #ifdef _WIN32 char szDrive[_MAX_DRIVE]; char szExt[_MAX_EXT]; _splitpath(pszFile,szDrive,szDir,szFname,szExt); #else CUtility::splitpath(pszFile,szDir,szFname); #endif if(pszClass != NULL) switch(szFname[0]) { case 's': case 'S': strcpy(pszClass,"summary"); break; case 'l': case 'L': strcpy(pszClass,"loci"); break; default: *pszClass = szFname[0]; pszClass[1] = '\0'; break; } pSrcChr = &szFname[1]; pDstChr = pszRefSpecies; bParseRef = true; bParsedRef = false; bParseRel = false; bParsedRel = false; bDigit = false; *pszRefSpecies = '\0'; *pszRelSpecies = '\0'; while(Chr = *pSrcChr++) { if(Chr == '_') { bParsedRel = true; *pDstChr = '\0'; if(pszType != NULL) { if((Chr = *pSrcChr) == '\0') { *pszType = '?'; pszType[1] = '\0'; } else switch(Chr) { case 'u': case 'U': strcpy(pszType,"ultra"); break; case 'h': case 'H': strcpy(pszType,"hyper"); break; default: *pszType = Chr; pszType[1] = '\0'; break; } } break; } if(bParseRef) { if(Chr >= '0' && Chr <= '9') bDigit = true; else { if(bDigit) // was previously parsing digits but not now then that means rel species starting { *pDstChr = '\0'; bParseRef = false; bParsedRef = true; bParseRel = true; pDstChr = pszRelSpecies; } } } *pDstChr++ = Chr; } if(!(bParsedRef && bParsedRel)) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to parse filename '%s' into ref+rel species names",szFname); return(eBSFerrFileName); } return(eBSFSuccess); } // ParseNumSpecies // Initialises pProcParams with parsed species names in space or comma delimited list ptd at by pszSpeciesList // Returns number of species int ParseNumSpecies(char *pszSpeciesList,tsProcParams *pProcParams) { // parse out species list char Chr; char *pSpecies; int NumSpecies = 0; bool InToken = false; if(pszSpeciesList == NULL || *pszSpeciesList == '\0') return(0); while(Chr = *pszSpeciesList++) { if(Chr == '"' || Chr == '\'') // change any single or double quotes into spaces Chr = ' '; if(isspace(Chr) || Chr==',') { if(!InToken) // slough whitespace or ',' if not inside a token parse continue; InToken = false; pszSpeciesList[-1] = '\0'; if(pProcParams != NULL) { strncpy(pProcParams->szSpecies[NumSpecies],pSpecies,cMaxDatasetSpeciesChrom); pProcParams->szSpecies[NumSpecies][cMaxDatasetSpeciesChrom-1] = '\0'; } pszSpeciesList[-1] = Chr; NumSpecies++; if(NumSpecies >= cRUmaxSpecies) break; continue; } if(!InToken) // if not already inside token then start token { pSpecies = pszSpeciesList-1; InToken = true; } } if(InToken) { pszSpeciesList[-1] = '\0'; if(pProcParams != NULL) { strncpy(pProcParams->szSpecies[NumSpecies],pSpecies,cMaxDatasetSpeciesChrom); pProcParams->szSpecies[NumSpecies][cMaxDatasetSpeciesChrom-1] = '\0'; } pszSpeciesList[-1] = Chr; NumSpecies++; } return(NumSpecies); } char * Mode2Text(etRPMode Mode) { switch(Mode) { case eRPMTotals: return((char *)"Totals summary"); case eRPMRegional: return((char *)"Regional summary"); case eRPMLociBases: return((char *)"Loci bases Totals summary"); case eRPMLociRegional: return((char *)"Loci bases Regional summary"); case eRPMOutspeciesSummary: return((char *)"Out species summary"); default: break; } gDiagnostics.DiagOut(eDLInfo,gszProcName,"Unsupported processing mode '%d' requested",(int)Mode); return((char *)"Unsupported"); } // Regions can be overlapping // feature bits - note that features can concurrently overlap multiple gene components // bit 0 (0x01) part of feature overlaps CDS // bit 1 (0x02) part of feature overlaps 5'UTR // bit 2 (0x04) part of feature overlaps 3'UTR // bit 3 (0x08) part of feature overlaps Intron // bit 4 (0x10) part of feature overlaps 5'upstream regulatory // bit 5 (0x20) part of feature overlaps 3'downstream regulatory // bit 6 (x040) part of feature overlaps intron5'/3'exon splice site // bit 7 (0x80) part of feature overlaps exon5'/3'intron splice site // Normalise regions maps regions into a logical index // Intergenic -> 0 // US -> 1 // 5'UTR -> 2 // CDS -> 3 // INTRON -> 4 // 3'UTR -> 5 // DS -> 6 int NormaliseRegion(int Region) { if(Region & cFeatBitCDS) return(eFRCDS); // CDS if(Region & cFeatBit5UTR) return(eFR5UTR); // 5'UTR if(Region & cFeatBit3UTR) return(eFR3UTR); // 3'UTR if(Region & cFeatBitIntrons) return(eFRIntronic); // Intron if(Region & cFeatBitUpstream) return(eFRUpstream); // 5'US if(Region & cFeatBitDnstream) return(eFRDnstream); // 3'DS return(eFRIntergenic); // IG } char * Region2Text(int Region) { switch(Region) { case 0: return((char *)"IG"); case 1: return((char *)"US"); case 2: return((char *)"5'UTR"); case 3: return((char *)"CDS"); case 4: return((char *)"INTRON"); case 5: return((char *)"3'UTR"); case 6: return((char *)"DS"); case 7: return((char *)"ANY"); default: break; } gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unsupported region '%d' requested",Region); return((char *)"Unsupported"); } int WriteRsltsHeader(tsProcParams *pParams) { char szLineBuff[2048]; int Len; int SegIdx; if(pParams->bHeaderOut) // if header already written? return(eBSFSuccess); if(pParams->hRsltsFile == -1) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Results file '%s' was closed when called to write headers",pParams->pszRsltsFile); return(eBSFerrFileClosed); } switch(pParams->Mode) { case eRPMTotals: case eRPMLociBases: Len = sprintf(szLineBuff,"\"ElType\",\"Ref Species\",\"Rel Species\",\"Total\""); break; case eRPMRegional: case eRPMLociRegional: Len = sprintf(szLineBuff,"\"ElType\",\"Ref Species\",\"Rel Species\",\"Region\",\"Total\""); break; case eRPMOutspeciesSummary: switch(pParams->RsltsLayout) { case eRPRsltStandard: Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"Region\",\"Qualifier\",\"Name\",\"Value\"\n"); break; case eRPRsltTable: Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"Aligned Core %%\",\"Aligned Bases\",\"Aligned Mismatches\",\"Aligned Identical\",\"Aligned Identity\"\n"); break; case eRPRsltSegDistRows: Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\""); for(SegIdx = 0; SegIdx < pParams->NumDistSegs; SegIdx++) Len += sprintf(&szLineBuff[Len],",\"Seg%dMatches\",\"Seg%dMismatches\",\"Seg%dInDels\",\"Seg%dUnaligns\"", SegIdx+1,SegIdx+1,SegIdx+1,SegIdx+1); Len += sprintf(&szLineBuff[Len],"\n"); break; case eRPRsltSegDistTables: Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Category\""); for(SegIdx = 1; SegIdx <= pParams->NumDistSegs; SegIdx++) Len += sprintf(&szLineBuff[Len],",\"Segment%d\"",SegIdx); Len += sprintf(&szLineBuff[Len],"\n"); break; case eRPRsltSegDistCols: Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Segment\",\"Matches\",\"Mismatches\",\"InDels\",\"Unaligned\"\n"); break; case eRPRsltIdentDistCols: Len = sprintf(szLineBuff,"\"ElType\",\"RefSpecies\",\"CoreSpecies\",\"OutSpecies\",\"LengthRange\",\"Core Instances\",\"OG Instances\",\"Identity\",\"OG Identity Instances\"\n"); break; case eRPRsltRegionTable: Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"IG\",\"US\",\"5'UTR\",\"CDS\",\"INTRON\",\"3'UTR\",\"DS\",\"5'ExSplice\",\"3'ExSplice\"\n"); break; case eRPRsltRegionTableA: Len = sprintf(szLineBuff,"\"Core Set\",\"Out Species\",\"Ref Core Len\",\"Ref Core Cnt\",\"Aligned Cnt\",\"IG\",\"US\",\"5'UTR\",\"CDS\",\"INTRON\",\"3'UTR\",\"DS\",\"5'ExSplice\",\"3'ExSplice\",\"Excl IG\",\"Excl US\",\"Excl 5'UTR\",\"Excl CDS\",\"Excl INTRON\",\"Excl 3'UTR\",\"Excl DS\",\"Splice Sites\"\n"); break; default: Len = sprintf(szLineBuff,",\"Illegal Layout\"\n"); break; } break; default: Len = sprintf(szLineBuff,",\"Illegal Mode\""); } if(pParams->Mode != eRPMOutspeciesSummary) switch(pParams->RangeClass) { case eRCCFull: Len += sprintf(&szLineBuff[Len],",\"20-29\",\"30-49\",\"50-74\",\"75-99\",\"100-124\",\"125-149\",\"150-174\",\"175-199\""); Len += sprintf(&szLineBuff[Len],",\"200-249\",\"250-299\",\"300-349\",\"350-399\",\"400-449\",\"450-499\""); Len += sprintf(&szLineBuff[Len],",\"500-599\",\"600-699\",\"700-799\",\"800-899\",\"900-999\""); Len += sprintf(&szLineBuff[Len],",\"1000-1249\",\"1250-1499\",\"1500-1749\",\"1750-1999\",\"2000+\""); break; case eRCCReduced: Len += sprintf(&szLineBuff[Len],",\"20-49\",\"50-99\",\"100-149\",\"150-199\",\"200-249\",\"250-299\",\"300+\""); break; case eRCCMinimal: Len += sprintf(&szLineBuff[Len],",\"20-49\",\"50-99\",\"100-199\",\"200-299\",\"300+\""); break; case eRCCMinimalA: Len += sprintf(&szLineBuff[Len],",\"20-99\",\"100-199\",\"200+\""); break; case eRCCMinimalB: Len += sprintf(&szLineBuff[Len],",\"20-49\",\"59-99\",\"100+\""); break; case eRCCMinimalC: Len += sprintf(&szLineBuff[Len],",\"100+\""); break; default: Len += sprintf(&szLineBuff[Len],",\"Illegal Range Class\""); break; } if(Len && (write(pParams->hRsltsFile,szLineBuff,Len)!=Len)) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } pParams->bHeaderOut = true; return(eBSFSuccess); } int ProcessLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams) { int Rslt; int NumRows; int NumFields; int Len; char *pszRange; int RangeCnt; int Total; int Totals[cMaxNumRangeClasses]; // to hold all totals int Idx; char szLineBuff[2048]; char szRefSpecies[200]; char szRelSpecies[200]; char szElementType[20]; if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess) return(Rslt); // Skip first row as that contains titles if((Rslt=pCSV->NextLine())<12) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 header fields in 1st row of '%s', NextLine returned '%d'",pszFile,Rslt); return(eBSFerrFieldCnt); } // subsequent rows contain fields of interest memset(Totals,0,sizeof(Totals)); NumRows = 0; Total = 0; while((Rslt=pCSV->NextLine()) == 12) // onto next line containing fields { if(NumRows == cMaxNumRangeClasses) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected only 28 rows (plus header) in '%s', file has more rows",pszFile); return(eBSFerrRowCnt); } NumFields = pCSV->GetCurFields(); if(NumFields != 12) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 12 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields); return(eBSFerrFieldCnt); } pCSV->GetText(1,&pszRange); pCSV->GetInt(3,&RangeCnt); switch(pParams->RangeClass) { case eRCCFull: Totals[NumRows] = RangeCnt; break; case eRCCReduced: switch(NumRows) { case 0: // 0-4 Totals[0] = RangeCnt; break; case 1: // 5-9 Totals[0] += RangeCnt; break; case 2: // 10-14 Totals[1] = RangeCnt; break; case 3: // 15-19 Totals[1] += RangeCnt; break; case 4: // 20-29 Totals[2] = RangeCnt; break; case 5: // 30-49 Totals[2] += RangeCnt; break; case 6: // 50-74 Totals[3] = RangeCnt; break; case 7: // 75-99 Totals[3] += RangeCnt; break; case 8: // 100-124 Totals[4] = RangeCnt; break; case 9: // 125-149 Totals[4] += RangeCnt; break; case 10: // 150-174 Totals[5] = RangeCnt; break; case 11: // 175-199 Totals[5] += RangeCnt; break; case 12: // 200-249 Totals[6] = RangeCnt; break; case 13: // 250-300 Totals[7] = RangeCnt; Totals[8] = 0; break; default: Totals[8] += RangeCnt; break; } break; case eRCCMinimal: switch(NumRows) { case 0: // 0-4 Totals[0] += RangeCnt; break; case 1: case 2: case 3: // 5-9, 10-14,15-19 Totals[0] += RangeCnt; break; case 4: // 20-29 Totals[1] += RangeCnt; break; case 5: // 30-49 Totals[1] += RangeCnt; break; case 6: // 50-74 Totals[2] += RangeCnt; break; case 7: // 75-99 Totals[2] += RangeCnt; break; case 8: // 100-124 Totals[3] += RangeCnt; break; case 9: case 10: case 11: // 125-149, 150-174,175-199 Totals[3] += RangeCnt; break; case 12: // 200-249 Totals[4] = RangeCnt; break; case 13: // 250-300 Totals[4] += RangeCnt; break; default: Totals[5] += RangeCnt; break; } break; case eRCCMinimalA: switch(NumRows) { case 0: case 1: case 2: case 3: // 0-20 Totals[0] += RangeCnt; break; case 4: case 5: case 6: case 7: // 20-99 Totals[1] += RangeCnt; break; case 8: case 9: case 10: case 11: // 100-199 Totals[2] += RangeCnt; break; default: Totals[3] += RangeCnt; break; } break; case eRCCMinimalB: switch(NumRows) { case 0: case 1: case 2: case 3: // 0-20 Totals[0] += RangeCnt; break; case 4: case 5: // 20-49 Totals[1] += RangeCnt; break; case 6: case 7: // 50-99 Totals[2] += RangeCnt; break; default: // 100+ Totals[3] += RangeCnt; break; } break; case eRCCMinimalC: switch(NumRows) { case 0: case 1: case 2: case 3: // 0-20 case 4: case 5: // 20-49 case 6: case 7: // 50-99 break; default: // 100+ Totals[0] += RangeCnt; break; } break; } NumRows++; } if(NumRows != cMaxNumRangeClasses) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 28 rows (plus header) in '%s', only '%d' parsed",pszFile,NumRows); return(eBSFerrRowCnt); } switch(pParams->RangeClass) { case eRCCFull: for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCReduced: for(Idx = 2; Idx < 9; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 2; Idx < 9; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimal: for(Idx = 1; Idx < 6; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 6; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalA: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalB: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalC: Total += Totals[0]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]); break; default: Len=sprintf(szLineBuff,",-1"); break; } WriteRsltsHeader(pParams); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } typedef struct TAG_sLenRangeClass { int ID; // uniquely identifies this range int Min; // minimum length in this range int Max; // maximum length in this range const char *pszDescr; // descriptive text }tsLenRangeClass; // length range classes tsLenRangeClass LenRangeClassesFull[] = { {1,0,4,"0-4"}, {2,5,9,"5-9"}, {3,10,14,"10-14"}, {4,15,19,"15-19"}, {5,20,29,"20-29"}, {6,30,49,"30-49"}, {7,50,74,"50-74"}, {8,75,99,"75-99"}, {9,100,124,"100-124"}, {10,125,149,"125-149"}, {11,150,174,"150-174"}, {12,175,199,"175-199"}, {13,200,249,"200-249"}, {14,250,299,"250-299"}, {15,300,349,"300-349"}, {16,350,399,"350-399"}, {17,400,449,"400-449"}, {18,450,499,"450-499"}, {19,500,599,"500-599"}, {20,600,699,"600-699"}, {21,700,799,"700-799"}, {22,800,899,"800-899"}, {23,900,999,"900-999"}, {24,1000,1249,"1000-1249"}, {25,1250,1499,"1250-1499"}, {26,1500,1749,"1500-1749"}, {27,1750,1999,"1750-1999"}, {28,2000,INT_MAX,"2000+"} }; const int cLenRangesFull = sizeof(LenRangeClassesFull)/sizeof(tsLenRangeClass); // number of length range classes tsLenRangeClass LenRangeClassesReduced[] = { {1,0,9,"0-9"}, {2,10,19,"10-19"}, {3,20,49,"20-49"}, {4,50,99,"50-99"}, {5,100,149,"100-149"}, {6,150,199,"150-199"}, {7,200,249,"200-249"}, {8,250,299,"250-299"}, {9,300,INT_MAX,"300+"} }; const int cLenRangesReduced = sizeof(LenRangeClassesReduced)/sizeof(tsLenRangeClass); // number of length range classes tsLenRangeClass LenRangeClassesMinimal[] = { {1,0,19,"0-19"}, {2,20,49,"20-49"}, {3,50,99,"50-99"}, {4,100,199,"100-199"}, {5,200,299,"200-299"}, {6,300,INT_MAX,"300+"} }; const int cLenRangesMinimal = sizeof(LenRangeClassesMinimal)/sizeof(tsLenRangeClass); tsLenRangeClass LenRangeClassesMinimalA[] = { {1,0,19,"0-19"}, {2,20,99,"20-99"}, {3,100,199,"100-199"}, {4,200,INT_MAX,"200+"} }; const int cLenRangesMinimalA = sizeof(LenRangeClassesMinimalA)/sizeof(tsLenRangeClass); tsLenRangeClass LenRangeClassesMinimalB[] = { {1,0,19,"0-19"}, {2,20,49,"20-49"}, {3,50,99,"50-99"}, {4,100,INT_MAX,"100+"} }; const int cLenRangesMinimalB = sizeof(LenRangeClassesMinimalB)/sizeof(tsLenRangeClass); tsLenRangeClass LenRangeClassesMinimalC[] = { {1,100,INT_MAX,"100+"} }; const int cLenRangesMinimalC = sizeof(LenRangeClassesMinimalC)/sizeof(tsLenRangeClass); tsLenRangeClass *pLenRangeClasses = LenRangeClassesFull; int NumLenRanges = cLenRangesFull; int // returns number of ranges InitRangeClasses(etRCClass RangeClass) { switch(RangeClass) { case eRCCFull: // 20-29,30-49,50-74,75-99,100-124,125-149,150-174,175-199,200-249,250-299,300-349,350-399,400-449,450-499,500-599,600-699,700-799,800-899,900-999,1000-1249,1250-1499,1500-1749,1750-1999,2000+ pLenRangeClasses = LenRangeClassesFull; NumLenRanges = cLenRangesFull; break; case eRCCReduced: // 20-49,50-99,100-149,150-199,200-249,250-299,300+ pLenRangeClasses = LenRangeClassesReduced; NumLenRanges = cLenRangesReduced; break; case eRCCMinimal: // 20-49,50-99,100-199,200-299,300+ pLenRangeClasses = LenRangeClassesMinimal; NumLenRanges = cLenRangesMinimal; break; case eRCCMinimalA: // 20-99,100-199,200+ pLenRangeClasses = LenRangeClassesMinimalA; NumLenRanges = cLenRangesMinimalA; break; case eRCCMinimalB: // 20-49,50-99,100+ pLenRangeClasses = LenRangeClassesMinimalB; NumLenRanges = cLenRangesMinimalB; break; case eRCCMinimalC: // 100+ pLenRangeClasses = LenRangeClassesMinimalC; NumLenRanges = cLenRangesMinimalC; break; default: return(-1); } return(NumLenRanges); } // GetLengthRangeClass // Returns ptr to length range class for specified Length, or NULL if can't classify into a range tsLenRangeClass *GetLengthRangeClass(int Length) { int Idx; tsLenRangeClass *pRange = pLenRangeClasses; for(Idx = 0; Idx < NumLenRanges; Idx++,pRange++) if(Length >= pRange->Min && Length <= pRange->Max) return(pRange); return(NULL); } // Expected CSV format // ElementID Uniquely identifies this element (1..n) // CoreType Currently either 'hypercore' or 'ultracore' // Chromosome Chromosome on reference species // StartLoci Starting offset (0..n) on Chromosome // EndLoci Ending offset (StartLoci + length -1) on Chromosome // Length Element length // SpeciesList List of all species sharing this element, 1st species is the reference // Region In which region core is located // // There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option) // Unaligned Count of bases in outspecies not aligned // Matches Count of bases in outspecies which align and match // Mismatches Count of bases in outspecies which align but mismatch // InDels Count of bases in reference or outspecies which are InDels int ProcessLociLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams) { int Rslt; int NumRows; int NumFields; int Len; int Total; int Totals[cMaxNumRangeClasses]; // to hold all totals int Idx; char szLineBuff[2048]; char szRefSpecies[200]; char szRelSpecies[200]; char szElementType[20]; tsLenRangeClass *pRangeClass; int SeqLen; if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess) return(Rslt); // no headers, straight into the rows which are expected to contain 9 fields NumRows = 0; Total = 0; memset(Totals,0,sizeof(Totals)); while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields { NumFields = pCSV->GetCurFields(); if(NumFields < 9) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields); return(eBSFerrFieldCnt); } pCSV->GetInt(7,&SeqLen); pRangeClass = GetLengthRangeClass(SeqLen); Totals[pRangeClass->ID-1] += SeqLen; NumRows++; } switch(pParams->RangeClass) { case eRCCFull: for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCReduced: for(Idx = 2; Idx < 9; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 2; Idx < 9; Idx++) if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimal: for(Idx = 1; Idx < 6; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 6; Idx++) if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalA: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalB: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalC: Total += Totals[0]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,Total); if(pParams->bPercentages) { Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0); } else Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]); break; default: Len=sprintf(szLineBuff,",-1"); break; } WriteRsltsHeader(pParams); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } int ProcessRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams) { int Rslt; int NumRows; int NumFields; int Len; char *pszRange; int RangeCnt; int Total; int Totals[cMaxNumRangeClasses]; // to hold all totals int Idx; char szLineBuff[2048]; char szRefSpecies[200]; char szRelSpecies[200]; char szClass[20]; char szElementType[20]; char *pszRegion; pszRegion = Region2Text(pParams->Region); if((Rslt=ParseFileNameSpecies(pszFile,szClass,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess) return(Rslt); // Skip first row as that contains titles if((Rslt=pCSV->NextLine())<12) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 header fields in 1st row of '%s', NextLine returned '%d'",pszFile,Rslt); return(eBSFerrFieldCnt); } // subsequent rows contain fields of interest memset(Totals,0,sizeof(Totals)); NumRows = 0; Total = 0; while((Rslt=pCSV->NextLine()) == 12) // onto next line containing fields { if(NumRows == cMaxNumRangeClasses) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected only 28 rows (plus header) in '%s', file has more rows",pszFile); return(eBSFerrRowCnt); } NumFields = pCSV->GetCurFields(); if(NumFields < 12) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 12 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields); return(eBSFerrFieldCnt); } pCSV->GetText(1,&pszRange); pCSV->GetInt(pParams->Region+4,&RangeCnt); switch(pParams->RangeClass) { case eRCCFull: Totals[NumRows] = RangeCnt; break; case eRCCReduced: switch(NumRows) { case 0: // 0-4 Totals[0] = RangeCnt; break; case 1: // 5-9 Totals[0] += RangeCnt; break; case 2: // 10-14 Totals[1] = RangeCnt; break; case 3: // 15-19 Totals[1] += RangeCnt; break; case 4: // 20-29 Totals[2] = RangeCnt; break; case 5: // 30-49 Totals[2] += RangeCnt; break; case 6: // 50-74 Totals[3] = RangeCnt; break; case 7: // 75-99 Totals[3] += RangeCnt; break; case 8: // 100-124 Totals[4] = RangeCnt; break; case 9: // 125-149 Totals[4] += RangeCnt; break; case 10: // 150-174 Totals[5] = RangeCnt; break; case 11: // 175-199 Totals[5] += RangeCnt; break; case 12: // 200-249 Totals[6] = RangeCnt; break; case 13: // 250-300 Totals[7] = RangeCnt; Totals[8] = 0; break; default: Totals[8] += RangeCnt; break; } break; case eRCCMinimal: switch(NumRows) { case 0: // 0-4 Totals[0] = RangeCnt; break; case 1: case 2: case 3: // 5-9, 10-14,15-19 Totals[0] += RangeCnt; break; case 4: // 20-29 Totals[1] = RangeCnt; break; case 5: // 30-49 Totals[1] += RangeCnt; break; case 6: // 50-74 Totals[2] = RangeCnt; break; case 7: // 75-99 Totals[2] += RangeCnt; break; case 8: // 100-124 Totals[3] = RangeCnt; break; case 9: case 10: case 11: // 125-149, 150-174,175-199 Totals[3] += RangeCnt; break; case 12: // 200-249 Totals[4] = RangeCnt; break; case 13: // 250-300 Totals[4] += RangeCnt; Totals[5] = 0; break; default: Totals[5] += RangeCnt; break; } break; case eRCCMinimalA: switch(NumRows) { case 0: case 1: case 2: case 3: // < 20 Totals[0] += RangeCnt; break; case 4: case 5: case 6: case 7: // 20-99 Totals[1] += RangeCnt; break; case 8: case 9: case 10: case 11: // 100-199 Totals[2] += RangeCnt; break; default: Totals[3] += RangeCnt; break; } break; case eRCCMinimalB: switch(NumRows) { case 0: case 1: case 2: case 3: // < 20 Totals[0] += RangeCnt; break; case 4: case 5: // 20-49 Totals[1] += RangeCnt; break; case 6: case 7: // 50-99 Totals[2] += RangeCnt; break; default: Totals[3] += RangeCnt; break; } break; case eRCCMinimalC: switch(NumRows) { case 0: case 1: case 2: case 3: // < 20 break; case 4: case 5: // 20-49 break; case 6: case 7: // 50-99 break; default: Totals[0] += RangeCnt; break; } break; } NumRows++; } if(NumRows != cMaxNumRangeClasses) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected 28 rows (plus header) in '%s', only '%d' parsed",pszFile,NumRows); return(eBSFerrRowCnt); } switch(pParams->RangeClass) { case eRCCFull: for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCReduced: for(Idx = 2; Idx < 9; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 2; Idx < 9; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimal: for(Idx = 1; Idx < 6; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 6; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalA: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalB: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalC: Total += Totals[0]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]); break; default: Len=sprintf(szLineBuff,",-1"); break; } WriteRsltsHeader(pParams); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // Expected CSV format // ElementID Uniquely identifies this element (1..n) // CoreType Currently either 'hypercore' or 'ultracore' // Chromosome Chromosome on reference species // StartLoci Starting offset (0..n) on Chromosome // EndLoci Ending offset (StartLoci + length -1) on Chromosome // Length Element length // SpeciesList List of all species sharing this element, 1st species is the reference // Region In which region core is located // // There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option) // Unaligned Count of bases in outspecies not aligned // Matches Count of bases in outspecies which align and match // Mismatches Count of bases in outspecies which align but mismatch // InDels Count of bases in reference or outspecies which are InDels int ProcessLociRegionalLengthSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams) { int Rslt; int NumRows; int NumFields; int Len; int Total; int Totals[cMaxNumRangeClasses]; // to hold all totals int Idx; char szLineBuff[2048]; char szRefSpecies[200]; char szRelSpecies[200]; char szElementType[20]; tsLenRangeClass *pRangeClass; int SeqLen; int Region; int NormRegion; char *pszRegion; pszRegion = Region2Text(pParams->Region); if((Rslt=ParseFileNameSpecies(pszFile,NULL,szRefSpecies,szRelSpecies,szElementType))!=eBSFSuccess) return(Rslt); // no headers, straight into the rows which are expected to contain at least 9 fields NumRows = 0; Total = 0; memset(Totals,0,sizeof(Totals)); while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields { NumFields = pCSV->GetCurFields(); if(NumFields < 9) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in '%s', GetCurFields() returned '%d'",pszFile,NumFields); return(eBSFerrFieldCnt); } pCSV->GetInt(9,&Region); NormRegion = NormaliseRegion(Region); if(pParams->Region != eFRAuto && pParams->Region != NormRegion) continue; pCSV->GetInt(7,&SeqLen); pRangeClass = GetLengthRangeClass(SeqLen); Totals[pRangeClass->ID-1] += SeqLen; NumRows++; } switch(pParams->RangeClass) { case eRCCFull: for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 4; Idx < cMaxNumRangeClasses; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCReduced: for(Idx = 2; Idx < 9; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 2; Idx < 9; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimal: for(Idx = 1; Idx < 6; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 6; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalA: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalB: for(Idx = 1; Idx < 4; Idx++) Total += Totals[Idx]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); for(Idx = 1; Idx < 4; Idx++) if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[Idx]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[Idx]); break; case eRCCMinimalC: Total += Totals[0]; Len=sprintf(szLineBuff,"\n\"%s\",\"%s\",\"%s\",\"%s\",%d",szElementType,szRefSpecies,szRelSpecies,pszRegion,Total); if(pParams->bPercentages) Len+=sprintf(&szLineBuff[Len],",%1.2f",Total > 0 ? ((double)Totals[0]*100.0)/(double)Total : 0.0); else Len+=sprintf(&szLineBuff[Len],",%d",Totals[0]); break; default: Len=sprintf(szLineBuff,",-1"); break; } WriteRsltsHeader(pParams); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } int FormatSummaryLine(char *pszBuffer,const char *pszElementType,const char *pszRefSpecies,const char *pszCoreList,const char *pszOutSpecies,const char *pszRegion,const char *pszQual,const char *pszName,int Value) { int Len = sprintf(pszBuffer,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%d\n", pszElementType,pszRefSpecies,pszCoreList,pszOutSpecies,pszRegion,pszQual,pszName,Value); return(Len); } typedef struct TAG_sDistSegCnts { double Matches; // number of exact matches in this segment double Mismatches; // number of mismatches double InDels; // total number of InDel bases double Unaligned; // number of unaligned bases } tsDistSegCnts; typedef struct TAG_sOutSpeciesSummary { int OGMatchBaseTotal; int OGMismatchBaseTotal; int OGInDelBaseTotal; int OGUnalignedBaseTotal; int OGUnalignedCoreBaseTotal; int InstTotal; // total number of core or reference instances int AlignedInstTotal; // total number of aligned cores int BaseTotal; // total number of bases over all core or reference instances int RegionTotals[7]; // genomic region totals int IntronExonSpliceSiteTotals; // 5' splice site totals int ExonIntronSpliceSiteTotals; // 3' splice site totals int InstTotals[cMaxNumRangeClasses]; // to hold total core or reference instance counts int BaseTotals[cMaxNumRangeClasses]; // total number of bases over all core or reference instances in each length range int OGUnalignedCores[cMaxNumRangeClasses]; // to hold outspecies number of instances with no alignment to core int OGUnalignedCoreBases[cMaxNumRangeClasses]; // to hold total number of bases in instances of cores unaligned to out species int OGMatchBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species matching core int OGMismatchBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species not matching core int OGInDelBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species which are InDels int OGUnalignedBaseTotals[cMaxNumRangeClasses]; // total number of bases in out species which are not aligned int OGAligned2Cores[cMaxNumRangeClasses]; // total number of alignments of at least MinAlignedBases in outspecies int OGRegions[cMaxNumRangeClasses][7]; // region counts int OGIntronExonSpliceSite[cMaxNumRangeClasses]; // 5'splice site int OGExonIntronSpliceSite[cMaxNumRangeClasses]; // 3'splice site int OGIntergenicRegion[cMaxNumRangeClasses]; // contained exclusively within intergenic region counts int OGIntergenicRegionTotals; int OGUSRegion[cMaxNumRangeClasses]; // contained exclusively within US counts int OGUSRegionTotals; int OG5UTRRegion[cMaxNumRangeClasses]; // contained exclusively within 5'UTR counts int OG5UTRRegionTotals; int OGCDSRegion[cMaxNumRangeClasses]; // contained exclusively within CDS counts int OGCDSRegionTotals; int OGIntronRegion[cMaxNumRangeClasses]; // contained exclusively within Intron counts int OGIntronRegionTotals; int OG3UTRRegion[cMaxNumRangeClasses]; // contained exclusively within 3'UTR counts int OG3UTRRegionTotals; int OGDSRegion[cMaxNumRangeClasses]; // contained exclusively within DS counts int OGDSRegionTotals; int OGSpliceSites[cMaxNumRangeClasses]; // counts of either 5' or 3' splice sites int OGSpliceSitesTotals; int OGMatchIdentities[cMaxNumRangeClasses][cMaxNumIdentityClasses]; // number of ref core elements with identities 0..100 in each range class int OGTotMatchIdentities[cMaxNumIdentityClasses]; // total number of ref core elements with identities 0..100 tsDistSegCnts DistSegCnts[cMaxNumRangeClasses][cMaxMatchDistSegments]; // to hold distribution segment counts for each length range tsDistSegCnts DistSegCntsTotals[cMaxNumRangeClasses]; int OGUnalignedCoresTotal; char szRefSpecies[200]; char szOutSpecies[200]; char szCoreList[1024]; char szElementType[120]; tsLenRangeClass *pRangeClass; char *pszRegion; int NumDistSegs; int StartIdx; int EndIdx; } tsOutSpeciesSummary; int RsltStandard(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; char szSegBuff[128]; int SegIdx; int Idx; int Len; WriteRsltsHeader(pParams); Len = FormatSummaryLine(szLineBuff,pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Cores",pOSSummary->InstTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Bases in Cores",pOSSummary->BaseTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Cores to OG Unaligned",pOSSummary->OGUnalignedCoresTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","Total Bases in Unaligned Cores",pOSSummary->OGUnalignedCoreBaseTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Matching Bases",pOSSummary->OGMatchBaseTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Missmatch Bases",pOSSummary->OGMismatchBaseTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG InDel Bases",pOSSummary->OGInDelBaseTotal); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,"All Cores","OG Unaligned Bases",pOSSummary->OGUnalignedBaseTotal); for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { sprintf(szSegBuff,"Segment %d",SegIdx+1); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies, pOSSummary->pszRegion,"All Cores (Matches)",szSegBuff, (int)(pOSSummary->DistSegCntsTotals[SegIdx].Matches + 0.5)); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies, pOSSummary->pszRegion,"All Cores (Mismatches)",szSegBuff, (int)(pOSSummary->DistSegCntsTotals[SegIdx].Mismatches + 0.5)); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies, pOSSummary->pszRegion,"All Cores (InDels)",szSegBuff, (int)(pOSSummary->DistSegCntsTotals[SegIdx].InDels + 0.5)); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies, pOSSummary->pszRegion,"All Cores (Unaligned)",szSegBuff, (int)(pOSSummary->DistSegCntsTotals[SegIdx].Unaligned + 0.5)); } if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr; Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Cores",pOSSummary->InstTotals[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Bases in Cores",pOSSummary->BaseTotals[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Cores to OG Unaligned",pOSSummary->OGUnalignedCores[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"Bases in Unaligned Cores",pOSSummary->OGUnalignedCoreBases[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Matching Bases",pOSSummary->OGMatchBaseTotals[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Missmatch Bases",pOSSummary->OGMismatchBaseTotals[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG InDel Bases",pOSSummary->OGInDelBaseTotals[Idx]); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,"OG Unaligned Bases",pOSSummary->OGUnalignedBaseTotals[Idx]); for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { sprintf(szSegBuff,"Segment %d (Matches)",SegIdx+1); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff, (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5)); sprintf(szSegBuff,"Segment %d (Mismatches)",SegIdx+1); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff, (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5)); sprintf(szSegBuff,"Segment %d (InDels)",SegIdx+1); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff, (int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5)); sprintf(szSegBuff,"Segment %d (Unaligned)",SegIdx+1); Len += FormatSummaryLine(&szLineBuff[Len],pOSSummary->szElementType,pOSSummary->szRefSpecies, pOSSummary->szCoreList,pOSSummary->szOutSpecies,pOSSummary->pszRegion,pszRange,szSegBuff, (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5)); } if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltTable // Generates table showing matching base identities for each outspecies // <refspecies>,<specieslist>,<outspecies>,<region>,<refcorelen>,<numrefcores>,<numoutcores>,<identity1>,<identity2> // <identity1> Identity as NumMatchingBases/NumBasesInCoresWhichAlignToRefCores // <identity2> Identity as NumMatchingBases/(NumMatchingBases + NumMissmatchingBases) int RsltTable(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int Len; WriteRsltsHeader(pParams); char szCoreSet[200]; strcpy(szCoreSet,pOSSummary->szRefSpecies); strcat(szCoreSet,pOSSummary->szCoreList); Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d,%2.2f,%d,%d,%d,%2.2f\n", szCoreSet,pOSSummary->szOutSpecies,"All", // core length range pOSSummary->InstTotal, pOSSummary->AlignedInstTotal, pOSSummary->InstTotal == 0 ? 0.0 : (pOSSummary->AlignedInstTotal*100.0)/pOSSummary->InstTotal, pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal, pOSSummary->OGMismatchBaseTotal, pOSSummary->OGMatchBaseTotal, (pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal) == 0 ? 0.0 : (pOSSummary->OGMatchBaseTotal * 100.0) / (pOSSummary->OGMatchBaseTotal + pOSSummary->OGMismatchBaseTotal)); for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr; Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d,%2.2f,%d,%d,%d,%2.2f\n", szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range pOSSummary->InstTotals[Idx], pOSSummary->OGAligned2Cores[Idx], pOSSummary->InstTotals[Idx] == 0 ? 0.0 : ((pOSSummary->InstTotals[Idx] - pOSSummary->OGUnalignedCores[Idx]) * 100.0) /pOSSummary->InstTotals[Idx], pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx], pOSSummary->OGMismatchBaseTotals[Idx], pOSSummary->OGMatchBaseTotals[Idx], (pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx]) == 0 ? 0.0 : (pOSSummary->OGMatchBaseTotals[Idx] * 100.0) / (pOSSummary->OGMatchBaseTotals[Idx] + pOSSummary->OGMismatchBaseTotals[Idx])); } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltSegDistRows // Output the segment distributions as proportions in rows int RsltSegDistRows(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int SegIdx; int Idx; double SegTotal; int Len = 0; WriteRsltsHeader(pParams); for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr; Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"", pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange); for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { if(pParams->bPercentages) { SegTotal = pOSSummary->DistSegCnts[Idx][SegIdx].Matches + pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches + pOSSummary->DistSegCnts[Idx][SegIdx].InDels + pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned; if(SegTotal <= 0.0) Len += sprintf(&szLineBuff[Len],",0.00000,0.00000,0.00000,0.00000"); else Len += sprintf(&szLineBuff[Len],",%1.8f,%1.8f,%1.8f,%1.8f", pOSSummary->DistSegCnts[Idx][SegIdx].Matches/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].InDels/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned/SegTotal); } else Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d", (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5)); } Len += sprintf(&szLineBuff[Len],"\n"); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltSegDistTables // Output the segment distributions as a table with segments the columns and rows from matches/mismatches/indels/unaligned int RsltSegDistTables(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int SegIdx; int Idx; double SegTotals[500]; double CntCatVal; int Len = 0; WriteRsltsHeader(pParams); for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { const char *pszRange = pOSSummary->pRangeClass[Idx].pszDescr; if(pParams->bPercentages) { for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { SegTotals[SegIdx] = pOSSummary->DistSegCnts[Idx][SegIdx].Matches + pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches + pOSSummary->DistSegCnts[Idx][SegIdx].InDels + pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned; if(SegTotals[SegIdx] < 0.0) SegTotals[SegIdx] = 0.0; } } for(int CntCat=0;CntCat<4;CntCat++) { Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"", pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange); switch(CntCat) { case 0: // matches Len += sprintf(&szLineBuff[Len],",Matches"); break; case 1: // mismatches Len += sprintf(&szLineBuff[Len],",Mismatches"); break; case 2: // indels Len += sprintf(&szLineBuff[Len],",InDels"); break; case 3: // unaligned Len += sprintf(&szLineBuff[Len],",Unaligned"); break; } for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { switch(CntCat) { case 0: // matches CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Matches; break; case 1: // mismatches CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches; break; case 2: // indels CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].InDels; break; case 3: // unaligned CntCatVal=pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned; break; } if(pParams->bPercentages) { if(SegTotals[SegIdx] <= 0.0) Len += sprintf(&szLineBuff[Len],",0.00000"); else Len += sprintf(&szLineBuff[Len],",%1.8f",CntCatVal/SegTotals[SegIdx]); } else Len += sprintf(&szLineBuff[Len],",%d",(int)(CntCatVal+0.5)); } Len += sprintf(&szLineBuff[Len],"\n"); if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; } } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltSegDistCols // Output the segment distributions as proportions in columns int RsltSegDistCols(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int SegIdx; int Idx; double SegTotal; char *pszRange; int Len = 0; WriteRsltsHeader(pParams); for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr; Len = 0; for(SegIdx = 0; SegIdx < pOSSummary->NumDistSegs; SegIdx++) { Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"Segment%d\"", pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange,SegIdx+1); if(pParams->bPercentages) { SegTotal = pOSSummary->DistSegCnts[Idx][SegIdx].Matches + pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches + pOSSummary->DistSegCnts[Idx][SegIdx].InDels + pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned; if(SegTotal <= 0.0) Len += sprintf(&szLineBuff[Len],",0.00000,0.00000,0.00000,0.00000\n"); else Len += sprintf(&szLineBuff[Len],",%1.8f,%1.8f,%1.8f,%1.8f\n", pOSSummary->DistSegCnts[Idx][SegIdx].Matches/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].InDels/SegTotal, pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned/SegTotal); } else Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d\n", (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Matches+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Mismatches+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].InDels+0.5), (int)(pOSSummary->DistSegCnts[Idx][SegIdx].Unaligned+0.5)); } if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltIdentDistCols // Output the identities and number of instances for each length range class in columns int RsltIdentDistCols(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x07fff]; int Idx; char *pszRange; int Len = 0; WriteRsltsHeader(pParams); for(Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr; Len = 0; for(int IdentityIdx = 0; IdentityIdx < cMaxNumIdentityClasses; IdentityIdx++) { Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%d,%d,%2.1f,%d\n", pOSSummary->szElementType,pOSSummary->szRefSpecies,pOSSummary->szCoreList,pOSSummary->szOutSpecies,pszRange, pOSSummary->InstTotals[Idx],pOSSummary->InstTotals[Idx] - pOSSummary->OGUnalignedCores[Idx], (double)IdentityIdx, pOSSummary->OGMatchIdentities[Idx][IdentityIdx]); } if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } Len = 0; } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltRegionTable // Output the regional characterisation by length range int RsltRegionTable(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int Len; WriteRsltsHeader(pParams); char szCoreSet[200]; strcpy(szCoreSet,pOSSummary->szRefSpecies); strcat(szCoreSet,pOSSummary->szCoreList); Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d", szCoreSet,pOSSummary->szOutSpecies,"All", // core length range pOSSummary->InstTotal, pOSSummary->AlignedInstTotal); for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++) Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->RegionTotals[RegionIdx]); Len += sprintf(&szLineBuff[Len],",%d,%d\n",pOSSummary->IntronExonSpliceSiteTotals,pOSSummary->ExonIntronSpliceSiteTotals); for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr; Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d", szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range pOSSummary->InstTotals[Idx], pOSSummary->OGAligned2Cores[Idx]); for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++) Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->OGRegions[Idx][RegionIdx]); Len += sprintf(&szLineBuff[Len],",%d,%d\n",pOSSummary->OGIntronExonSpliceSite[Idx],pOSSummary->OGExonIntronSpliceSite[Idx]); } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // RsltRegionTableA // Output the regional characterisation by length range int RsltRegionTableA(tsOutSpeciesSummary *pOSSummary,tsProcParams *pParams) { char szLineBuff[0x03fff]; int Len; WriteRsltsHeader(pParams); char szCoreSet[2048]; strcpy(szCoreSet,pOSSummary->szRefSpecies); strcat(szCoreSet,pOSSummary->szCoreList); Len = sprintf(szLineBuff,"\"%s\",\"%s\",\"%s\",%d,%d", szCoreSet,pOSSummary->szOutSpecies,"All", // core length range pOSSummary->InstTotal, pOSSummary->AlignedInstTotal); for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++) Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->RegionTotals[RegionIdx]); Len += sprintf(&szLineBuff[Len],",%d,%d", pOSSummary->IntronExonSpliceSiteTotals,pOSSummary->ExonIntronSpliceSiteTotals); Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d,%d,%d,%d,%d\n", pOSSummary->OGIntergenicRegionTotals,pOSSummary->OGUSRegionTotals, pOSSummary->OG5UTRRegionTotals,pOSSummary->OGCDSRegionTotals, pOSSummary->OGIntronRegionTotals,pOSSummary->OG3UTRRegionTotals, pOSSummary->OGDSRegionTotals,pOSSummary->OGSpliceSitesTotals); for(int Idx = pOSSummary->StartIdx; Idx < pOSSummary->EndIdx; Idx++) { char *pszRange = (char *)pOSSummary->pRangeClass[Idx].pszDescr; Len += sprintf(&szLineBuff[Len],"\"%s\",\"%s\",\"%s\",%d,%d", szCoreSet,pOSSummary->szOutSpecies,pszRange, // core length range pOSSummary->InstTotals[Idx], pOSSummary->OGAligned2Cores[Idx]); for(int RegionIdx = 0; RegionIdx < 7; RegionIdx++) Len += sprintf(&szLineBuff[Len],",%d",pOSSummary->OGRegions[Idx][RegionIdx]); Len += sprintf(&szLineBuff[Len],",%d,%d",pOSSummary->OGIntronExonSpliceSite[Idx],pOSSummary->OGExonIntronSpliceSite[Idx]); Len += sprintf(&szLineBuff[Len],",%d,%d,%d,%d,%d,%d,%d,%d\n", pOSSummary->OGIntergenicRegion[Idx],pOSSummary->OGUSRegion[Idx], pOSSummary->OG5UTRRegion[Idx],pOSSummary->OGCDSRegion[Idx], pOSSummary->OGIntronRegion[Idx],pOSSummary->OG3UTRRegion[Idx], pOSSummary->OGDSRegion[Idx],pOSSummary->OGSpliceSites[Idx]); } if(Len) if(write(pParams->hRsltsFile,szLineBuff,Len)!=Len) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to write results file '%s' - '%s'",pParams->pszRsltsFile,strerror(errno)); return(eBSFerrWrite); } return(eBSFSuccess); } // Expected CSV format // ElementID Uniquely identifies this element (1..n) // CoreType Currently either 'hypercore' or 'ultracore' // Chromosome Chromosome on reference species // StartLoci Starting offset (0..n) on Chromosome // EndLoci Ending offset (StartLoci + length -1) on Chromosome // Length Element length // SpeciesList List of all species sharing this element, 1st species is the reference // Region In which region core is located // // There are an optional 4 fields present if CSV file was generated with outspecies processing (-x2 option) // Unaligned Count of bases in outspecies not aligned // Matches Count of bases in outspecies which align and match // Mismatches Count of bases in outspecies which align but mismatch // InDels Count of bases in reference or outspecies which are InDels int ProcessOutspeciesSummary(char *pszFile,CCSVFile *pCSV,tsProcParams *pParams) { int Rslt; int NumRows; int NumFields; int AlignedBases; int OGUnalignedBases; int OGMatchCnt; int OGMismatchCnt; int OGInDelCnt; int SegCnt; int SegIdx; char *pszElementType; char *pszSpeciesList; char *pszRefSpecies; int SeqLen; int Region; int NormRegion; tsLenRangeClass *pRangeClass; tsOutSpeciesSummary OSSummary; // no headers, straight into the rows which are expected to contain at least 13 fields NumRows = 0; memset(&OSSummary,0,sizeof(OSSummary)); OSSummary.pszRegion = Region2Text(pParams->Region); switch(pParams->RangeClass) { case eRCCFull: OSSummary.StartIdx = 4; OSSummary.EndIdx = cMaxNumRangeClasses; break; case eRCCReduced: OSSummary.StartIdx = 2; OSSummary.EndIdx = 9; break; case eRCCMinimal: OSSummary.StartIdx = 1; OSSummary.EndIdx = 6; break; case eRCCMinimalA: OSSummary.StartIdx = 1; OSSummary.EndIdx = 4; break; case eRCCMinimalB: OSSummary.StartIdx = 1; OSSummary.EndIdx = 4; break; case eRCCMinimalC: OSSummary.StartIdx = 0; OSSummary.EndIdx = 1; break; } pParams->NumSpecies = 0; while((Rslt=pCSV->NextLine()) > 0) // onto next line containing fields { NumFields = pCSV->GetCurFields(); if(NumFields < 9) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Expected at least 9 fields in outspecies '%s', GetCurFields() returned '%d'",pszFile,NumFields); return(eBSFerrFieldCnt); } pCSV->GetText(2,(char **)&pszElementType); strncpy(OSSummary.szElementType,pszElementType,sizeof(OSSummary.szElementType)); OSSummary.szElementType[sizeof(OSSummary.szElementType)-1] = '\0'; pCSV->GetText(3,(char **)&pszRefSpecies); pCSV->GetText(8,(char **)&pszSpeciesList); if(!pParams->NumSpecies) { pParams->NumSpecies = ParseNumSpecies(pszSpeciesList,pParams); strcpy(OSSummary.szRefSpecies,pParams->szSpecies[0]); strcpy(OSSummary.szOutSpecies,pParams->szSpecies[pParams->NumSpecies-1]); OSSummary.szCoreList[0] = '\0'; for(int Idx = 1; Idx < (pParams->NumSpecies-1); Idx++) { if(Idx > 1) strcat(OSSummary.szCoreList,","); strcat(OSSummary.szCoreList,pParams->szSpecies[Idx]); } } pCSV->GetInt(9,&Region); NormRegion = NormaliseRegion(Region); if(pParams->Region != eFRAuto && pParams->Region != NormRegion) continue; pCSV->GetInt(7,&SeqLen); pRangeClass = GetLengthRangeClass(SeqLen); if(NumFields > 9) // if base alignment detail in file { pCSV->GetInt(10,&OGUnalignedBases); pCSV->GetInt(11,&OGMatchCnt); pCSV->GetInt(12,&OGMismatchCnt); pCSV->GetInt(13,&OGInDelCnt); AlignedBases = OGMatchCnt + OGMismatchCnt; if((AlignedBases >= pParams->Align2Core || AlignedBases == SeqLen) && (((AlignedBases * 100.0) / SeqLen) >= pParams->PCAlign2Core) && (((OGMatchCnt * 100.0) / SeqLen) >= pParams->IDAlign2Core) && (((OGMatchCnt * 100.0) / (OGMatchCnt + OGMismatchCnt)) >= pParams->IDOSIdentity)) OSSummary.OGAligned2Cores[pRangeClass->ID-1] += 1; else { OGMatchCnt = 0; OGMismatchCnt = 0; OGInDelCnt = 0; OGUnalignedBases = SeqLen; NormRegion = -1; Region = -1; } } else { OGUnalignedBases = 0; OGMatchCnt = SeqLen; OGMismatchCnt = 0; OGInDelCnt = 0; } OSSummary.BaseTotals[pRangeClass->ID-1] += SeqLen; OSSummary.InstTotals[pRangeClass->ID-1] += 1; OSSummary.OGMatchBaseTotals[pRangeClass->ID-1] += OGMatchCnt; OSSummary.OGMismatchBaseTotals[pRangeClass->ID-1] += OGMismatchCnt; OSSummary.OGInDelBaseTotals[pRangeClass->ID-1] += OGInDelCnt; if(NormRegion != -1) // if regional mapping in source file { if(pParams->RsltsLayout == eRPRsltRegionTableA) { // determine exclusive regions (loci exclusive, totally contained, within the region) if(Region & cFeatBitCDS && !(Region & (cFeatBit5UTR | cFeatBit3UTR))) { OSSummary.OGCDSRegion[pRangeClass->ID-1] += 1; OSSummary.OGCDSRegionTotals += 1; } else if(Region & cFeatBit5UTR && !(Region & (cFeatBitCDS | cFeatBit3UTR))) { OSSummary.OG5UTRRegion[pRangeClass->ID-1] += 1; OSSummary.OG5UTRRegionTotals += 1; } else if(Region & cFeatBit3UTR && !(Region & (cFeatBitCDS | cFeatBit5UTR))) { OSSummary.OG3UTRRegion[pRangeClass->ID-1] += 1; OSSummary.OG3UTRRegionTotals += 1; } else if(Region & cFeatBitIntrons && !(Region & (cFeatBitCDS | cFeatBit5UTR | cFeatBit3UTR))) { OSSummary.OGIntronRegion[pRangeClass->ID-1] += 1; OSSummary.OGIntronRegionTotals += 1; } else if(Region & cFeatBitUpstream && !(Region & (cFeatBitCDS | cFeatBitIntrons | cFeatBit5UTR | cFeatBit3UTR))) { OSSummary.OGUSRegion[pRangeClass->ID-1] += 1; OSSummary.OGUSRegionTotals += 1; } else if(Region & cFeatBitDnstream && !(Region & (cFeatBitCDS | cFeatBitIntrons | cFeatBit5UTR | cFeatBit3UTR))) { OSSummary.OGDSRegion[pRangeClass->ID-1] += 1; OSSummary.OGDSRegionTotals += 1; } else if(!Region) { OSSummary.OGIntergenicRegion[pRangeClass->ID-1] += 1; OSSummary.OGIntergenicRegionTotals += 1; } if(Region & (cIntronExonSpliceSite | cExonIntronSpliceSite)) { OSSummary.OGSpliceSites[pRangeClass->ID-1] += 1; OSSummary.OGSpliceSitesTotals += 1; } // now process region counts with region unnormalised if(Region & cFeatBitCDS) { OSSummary.OGRegions[pRangeClass->ID-1][eFRCDS] += 1; OSSummary.RegionTotals[eFRCDS] += 1; } if(Region & cFeatBit5UTR) { OSSummary.OGRegions[pRangeClass->ID-1][eFR5UTR] += 1; OSSummary.RegionTotals[eFR5UTR] += 1; } if(Region & cFeatBit3UTR) { OSSummary.OGRegions[pRangeClass->ID-1][eFR3UTR] += 1; OSSummary.RegionTotals[eFR3UTR] += 1; } if(Region & cFeatBitIntrons) { OSSummary.OGRegions[pRangeClass->ID-1][eFRIntronic] += 1; OSSummary.RegionTotals[eFRIntronic] += 1; } if(Region & cFeatBitUpstream) { OSSummary.OGRegions[pRangeClass->ID-1][eFRUpstream] += 1; OSSummary.RegionTotals[eFRUpstream] += 1; } if(Region & cFeatBitDnstream) { OSSummary.OGRegions[pRangeClass->ID-1][NormRegion] += 1; OSSummary.RegionTotals[eFRDnstream] += 1; } if(!Region) { OSSummary.OGRegions[pRangeClass->ID-1][eFRIntergenic] += 1; OSSummary.RegionTotals[eFRIntergenic] += 1; } if(Region & cIntronExonSpliceSite) { OSSummary.OGIntronExonSpliceSite[pRangeClass->ID-1] += 1; OSSummary.IntronExonSpliceSiteTotals += 1; } if(Region & cExonIntronSpliceSite) { OSSummary.OGExonIntronSpliceSite[pRangeClass->ID-1] += 1; OSSummary.ExonIntronSpliceSiteTotals += 1; } } else { // now process region counts where region has been normalised OSSummary.OGRegions[pRangeClass->ID-1][NormRegion] += 1; OSSummary.RegionTotals[NormRegion] += 1; if(Region & cIntronExonSpliceSite) { OSSummary.OGIntronExonSpliceSite[pRangeClass->ID-1] += 1; OSSummary.IntronExonSpliceSiteTotals += 1; } if(Region & cExonIntronSpliceSite) { OSSummary.OGExonIntronSpliceSite[pRangeClass->ID-1] += 1; OSSummary.ExonIntronSpliceSiteTotals += 1; } } } if(NumFields <= 15) OSSummary.NumDistSegs = 0; else OSSummary.NumDistSegs = (NumFields - 15)/4; // 4 fields per segment (matches,mismatches,indels,unaligned) pParams->NumDistSegs = OSSummary.NumDistSegs; // need to normalise the counts because the orginal count binning // was on discrete base boundaries. For example - // Assume 10 bins, and sequence length was 20 // All 10 bins contain counts for 2 bases per bin (BinWidth = 2) // Assume sequence length was 21 // The first 9 bins contain counts for 2 bases per bin, but the last bin contains counts for 3 bases // Assume sequence length now 28 // The first 2 bins contain counts for 2 bases per bin (BinWidth = 2), but the last 8 bins contains counts for 3 bases (BinWidth = 3) // // To normalise, scale the bases per bin to be BinCnt *= Sequencelength/(NumberBins*BinWidth) // Using same examples as above - // Assume 10 bins, and sequence length was 20 // Scale all 10 bins by 20/(10*2) or 1.0 // Assume sequence length was 21 // Scale first 9 bins by 21/(10*2) or 1.05 , last bin by 21/(10*3) or 0.70 if(OSSummary.NumDistSegs && (!pParams->bSegsExcludeMatch || SeqLen > OGMatchCnt)) { int BinWidth = SeqLen / OSSummary.NumDistSegs; // intial bin width or number of bases in that bin int BinWidthChg = OSSummary.NumDistSegs - (SeqLen % OSSummary.NumDistSegs); // bin index at which scaling changes double CntScale = (double)SeqLen / (OSSummary.NumDistSegs * BinWidth); for(SegIdx = 0; SegIdx < OSSummary.NumDistSegs; SegIdx++) { if(SegIdx == BinWidthChg) CntScale = (double)SeqLen / (OSSummary.NumDistSegs * (BinWidth+1)); pCSV->GetInt((SegIdx * 4) + 16,&SegCnt); OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Matches += SegCnt * CntScale; pCSV->GetInt((SegIdx * 4) + 17,&SegCnt); OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Mismatches += SegCnt * CntScale; pCSV->GetInt((SegIdx * 4) + 18,&SegCnt); OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].InDels += SegCnt * CntScale; pCSV->GetInt((SegIdx * 4) + 19,&SegCnt); OSSummary.DistSegCnts[pRangeClass->ID-1][SegIdx].Unaligned += SegCnt * CntScale; } } if(OGUnalignedBases == SeqLen) // if no alignment at all... { OSSummary.OGUnalignedCores[pRangeClass->ID-1] += 1; OSSummary.OGUnalignedCoreBases[pRangeClass->ID-1] += OGUnalignedBases; } else // else at least 1 base aligned! { OSSummary.OGUnalignedBaseTotals[pRangeClass->ID-1] += OGUnalignedBases; double MatchPercent = (OGMatchCnt * 100.0) / SeqLen; int MatchPercentIdx = (int)(MatchPercent + 0.001); // 0.001 added in case of small round down errors in floating points OSSummary.OGMatchIdentities[pRangeClass->ID-1][MatchPercentIdx] += 1; } NumRows++; } // all element rows have been processed OSSummary.InstTotal = 0; OSSummary.BaseTotal = 0; for(int Idx = OSSummary.StartIdx; Idx < OSSummary.EndIdx; Idx++) { OSSummary.InstTotal += OSSummary.InstTotals[Idx]; OSSummary.BaseTotal += OSSummary.BaseTotals[Idx]; OSSummary.AlignedInstTotal += OSSummary.OGAligned2Cores[Idx]; OSSummary.OGMatchBaseTotal += OSSummary.OGMatchBaseTotals[Idx]; OSSummary.OGMismatchBaseTotal += OSSummary.OGMismatchBaseTotals[Idx]; OSSummary.OGInDelBaseTotal += OSSummary.OGInDelBaseTotals[Idx]; OSSummary.OGUnalignedBaseTotal += OSSummary.OGUnalignedBaseTotals[Idx]; OSSummary.OGUnalignedCoreBaseTotal += OSSummary.OGUnalignedCoreBases[Idx]; OSSummary.OGUnalignedCoresTotal += OSSummary.OGUnalignedCores[Idx]; for(int IdentityIdx = 0; IdentityIdx < cMaxNumIdentityClasses; IdentityIdx++) OSSummary.OGTotMatchIdentities[IdentityIdx] += OSSummary.OGMatchIdentities[Idx][IdentityIdx]; for(SegIdx = 0; SegIdx < OSSummary.NumDistSegs; SegIdx++) { OSSummary.DistSegCntsTotals[SegIdx].Matches += OSSummary.DistSegCnts[Idx][SegIdx].Matches; OSSummary.DistSegCntsTotals[SegIdx].Mismatches += OSSummary.DistSegCnts[Idx][SegIdx].Mismatches; OSSummary.DistSegCntsTotals[SegIdx].InDels += OSSummary.DistSegCnts[Idx][SegIdx].InDels; OSSummary.DistSegCntsTotals[SegIdx].Unaligned += OSSummary.DistSegCnts[Idx][SegIdx].Unaligned; } } OSSummary.pRangeClass = pLenRangeClasses; switch(pParams->RsltsLayout) { case eRPRsltStandard: Rslt = RsltStandard(&OSSummary,pParams); break; case eRPRsltTable: Rslt = RsltTable(&OSSummary,pParams); break; case eRPRsltSegDistRows: Rslt = RsltSegDistRows(&OSSummary,pParams); break; case eRPRsltSegDistTables: Rslt = RsltSegDistTables(&OSSummary,pParams); break; case eRPRsltSegDistCols: Rslt = RsltSegDistCols(&OSSummary,pParams); break; case eRPRsltIdentDistCols: Rslt = RsltIdentDistCols(&OSSummary,pParams); break; case eRPRsltRegionTable: Rslt = RsltRegionTable(&OSSummary,pParams); break; case eRPRsltRegionTableA: Rslt = RsltRegionTableA(&OSSummary,pParams); break; } return(eBSFSuccess); }
102,696
47,248
#ifdef WEIRDLIB_ENABLE_VECTOR_MATH #include "../../include/weirdlib_vecmath.hpp" #include "../../include/cpu_detection.hpp" #include "../../include/weirdlib_simdhelper.hpp" #include <array> namespace wlib::vecmath { #if X86_SIMD_LEVEL >= LV_AVX2 static const auto PERM_MASK_CROSSP_LHS = _mm256_set_epi32(0, 0, 1, 0, 2, 0, 2, 1); static const auto PERM_MASK_CROSSP_RHS = _mm256_set_epi32(0, 0, 0, 2, 1, 1, 0, 2); static const auto PERM_MASK_CROSSP_SUB = _mm256_set_epi32(0, 0, 5, 2, 4, 1, 3, 0); #endif Vector3<float> CrossProduct(const Vector3<float>& lhs, const Vector3<float>& rhs) { #if X86_SIMD_LEVEL >= LV_AVX2 auto lhs_vec = _mm256_loadu_ps(&lhs.x); auto rhs_vec = _mm256_loadu_ps(&rhs.x); auto lhs_yzxzxy = _mm256_permutevar8x32_ps(lhs_vec, PERM_MASK_CROSSP_LHS); auto rhs_zxyyzx = _mm256_permutevar8x32_ps(rhs_vec, PERM_MASK_CROSSP_RHS); auto product = _mm256_mul_ps(lhs_yzxzxy, rhs_zxyyzx); // Set up for subtraction auto prod_hsub = _mm256_permutevar8x32_ps(product, PERM_MASK_CROSSP_SUB); auto result = _mm256_hsub_ps(prod_hsub, prod_hsub); alignas(32) std::array<float, 8> outvec; _mm256_store_ps(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[4]); #elif X86_SIMD_LEVEL >= LV_SSE auto lhs_vec = _mm_loadu_ps(&lhs.x); auto rhs_vec = _mm_loadu_ps(&rhs.x); auto lhs_yzx = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 0, 2, 1)); auto lhs_zxy = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 1, 0, 2)); auto rhs_zxy = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 1, 0, 2)); auto rhs_yzx = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 0, 2, 1)); auto left_side = _mm_mul_ps(lhs_yzx, rhs_zxy); auto right_side = _mm_mul_ps(lhs_zxy, rhs_yzx); auto result = _mm_sub_ps(left_side, right_side); alignas(16) std::array<float, 4> outvec; _mm_store_ps(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[2]); #else float x = (lhs.y * rhs.z) - (lhs.z * rhs.y); float y = (lhs.z * rhs.x) - (lhs.x * rhs.z); float z = (lhs.x * rhs.y) - (lhs.y * rhs.x); return Vector3(x, y, z); #endif } Vector3<double> CrossProduct(const Vector3<double>& lhs, const Vector3<double>& rhs) { #if X86_SIMD_LEVEL >= LV_AVX2 auto lhs_vec = _mm256_loadu_pd(&lhs.x); auto rhs_vec = _mm256_loadu_pd(&rhs.x); auto lhs_yzx = _mm256_permute4x64_pd(lhs_vec, 0b00001001); auto lhs_zxy = _mm256_permute4x64_pd(lhs_vec, 0b00010010); auto rhs_yzx = _mm256_permute4x64_pd(rhs_vec, 0b00001001); auto rhs_zxy = _mm256_permute4x64_pd(rhs_vec, 0b00010010); auto left_side = _mm256_mul_pd(lhs_yzx, rhs_zxy); auto right_side = _mm256_mul_pd(lhs_zxy, rhs_yzx); auto result = _mm256_sub_pd(left_side, right_side); alignas(32) std::array<double, 4> outvec; _mm256_store_pd(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[2]); #elif X86_SIMD_LEVEL >= LV_SSE2 auto lhs_vec_xy = _mm_loadu_pd(&lhs.x); auto lhs_vec_z_ = _mm_loadu_pd(&lhs.z); auto rhs_vec_xy = _mm_loadu_pd(&rhs.x); auto rhs_vec_z_ = _mm_loadu_pd(&rhs.z); auto lhs_yz = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_z_, 0b00000001); auto lhs_zx = _mm_shuffle_pd(lhs_vec_z_, lhs_vec_xy, 0b00000000); auto lhs_x_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000000); auto lhs_y_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000001); auto rhs_yz = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_z_, 0b00000001); auto rhs_zx = _mm_shuffle_pd(rhs_vec_z_, rhs_vec_xy, 0b00000000); auto rhs_x_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000000); auto rhs_y_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000001); auto l0 = _mm_mul_pd(lhs_yz, rhs_zx); auto r0 = _mm_mul_pd(lhs_zx, rhs_yz); auto l1 = _mm_mul_pd(lhs_x_, rhs_y_); auto r1 = _mm_mul_pd(lhs_y_, rhs_x_); auto result0 = _mm_sub_pd(l0, r0); auto result1 = _mm_sub_pd(l1, r1); alignas(16) std::array<double, 4> outvec; _mm_store_pd(outvec.data(), result0); _mm_store_pd(outvec.data()+2, result1); return Vector3(outvec[0], outvec[1], outvec[2]); #else double x = (lhs.y * rhs.z) - (lhs.z * rhs.y); double y = (lhs.z * rhs.x) - (lhs.x * rhs.z); double z = (lhs.x * rhs.y) - (lhs.y * rhs.x); return Vector3(x, y, z); #endif } } // namespace wlib::vecmath #endif
4,323
2,434
#include "src/metafs/mvm/volume/meta_volume_state.h" #include <gtest/gtest.h>
79
36
/* * Copyright 2022 CTA Radar API Technical Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef I_RADAR_SENSOR_HPP_ #define I_RADAR_SENSOR_HPP_ #include <cstdint> #include <string> #include <time.h> #include <vector> //-------------------------------------- //----- Enums -------------------------- //-------------------------------------- namespace radar_api { // A list of possible status/return codes that API can report back. enum ReturnCode { // A default undefined value that should be used at initialization. RC_UNDEFINED = 0, // Operation completed successfully. RC_OK, // Operation failed and no more information can be provided. RC_ERROR, // Input parameters are invalid or out of supported range. RC_BAD_INPUT, // Operation timed out. RC_TIMEOUT, // Operation cannot be performed at the current state. RC_BAD_STATE, // Operation failed due to limited resources (memory, timers, mutexes, etc). RC_RES_LIMIT, // Operation is not supported. RC_UNSUPPORTED, // An internal system error that should never happen. RC_OOPS }; // A list of possible power mode states for radar sensors. enum RadarState { // A default undefined value that should be used at initialization. RSTATE_UNDEFINED = 0, // Active state when radar is emitting/collecting data started. RSTATE_ACTIVE, // Idle state when the radar is neither ACTIVE nor SLEEP nor OFF. RSTATE_IDLE, // Sleep state when configuration persists but power consumption reduced. RSTATE_SLEEP, // When radar is currently turned off and configuration is reset. RSTATE_OFF }; // Defineis how an internal fifo buffer should behave in case of overflow. enum FifoMode { // A default undefined value that should be used at initialization. RFIFO_UNDEFINED = 0, // A new burst will be ignored. RFIFO_DROP_NEW, // The oldest burst(s) will be dropped to release space for a new burst. RFIFO_DROP_OLD }; //-------------------------------------- //----- Params ------------------------- //-------------------------------------- // A list of radar sensor parameters that define main characteristics. // A configuration slot can hold only 1 value for each MainParam. enum MainParam { // A default undefined value that should be used at initialization. RADAR_PARAM_UNDEFINED = 0, // Power mode for after the burst period. RADAR_PARAM_AFTERBURST_POWER_MODE, // Power mode for the period between chirps. RADAR_PARAM_INTERCHIRP_POWER_MODE, // Duration between the start times of two consecutive bursts. RADAR_PARAM_BURST_PERIOD_US, // Duration between the start times of two consecutive chirps. RADAR_PARAM_CHIRP_PERIOD_US, // Amount of chirps within the burst. RADAR_PARAM_CHIRPS_PER_BURST, // The number of ADC sample values captured for each chirp. RADAR_PARAM_SAMPLES_PER_CHIRP, // The lower frequency at what TX antenna starts emitting the signal. RADAR_PARAM_LOWER_FREQ_MHZ, // The upper frequency at what TX antenna stops emitting the signal. RADAR_PARAM_UPPER_FREQ_MHZ, // Bit mask for enabled TX antennas. RADAR_PARAM_TX_ANTENNA_MASK, // Bit mask for enabled RX antennas. RADAR_PARAM_RX_ANTENNA_MASK, // Power for TX antennas. RADAR_PARAM_TX_POWER, // ADC sampling frequency. RADAR_PARAM_ADC_SAMPLING_HZ }; // A channel specific list of parameters. enum ChannelParam { // A default undefined value that should be used at initialization. CHANNEL_PARAM_UNDEFINED = 0, // Variable Gain Amplifiers (VGA) in dB. CHANNEL_PARAM_VGA_DB, // High Phase (HP) filter gain in dB. CHANNEL_PARAM_HP_GAIN_DB, // High Phase (HP) cut off frequency in kHz. CHANNEL_PARAM_HP_CUTOFF_KHZ }; enum LogLevel { // A default undefined value that should be used at initialization. RLOG_UNDEFINED = 0, // None of log messages are requested. RLOG_OFF, // Provide only log messages about occurred errors. RLOG_ERR, // Provide log messages same as for RLOG_ERR and warnings. RLOG_WRN, // Provide log messages same as for RLOG_WRN and informative changes. RLOG_INF, // Provide log messages same as for RLOG_INF and debugging info details. RLOG_DBG }; //-------------------------------------- //----- Data types --------------------- //-------------------------------------- // Forward declaration for a list of vensor specific parameters. enum VendorParam : uint16_t; // Describes a data format of burst data. struct BurstFormat { // Sequence number for the current burst. uint32_t sequence_number; // Maximum value ADC sampler produces. uint32_t max_sample_value; // Amount of bits per single sample. uint8_t bits_per_sample; // Amount of samples per single chirp. uint16_t samples_per_chirp; // Amount of active channels in the current burst. uint8_t channels_count; // Amount of chirps in the current burst. uint8_t chirps_per_burst; // Config slot ID used to generate the current burst. uint8_t config_id; bool is_channels_interlieved; bool is_big_endian; // CRC for the current burst data buffer. uint32_t burst_data_crc; // Timestamp when the burst was created since radar was turned on. uint32_t timestamp_ms; }; // A semantic version holder. struct Version { uint8_t major; uint8_t minor; uint8_t patch; uint8_t build; }; // The general information about the radar sensor hardware and software. struct SensorInfo { // Name of the radar sensor. std::string name; // Vendor name. std::string vendor; // ID that identifies this sensor. uint32_t device_id; // The radar driver version. Version driver_version; // The Radar API version that the current driver supports. Version api_version; // Maximum ADC sampling rate in hertz. uint64_t max_sampling_rate_hz; // Current sensor state RadarState state; }; /* * @brief A Radar data observer that allows application to be notified * about it's events. */ class IRadarSensorObserver { public: /* * @brief An interface function declaration that will be invoked * when a new burst is ready for read. Can be set using * radarSetBurstReadyCb function. * * @return void */ virtual void OnBurstReady(void) = 0; /* * @brief An interface function declaration that will be invoked * when a new log message is available from the radar driver. * The callback can be registered with radarSetLogCb function. * Run time log level can be set using radarSetLogLevel function. * * @param level a level of the current log message. * @param file a source file name where the log message is generated. * The value is set by a compiler and embedded into the code. * @param function a function name where the log message is generated. * The value is set by a compiler and embedded into the code. * @param line a line number within a file where the log message is generated. * @param message a completely formed log message. * * @return void */ virtual void OnLogMessage(int level, const char* file, const char* function, int line, const std::string& message) = 0; /* * @brief An interface function declaration that will be invoked * when the radar driver sets a new value for the sensor chip register. * * @param address a register's address. * @param value a new value to be set in the register. * * @return void. */ virtual void OnRegisterSet(uint32_t address, uint32_t value) = 0; }; //-------------------------------------- //----- API ---------------------------- //-------------------------------------- class IRadarSensor { public: // Feedback /* * @brief Add a new observer object that will get notified about * the Radar sensor activity. * * @param observer pointer to the implmenetation of the interface to add. */ virtual ReturnCode AddObserver(IRadarSensorObserver* observer) = 0; /* * @brief Remove the previously registered observer from subscribers list. * * @param observer pointer to the implmenetation of the interface to remove. */ virtual ReturnCode RemoveObserver(IRadarSensorObserver* observer) = 0; // Power management. /* * @brief Get the current power state. * * @param state a pointer to the state that will be set. */ virtual ReturnCode GetRadarState(RadarState& state) = 0; /* * @brief Turn on the radar. */ virtual ReturnCode TurnOn(void) = 0; /* * @brief Turn off the radar. */ virtual ReturnCode TurnOff(void) = 0; /* * @brief Put the radar to sleep and preserve configuration. */ virtual ReturnCode GoSleep(void) = 0; /* * @brief Wake up the radar. */ virtual ReturnCode WakeUp(void) = 0; // Configuration. /* * @brief Set mode of the internal FIFO that holds radar bursts. * * @param mode a new fifo mode for the internal buffer. */ virtual ReturnCode SetFifoMode(FifoMode mode) = 0; /* * Get the total available configuration slots. * * @param num_slots where the number of config slots to write. */ virtual ReturnCode GetNumConfigSlots(int8_t& num_slots) = 0; /* * @brief Activate a specified configuration slot. Does not start the radar. * * @param slot_id a configuration slot ID to activate. * * @note This function will perform the final configuration check for * compatibility before activating. */ virtual ReturnCode ActivateConfig(uint8_t slot_id) = 0; /* * @brief Deactivate a specified configuration slot. * * @param slot_id a configuration slot ID to deactivate. */ virtual ReturnCode DeactivateConfig(uint8_t slot_id) = 0; /* * @brief Check if the configuration slot is active. * * @param slot_ids a vector to be filled with IDs of * active config slots. */ virtual ReturnCode GetActiveConfigs(std::vector<uint8_t>& slot_ids) = 0; /* * @brief Get a main radar parameter. * * @param slot_id a configuration slot ID where to read the parameter value. * @param id a parameter ID to be read. * @param value where a parameter value will be written into. */ virtual ReturnCode GetMainParam(uint32_t slot_id, MainParam id, uint32_t& value) = 0; /* * @brief Get a main radar parameter. * * @param slot_id a configuration slot ID where to set a new parameter value. * @param id a parameter ID to be set. * @param value a new value for the parameter. */ virtual ReturnCode SetMainParam(uint32_t slot_id, MainParam id, uint32_t value) = 0; /* * @brief Get a main radar parameter range of acceptable values. * * @param id a parameter ID which range of values to read. * @param min_value where a minimum parameter value will be set. * @param max_value where a maximum parameter value will be set. */ virtual ReturnCode GetMainParamRange(MainParam id, uint32_t& min_value, uint32_t& max_value) = 0; /* * @brief Get a channel specific parameter. * * @param slot_id a configuration slot ID where to read the parameter value. * @param channel_id a channel ID which parameter needs to be read. * @param id a parameter ID to read. * @param value to where a parameter value will be written into. */ virtual ReturnCode GetChannelParam(uint32_t slot_id, uint8_t channel_id, ChannelParam id, uint32_t& value) = 0; /* * @brief Set a channel specific parameter. * * @param slot_id a configuration slot ID where to set a new parameter value. * @param channel_id a channel ID which parameter needs to be set. * @param id a parameter ID to set. * @param value a new value for the parameter. */ virtual ReturnCode SetChannelParam(uint32_t slot_id, uint8_t channel_id, ChannelParam id, uint32_t value) = 0; /* * @brief Get a channel pamaeter range of acceptable values. * * @param id a parameter ID which range of values to read. * @param min_value where a minimum parameter value will be set. * @param max_value where a maximum parameter value will be set. */ virtual ReturnCode GetChannelParamRange(ChannelParam id, uint32_t& min_value, uint32_t& max_value) = 0; /* * @brief Get a vendor specific parameter. * * @param slot_id a configuration slot ID where to read a parameter value. * @param id a vendor specific parameter ID to read. * @param value to where a parameter value will be written into. */ virtual ReturnCode GetVendorParam(uint32_t slot_id, VendorParam id, uint32_t& value) = 0; /* * @brief Set a vendor specific parameter. * * @param slot_id a configuration slot ID where to set a new parameter value. * @param id a parameter ID to set. * @param value a new value for the parameter. */ virtual ReturnCode SetVendorParam(uint32_t slot_id, VendorParam id, uint32_t value) = 0; // Running. /* * @brief Start running the radar with active configuration. */ virtual ReturnCode StartDataStreaming(void) = 0; /* * @brief Stop running the radar. */ virtual ReturnCode StopDataStreaming(void) = 0; /* * @brief Check if the radar has a new burst ready to read. * * @param is_ready where the result will be set. */ virtual ReturnCode IsBurstReady(bool& is_ready) = 0; /* * @brief Initiate reading a new burst. * * @param format where a new burst format will be written into. * @param raw_radar_data where a burst data to be written. * @param timeout the maximum time to wait if the burst frame is not ready. */ virtual ReturnCode ReadBurst(BurstFormat& format, std::vector<uint8_t>& raw_radar_data, timespec timeout) = 0; // Miscellaneous. /* * @brief Set country code. If local regulations do not allow current sensor * to operate, it should be turned off or faile to turn on. * * @param country_code a ISO 3166-1 alpha-2 country code. */ virtual ReturnCode SetCountryCode(const std::string& country_code) = 0; /* * @brief Get radar sensor info. * * @param info where the sensor info to be filled in. */ virtual ReturnCode GetSensorInfo(SensorInfo& info) = 0; /* * @brief Set a run time log level for radar API impl. * * @param level new log level. */ virtual ReturnCode SetLogLevel(LogLevel level) = 0; /* * @brief Get all register values from the radar sensor. * * @param registers where the pair of register's address and value * to be written. */ virtual ReturnCode GetAllRegisters( std::vector<std::pair<uint32_t, uint32_t>>& registers) = 0; /* * @brief Get a register value directly from the sensor. * * @param address an address to read. * @param value where the register's value will be written into. */ virtual ReturnCode GetRegister(uint32_t address, uint32_t& value) = 0; /* * @brief Set a register value directly to the sensor. * * @param address an address of the register to set. * @param value a new value to set. */ virtual ReturnCode SetRegister(uint32_t address, uint32_t value) = 0; }; // Return the intsance of the RadarSensor implementation. IRadarSensor* GetRadarSensorImpl(void); } // namespace radar_api #endif // I_RADAR_SENSOR_HPP_
16,021
4,962
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // float Health (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UGAB_AthenaDBNO_C::GetInitialHealAmount(float* Health) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount"); UGAB_AthenaDBNO_C_GetInitialHealAmount_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Health != nullptr) *Health = params.Health; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGameplayEventData EventHitData (Parm) void UGAB_AthenaDBNO_C::InitializeDeathHitDirection(const struct FGameplayEventData& EventHitData) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection"); UGAB_AthenaDBNO_C_InitializeDeathHitDirection_Params params; params.EventHitData = EventHitData; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnCancelled_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnCancelled_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnInterrupted_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnInterrupted_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnBlendOut_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnBlendOut_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnCompleted_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnCompleted_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6 // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6"); UGAB_AthenaDBNO_C_OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6 // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6"); UGAB_AthenaDBNO_C_OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent // (Event, Protected, HasOutParms, BlueprintEvent) // Parameters: // struct FGameplayEventData* EventData (ConstParm, Parm, OutParm, ReferenceParm) void UGAB_AthenaDBNO_C::K2_ActivateAbilityFromEvent(struct FGameplayEventData* EventData) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent"); UGAB_AthenaDBNO_C_K2_ActivateAbilityFromEvent_Params params; params.EventData = EventData; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility // (Event, Protected, BlueprintEvent) void UGAB_AthenaDBNO_C::K2_OnEndAbility() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility"); UGAB_AthenaDBNO_C_K2_OnEndAbility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UGAB_AthenaDBNO_C::ExecuteUbergraph_GAB_AthenaDBNO(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO"); UGAB_AthenaDBNO_C_ExecuteUbergraph_GAB_AthenaDBNO_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
6,497
2,929
#include "PresetFrameIO.hpp" #include "wipemalloc.h" #include <math.h> #include <cassert> #include <iostream> PresetInputs::PresetInputs() { } void PresetInputs::Initialize ( int gx, int gy ) { int x, y; this->gx =gx; this->gy= gy; this->x_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->x_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->y_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->y_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->rad_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->rad_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->theta_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x <gx; x++ ) { this->theta_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->origtheta= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->origtheta[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->origrad= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->origrad[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->origx= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->origx[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->origy= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->origy[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } for ( x=0;x<gx;x++ ) { for ( y=0;y<gy;y++ ) { this->origx[x][y]=mathval(x/ ( float ) ( gx-1 )); this->origy[x][y]=mathval(- ( ( y/ ( float ) ( gy-1 ) )-1 )); this->origrad[x][y]=mathval( hypotf ( ( mathtofloat(this->origx[x][y])-.5f ) *2, ( mathtofloat(this->origy[x][y])-.5f ) *2 ) * .7071067f); this->origtheta[x][y]=mathval(atan2 ( ( ( mathtofloat(this->origy[x][y])-.5f ) *2 ), ( ( mathtofloat(this->origx[x][y])-.5f ) *2 ) )); } } } PresetOutputs::PresetOutputs() {} PresetOutputs::~PresetOutputs() { assert(this->gx > 0); for ( int x = 0; x < this->gx; x++ ) { free(this->x_mesh[x]); free(this->y_mesh[x]); free(this->sx_mesh[x]); free(this->sy_mesh[x]); free(this->dy_mesh[x]); free(this->dx_mesh[x]); free(this->cy_mesh[x]); free(this->cx_mesh[x]); free(this->warp_mesh[x]); free(this->zoom_mesh[x]); free(this->zoomexp_mesh[x]); free(this->rot_mesh[x]); } free(this->x_mesh); free(this->y_mesh); free(this->sx_mesh); free(this->sy_mesh); free(this->dy_mesh); free(this->dx_mesh); free(this->cy_mesh); free(this->cx_mesh); free(this->warp_mesh); free(this->zoom_mesh); free(this->zoomexp_mesh); free(this->rot_mesh); } void PresetOutputs::Initialize ( int gx, int gy ) { assert(gx > 0); this->gx = gx; this->gy= gy; assert(this->gx > 0); int x; this->x_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->x_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->y_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->y_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->sx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->sx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->sy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->sy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->dx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->dx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->dy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->dy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->cx_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->cx_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->cy_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->cy_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->zoom_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->zoom_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->zoomexp_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->zoomexp_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->rot_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->rot_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } this->warp_mesh= ( mathtype ** ) wipemalloc ( gx * sizeof ( mathtype * ) ); for ( x = 0; x < gx; x++ ) { this->warp_mesh[x] = ( mathtype * ) wipemalloc ( gy * sizeof ( mathtype ) ); } } PresetInputs::~PresetInputs() { for ( int x = 0; x < this->gx; x++ ) { free ( this->origtheta[x] ); free ( this->origrad[x] ); free ( this->origx[x] ); free ( this->origy[x] ); free ( this->x_mesh[x] ); free ( this->y_mesh[x] ); free ( this->rad_mesh[x] ); free ( this->theta_mesh[x] ); } free ( this->origx ); free ( this->origy ); free ( this->origrad ); free ( this->origtheta ); free ( this->x_mesh ); free ( this->y_mesh ); free ( this->rad_mesh ); free ( this->theta_mesh ); this->origx = NULL; this->origy = NULL; this->origtheta = NULL; this->origrad = NULL; this->x_mesh = NULL; this->y_mesh = NULL; this->rad_mesh = NULL; this->theta_mesh = NULL; } void PresetInputs::ResetMesh() { int x,y; assert ( x_mesh ); assert ( y_mesh ); assert ( rad_mesh ); assert ( theta_mesh ); for ( x=0;x<this->gx;x++ ) { for ( y=0;y<this->gy;y++ ) { x_mesh[x][y]=this->origx[x][y]; y_mesh[x][y]=this->origy[x][y]; rad_mesh[x][y]=this->origrad[x][y]; theta_mesh[x][y]=this->origtheta[x][y]; } } }
6,391
3,098
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2000 Simon Hausmann (hausmann@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2006, 2008, 2009 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "core/html/HTMLFrameElementBase.h" #include "bindings/core/v8/BindingSecurity.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/ScriptEventListener.h" #include "core/HTMLNames.h" #include "core/dom/Attribute.h" #include "core/dom/Document.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/frame/RemoteFrame.h" #include "core/frame/RemoteFrameView.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/html/parser/HTMLParserIdioms.h" #include "core/loader/FrameLoader.h" #include "core/loader/FrameLoaderClient.h" #include "core/page/FocusController.h" #include "core/page/Page.h" namespace blink { using namespace HTMLNames; HTMLFrameElementBase::HTMLFrameElementBase(const QualifiedName& tagName, Document& document) : HTMLFrameOwnerElement(tagName, document), m_scrollingMode(ScrollbarAuto), m_marginWidth(-1), m_marginHeight(-1) {} bool HTMLFrameElementBase::isURLAllowed() const { if (m_URL.isEmpty()) return true; const KURL& completeURL = document().completeURL(m_URL); if (contentFrame() && protocolIsJavaScript(completeURL)) { // Check if the caller can execute script in the context of the content // frame. NB: This check can be invoked without any JS on the stack for some // parser operations. In such case, we use the origin of the frame element's // containing document as the caller context. v8::Isolate* isolate = toIsolate(&document()); LocalDOMWindow* accessingWindow = isolate->InContext() ? currentDOMWindow(isolate) : document().domWindow(); if (!BindingSecurity::shouldAllowAccessToFrame( accessingWindow, contentFrame(), BindingSecurity::ErrorReportOption::Report)) return false; } LocalFrame* parentFrame = document().frame(); if (parentFrame) return parentFrame->isURLAllowed(completeURL); return true; } void HTMLFrameElementBase::openURL(bool replaceCurrentItem) { if (!isURLAllowed()) return; if (m_URL.isEmpty()) m_URL = AtomicString(blankURL().getString()); LocalFrame* parentFrame = document().frame(); if (!parentFrame) return; // Support for <frame src="javascript:string"> KURL scriptURL; KURL url = document().completeURL(m_URL); if (protocolIsJavaScript(m_URL)) { // We'll set/execute |scriptURL| iff CSP allows us to execute inline // JavaScript. If CSP blocks inline JavaScript, then exit early if // we're trying to execute script in an existing document. If we're // executing JavaScript to create a new document (e.g. // '<iframe src="javascript:...">' then continue loading 'about:blank' // so that the frame is populated with something reasonable. if (ContentSecurityPolicy::shouldBypassMainWorld(&document()) || document().contentSecurityPolicy()->allowJavaScriptURLs( this, document().url(), OrdinalNumber::first())) { scriptURL = url; } else { if (contentFrame()) return; } url = blankURL(); } if (!loadOrRedirectSubframe(url, m_frameName, replaceCurrentItem)) return; if (!contentFrame() || scriptURL.isEmpty() || !contentFrame()->isLocalFrame()) return; if (contentFrame()->owner()->getSandboxFlags() & SandboxOrigin) return; toLocalFrame(contentFrame()) ->script() .executeScriptIfJavaScriptURL(scriptURL, this); } void HTMLFrameElementBase::frameOwnerPropertiesChanged() { // Don't notify about updates if contentFrame() is null, for example when // the subframe hasn't been created yet. if (contentFrame()) document().frame()->loader().client()->didChangeFrameOwnerProperties(this); } void HTMLFrameElementBase::parseAttribute( const AttributeModificationParams& params) { const QualifiedName& name = params.name; const AtomicString& value = params.newValue; if (name == srcdocAttr) { if (!value.isNull()) { setLocation(srcdocURL().getString()); } else { const AtomicString& srcValue = fastGetAttribute(srcAttr); if (!srcValue.isNull()) setLocation(stripLeadingAndTrailingHTMLSpaces(srcValue)); } } else if (name == srcAttr && !fastHasAttribute(srcdocAttr)) { setLocation(stripLeadingAndTrailingHTMLSpaces(value)); } else if (name == idAttr) { // Important to call through to base for the id attribute so the hasID bit // gets set. HTMLFrameOwnerElement::parseAttribute(params); m_frameName = value; } else if (name == nameAttr) { m_frameName = value; } else if (name == marginwidthAttr) { setMarginWidth(value.toInt()); } else if (name == marginheightAttr) { setMarginHeight(value.toInt()); } else if (name == scrollingAttr) { // Auto and yes both simply mean "allow scrolling." No means "don't allow // scrolling." if (equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "yes")) setScrollingMode(ScrollbarAuto); else if (equalIgnoringCase(value, "no")) setScrollingMode(ScrollbarAlwaysOff); } else if (name == onbeforeunloadAttr) { // FIXME: should <frame> elements have beforeunload handlers? setAttributeEventListener( EventTypeNames::beforeunload, createAttributeEventListener(this, name, value, eventParameterName())); } else { HTMLFrameOwnerElement::parseAttribute(params); } } void HTMLFrameElementBase::setNameAndOpenURL() { m_frameName = getNameAttribute(); openURL(); } Node::InsertionNotificationRequest HTMLFrameElementBase::insertedInto( ContainerNode* insertionPoint) { HTMLFrameOwnerElement::insertedInto(insertionPoint); return InsertionShouldCallDidNotifySubtreeInsertions; } void HTMLFrameElementBase::didNotifySubtreeInsertionsToDocument() { if (!document().frame()) return; if (!SubframeLoadingDisabler::canLoadFrame(*this)) return; // We should never have a content frame at the point where we got inserted // into a tree. SECURITY_CHECK(!contentFrame()); setNameAndOpenURL(); } void HTMLFrameElementBase::attachLayoutTree(const AttachContext& context) { HTMLFrameOwnerElement::attachLayoutTree(context); if (layoutPart()) { if (Frame* frame = contentFrame()) { if (frame->isLocalFrame()) setWidget(toLocalFrame(frame)->view()); else if (frame->isRemoteFrame()) setWidget(toRemoteFrame(frame)->view()); } } } void HTMLFrameElementBase::setLocation(const String& str) { m_URL = AtomicString(str); if (isConnected()) openURL(false); } bool HTMLFrameElementBase::supportsFocus() const { return true; } void HTMLFrameElementBase::setFocused(bool received) { HTMLFrameOwnerElement::setFocused(received); if (Page* page = document().page()) { if (received) { page->focusController().setFocusedFrame(contentFrame()); } else if (page->focusController().focusedFrame() == contentFrame()) { // Focus may have already been given to another frame, don't take it away. page->focusController().setFocusedFrame(nullptr); } } } bool HTMLFrameElementBase::isURLAttribute(const Attribute& attribute) const { return attribute.name() == longdescAttr || attribute.name() == srcAttr || HTMLFrameOwnerElement::isURLAttribute(attribute); } bool HTMLFrameElementBase::hasLegalLinkAttribute( const QualifiedName& name) const { return name == srcAttr || HTMLFrameOwnerElement::hasLegalLinkAttribute(name); } bool HTMLFrameElementBase::isHTMLContentAttribute( const Attribute& attribute) const { return attribute.name() == srcdocAttr || HTMLFrameOwnerElement::isHTMLContentAttribute(attribute); } // FIXME: Remove this code once we have input routing in the browser // process. See http://crbug.com/339659. void HTMLFrameElementBase::defaultEventHandler(Event* event) { if (contentFrame() && contentFrame()->isRemoteFrame()) { toRemoteFrame(contentFrame())->forwardInputEvent(event); return; } HTMLFrameOwnerElement::defaultEventHandler(event); } void HTMLFrameElementBase::setScrollingMode(ScrollbarMode scrollbarMode) { if (m_scrollingMode == scrollbarMode) return; if (contentDocument()) { contentDocument()->willChangeFrameOwnerProperties( m_marginWidth, m_marginHeight, scrollbarMode); } m_scrollingMode = scrollbarMode; frameOwnerPropertiesChanged(); } void HTMLFrameElementBase::setMarginWidth(int marginWidth) { if (m_marginWidth == marginWidth) return; if (contentDocument()) { contentDocument()->willChangeFrameOwnerProperties( marginWidth, m_marginHeight, m_scrollingMode); } m_marginWidth = marginWidth; frameOwnerPropertiesChanged(); } void HTMLFrameElementBase::setMarginHeight(int marginHeight) { if (m_marginHeight == marginHeight) return; if (contentDocument()) { contentDocument()->willChangeFrameOwnerProperties( m_marginWidth, marginHeight, m_scrollingMode); } m_marginHeight = marginHeight; frameOwnerPropertiesChanged(); } } // namespace blink
10,196
3,007
#include "HaasMLMnn.h" #include "HaasLog.h" #include "HaasErrno.h" HaasMLMnn::HaasMLMnn() { LOG_D("entern\n"); } HaasMLMnn::~HaasMLMnn() { LOG_D("entern\n"); } int HaasMLMnn::SetInputData(const char* dataPath) { LOG_D("entern\n"); return STATUS_OK; } int HaasMLMnn::LoadNet(const char* modePath) { LOG_D("entern\n"); return STATUS_OK; } int HaasMLMnn::Predict() { LOG_D("entern\n"); return STATUS_OK; } int HaasMLMnn::GetPredictResponses(char* outResult, int len) { LOG_D("entern\n"); return STATUS_OK; } int HaasMLMnn::UnLoadNet() { LOG_D("entern\n"); return STATUS_OK; }
629
302
#include <cstdlib> #include <cmath> #include <cassert> #include <numeric> #include <functional> #include <iostream> #include "Common.h" #include "Util.h" namespace Horus { namespace UnitTests { const std::string modelFile = "../examples/complex.fg" ; const std::vector<Params> marginalProbs = { /* marginals x0 = */ {0.5825521, 0.4174479}, /* marginals x1 = */ {0.648528, 0.351472}, {0.03100852, 0.9689915}, {0.04565728, 0.503854, 0.4504888}, {0.7713128, 0.03128429, 0.1974029}, {0.8771822, 0.1228178}, {0.05617282, 0.01509834, 0.9287288}, {0.08224711, 0.5698616, 0.047964, 0.2999273}, {0.1368483, 0.8631517}, /* marginals x9 = */ {0.7529569, 0.2470431} }; const Params jointProbs = { /* P(x0=0, x4=0, x6=0) = */ 0.025463399, /* P(x0=0, x4=0, x6=1) = */ 0.0067233122, /* P(x0=0, x4=0, x6=2) = */ 0.42069289, /* P(x0=0, x4=1, x6=0) = */ 0.0010111473, /* P(x0=0, x4=1, x6=1) = */ 0.00027096982, /* P(x0=0, x4=1, x6=2) = */ 0.016715682, /* P(x0=0, x4=2, x6=0) = */ 0.0062433667, /* P(x0=0, x4=2, x6=1) = */ 0.001828545, /* P(x0=0, x4=2, x6=2) = */ 0.10360283, /* P(x0=1, x4=0, x6=0) = */ 0.017910021, /* P(x0=1, x4=0, x6=1) = */ 0.0046988842, /* P(x0=1, x4=0, x6=2) = */ 0.29582433, /* P(x0=1, x4=1, x6=0) = */ 0.00074648444, /* P(x0=1, x4=1, x6=1) = */ 0.00019991076, /* P(x0=1, x4=1, x6=2) = */ 0.012340097, /* P(x0=1, x4=2, x6=0) = */ 0.0047984062, /* P(x0=1, x4=2, x6=1) = */ 0.0013767189, /* P(x0=1, x4=2, x6=2) = */ 0.079553004 }; Params generateRandomParams (Ranges ranges) { Params params; unsigned size = std::accumulate (ranges.begin(), ranges.end(), 1, std::multiplies<unsigned>()); for (unsigned i = 0; i < size; i++) { params.push_back (rand() / double (RAND_MAX)); } Horus::LogAware::normalize (params); return params; } bool similiar (double v1, double v2) { const double epsilon = 0.0000001; return std::fabs (v1 - v2) < epsilon; } bool similiar (const Params& p1, const Params& p2) { assert (p1.size() == p2.size()); for (size_t i = 0; i < p1.size(); i++) { if (! similiar(p1[i], p2[i])) { return false; } } return true; } } // namespace UnitTests } // namespace Horus;
2,346
1,370
// Copyright (c) 2014-2019 Michael C. Heiber // This source file is part of the Ising_OPV project, which is subject to the MIT License. // For more information, see the LICENSE file that accompanies this software. // The Ising_OPV project can be found on Github at https://github.com/MikeHeiber/Ising_OPV #include "Parameters.h" using namespace std; namespace Ising_OPV { Parameters::Parameters() { } bool Parameters::checkParameters() const { bool Error_found = false; // Check for valid lattice dimensions if (Length <= 0 || Width <= 0 || Height <= 0) { cout << "Parameter error! The input Length, Width, and Height of the lattice must be greater than zero." << endl; Error_found = true; } // Check the input mix fraction if (Mix_fraction < 0 || Mix_fraction > 1) { cout << "Parameter error! The input Mix_fraction must be between 0 and 1." << endl; Error_found = true; } // Check the input interaction energies if (Interaction_energy1 < 0 || Interaction_energy2 < 0) { cout << "Parameter error! The input Interaction_energy1 and Interaction_energy2 parameters cannot be negative." << endl; Error_found = true; } // Check the input number of Monte Carlo steps if (MC_steps < 0) { cout << "Parameter error! The input MC_steps parameter cannot be negative." << endl; Error_found = true; } // Check the smoothing parameters if (Enable_smoothing && !(Smoothing_threshold > 0)) { cout << "Parameter error! When performing smoothing, the input Smoothing_threshold must be greater than zero." << endl; Error_found = true; } // Check the lattice resclae parameters if (Enable_rescale && !(Rescale_factor > 0)) { cout << "Parameter error! When rescaling the lattice, the input Rescale_factor must be greater than zero." << endl; Error_found = true; } if (Enable_rescale && Enable_shrink && (Length % Rescale_factor != 0 || Width % Rescale_factor != 0 || Height % Rescale_factor != 0)) { cout << "Parameter error! When shrinking the lattice, the input Rescale_factor must be an integer multiple of the Length, Width, and Height." << endl; Error_found = true; } // Check the interfacial mixing parameters if (Enable_interfacial_mixing && !(Interface_width > 0)) { cout << "Parameter error! When performing interfacial mixing, the input Interface_width must be greater than zero." << endl; Error_found = true; } if (Enable_interfacial_mixing && (!(Interface_conc > 0) || !(Interface_conc < 1))) { cout << "Parameter error! When performing interfacial mixing, the input Interface_conc must be greater than zero and less than 1." << endl; Error_found = true; } // Check the correlation calculation parameters if (Enable_correlation_calc && !(N_sampling_max > 0)) { cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && Enable_mix_frac_method && Enable_e_method) { cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && !Enable_mix_frac_method && !Enable_e_method) { cout << "Parameter error! When performing the correlation calculation, either the mix fraction method or the 1/e method must be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && Enable_extended_correlation_calc && !(Extended_correlation_cutoff_distance > 0)) { cout << "Parameter error! When performing the extended correlation calculation, Extended_correlation_cutoff_distance must be greater than zero." << endl; Error_found = true; } // Check the growth preference parameters if (Enable_growth_pref && (Growth_direction < 1 || Growth_direction > 3)) { cout << "Parameter error! When performing phase separation with a directional growth preference, the input Growth_direction paramter must be 1, 2, or 3." << endl; Error_found = true; } if (Enable_growth_pref && !(Additional_interaction > 0) && !(Additional_interaction < 0)) { cout << "Parameter error! When performing phase separation with a directional growth preference, the input Additional_interaction parameter must not be zero." << endl; Error_found = true; } // Check tomogram import parameters if (Enable_import_morphologies && Enable_import_tomogram) { cout << "Parameter error! The import morphologies and import tomogram options cannot both be enabled." << endl; Error_found = true; } if (Enable_import_tomogram && !(Desired_unit_size > 0)) { cout << "Parameter error! When importing a tomogram dataset, the input Desired_unit_size must not be zero." << endl; Error_found = true; } if (Enable_import_tomogram && !(Mixed_frac < 1)) { cout << "Parameter error! When importing a tomogram dataset, the Mixed_frac must be graeter than equal to 0 and less than 1." << endl; Error_found = true; } if (Enable_import_tomogram && (!(Mixed_conc > 0) || !(Mixed_conc < 1))) { cout << "Parameter error! When importing a tomogram dataset, the Mixed_conc must be greater than zero and less than 1." << endl; Error_found = true; } //if (Enable_import_tomogram && !Enable_cutoff_analysis && !Enable_probability_analysis) { // cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis or the probability analysis option must be enabled." << endl; // Error_found = true; //} //if (Enable_import_tomogram && Enable_cutoff_analysis && Enable_probability_analysis) { // cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis and the probability analysis options cannot both be enabled." << endl; // Error_found = true; //} //if (Enable_import_tomogram && Enable_probability_analysis && Probability_scaling_exponent < 0) { // cout << "Parameter error! When importing a tomogram dataset and using the probability analysis option, the Probability_scaling_exponent must not be negative." << endl; // Error_found = true; //} if (Enable_import_tomogram && N_extracted_segments <= 0) { cout << "Parameter error! When importing a tomogram dataset, the input N_extracted segments must be greater than zero." << endl; Error_found = true; } if (Enable_import_tomogram && N_variants <= 0) { cout << "Parameter error! When importing a tomogram dataset, the input N_variants segments must be greater than zero." << endl; Error_found = true; } if (Enable_import_tomogram && N_extracted_segments != intpow((int)floor(sqrt(N_extracted_segments)), 2)) { cout << "Parameter error! When importing a tomogram dataset, the input value for N_extracted_segments must be 1, 4, 9, 16, 25, 36, 49, 64, 89, 100, 121, 144, 169, or 196 but " << N_extracted_segments << " was entered." << endl; Error_found = true; } // Check other parameter conflicts if (Enable_analysis_only && !Enable_import_morphologies && !Enable_import_tomogram) { cout << "Parameter error! The 'analysis only' option can only be used when importing morphologies." << endl; Error_found = true; } if (Error_found) { return false; } return true; } bool Parameters::importParameters(ifstream& parameterfile) { Version min_version("4.0.0-rc.1"); string line; // Parse header file line getline(parameterfile, line); line = line.substr(line.find('v') + 1); Version file_version; try { file_version = Version(line); } catch (invalid_argument exception) { cout << "Error! Unable to load parameter file with version " << line << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl; return false; } if (file_version < min_version) { cout << "Error! Unable to load parameter file with v" << file_version << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl; return false; } string var; vector<string> stringvars; // Read input file line by line. while (getline(parameterfile, line)) { // Skip lines designated as section breaks and section headers. if ((line.substr(0, 2)).compare("--") != 0 && (line.substr(0, 2)).compare("##") != 0) { // Strip off trailing comments from each line. var = line.substr(0, line.find("//")); var = removeWhitespace(var); // Add parameter value strings to a vector. stringvars.push_back(var); } } // Check that correct number of parameters have been imported if ((int)stringvars.size() != 42) { cout << "Error! Incorrect number of parameters were loaded from the parameter file." << endl; return false; } bool Error_found = false; int i = 0; // Convert strings into the correct data type and assign them to their corresponding parameter variable. // General Parameters Length = atoi(stringvars[i].c_str()); i++; Width = atoi(stringvars[i].c_str()); i++; Height = atoi(stringvars[i].c_str()); i++; //enable_z_periodic_boundary try { Enable_periodic_z = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting z-direction periodic boundary conditions!" << endl; Error_found = true; } i++; Mix_fraction = atof(stringvars[i].c_str()); i++; Interaction_energy1 = atof(stringvars[i].c_str()); i++; Interaction_energy2 = atof(stringvars[i].c_str()); i++; MC_steps = atoi(stringvars[i].c_str()); i++; //enable_smoothing try { Enable_smoothing = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology smoothing options" << endl; Error_found = true; } i++; Smoothing_threshold = atof(stringvars[i].c_str()); i++; //enable_rescale try { Enable_rescale = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology rescale options" << endl; Error_found = true; } i++; Rescale_factor = atoi(stringvars[i].c_str()); i++; try { Enable_shrink = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology shrink options" << endl; Error_found = true; } i++; //enable_interfacial_mixing try { Enable_interfacial_mixing = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting interfacial mixing options" << endl; Error_found = true; } i++; Interface_width = atof(stringvars[i].c_str()); i++; Interface_conc = atof(stringvars[i].c_str()); i++; //enable_analysis_only try { Enable_analysis_only = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting analysis options" << endl; Error_found = true; } i++; //enable_correlation_calc try { Enable_correlation_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation options" << endl; Error_found = true; } i++; N_sampling_max = atoi(stringvars[i].c_str()); i++; //enable_mix_frac_method try { Enable_mix_frac_method = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation domain size determination method options" << endl; Error_found = true; } i++; //enable_e_method try { Enable_e_method = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation domain size determination method options" << endl; Error_found = true; } i++; //enable_extended_correlation_calc try { Enable_extended_correlation_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting extended correlation calculation options" << endl; Error_found = true; } i++; Extended_correlation_cutoff_distance = atoi(stringvars[i].c_str()); i++; //enable_interfacial_distance_calc try { Enable_interfacial_distance_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting interfacial distance calculation options" << endl; Error_found = true; } i++; //enable_tortuosity_calc try { Enable_tortuosity_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting tortuosity calculation options" << endl; Error_found = true; } i++; //enable_reduced_memory_tortuosity_calc try { Enable_reduced_memory_tortuosity_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting reduced memory tortuosity calculation options" << endl; Error_found = true; } i++; //enable_depth_dependent_cal try { Enable_depth_dependent_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting areal mapping calculation options" << endl; Error_found = true; } i++; //enable_areal_maps_cal try { Enable_areal_maps_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting depth dependent calculation options" << endl; Error_found = true; } i++; //enable_checkerboard_start try { Enable_checkerboard_start = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting checkerboard starting condition" << endl; Error_found = true; } i++; //enable_growth_pref try { Enable_growth_pref = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting growth preference conditions" << endl; Error_found = true; } i++; Growth_direction = atoi(stringvars[i].c_str()); i++; Additional_interaction = atof(stringvars[i].c_str()); i++; // Export Morphology Parameters //Enable_export_compressed_files try { Enable_export_compressed_files = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting export options" << endl; Error_found = true; } i++; //Enable_export_cross_section try { Enable_export_cross_section = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting export cross-section options" << endl; Error_found = true; } i++; // Import Morphology Options //Enable_import_morphologies try { Enable_import_morphologies = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology import option" << endl; Error_found = true; } i++; // Tomogram Import Options //Enable_import_tomogram try { Enable_import_tomogram = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting tomogram import option" << endl; Error_found = true; } i++; Tomogram_name = stringvars[i]; i++; Desired_unit_size = atof(stringvars[i].c_str()); i++; //try { // Enable_cutoff_analysis = str2bool(stringvars[i]); //} //catch (invalid_argument& exception) { // cout << exception.what() << endl; // cout << "Error setting tomogram import conditions" << endl; // Error_found = true; //} //i++; Mixed_frac = atof(stringvars[i].c_str()); i++; Mixed_conc = atof(stringvars[i].c_str()); i++; //try { // Enable_probability_analysis = str2bool(stringvars[i]); //} //catch (invalid_argument& exception) { // cout << exception.what() << endl; // cout << "Error setting tomogram import conditions" << endl; // Error_found = true; //} //i++; //Probability_scaling_exponent = atof(stringvars[i].c_str()); //i++; N_extracted_segments = atoi(stringvars[i].c_str()); i++; N_variants = atoi(stringvars[i].c_str()); i++; return !Error_found; } }
16,513
5,895
#include <qpdf/Pl_ASCIIHexDecoder.hh> #include <qpdf/QTC.hh> #include <stdexcept> #include <string.h> #include <ctype.h> Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) : Pipeline(identifier, next), pos(0), eod(false) { this->inbuf[0] = '0'; this->inbuf[1] = '0'; this->inbuf[2] = '\0'; } Pl_ASCIIHexDecoder::~Pl_ASCIIHexDecoder() { } void Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) { if (this->eod) { return; } for (size_t i = 0; i < len; ++i) { char ch = static_cast<char>(toupper(buf[i])); switch (ch) { case ' ': case '\f': case '\v': case '\t': case '\r': case '\n': QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); // ignore whitespace break; case '>': this->eod = true; flush(); break; default: if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'F'))) { this->inbuf[this->pos++] = ch; if (this->pos == 2) { flush(); } } else { char t[2]; t[0] = ch; t[1] = 0; throw std::runtime_error( std::string("character out of range" " during base Hex decode: ") + t); } break; } if (this->eod) { break; } } } void Pl_ASCIIHexDecoder::flush() { if (this->pos == 0) { QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush"); return; } int b[2]; for (int i = 0; i < 2; ++i) { if (this->inbuf[i] >= 'A') { b[i] = this->inbuf[i] - 'A' + 10; } else { b[i] = this->inbuf[i] - '0'; } } unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]); QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", (this->pos == 2) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. this->pos = 0; this->inbuf[0] = '0'; this->inbuf[1] = '0'; this->inbuf[2] = '\0'; getNext()->write(&ch, 1); } void Pl_ASCIIHexDecoder::finish() { flush(); getNext()->finish(); }
2,028
933
//! ---------------------------------------------------------------------------- //! Copyright Verizon. //! //! \file: TODO //! \details: TODO //! //! Licensed under the terms of the Apache 2.0 open source license. //! Please refer to the LICENSE file in the project root for the terms. //! ---------------------------------------------------------------------------- //! ---------------------------------------------------------------------------- //! includes //! ---------------------------------------------------------------------------- #include "status.h" #include "support/ndebug.h" #include "support/trace.h" #include "support/nbq.h" #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <stdint.h> #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif #include <inttypes.h> namespace ns_hurl { //! ---------------------------------------------------------------------------- //! Macros //! ---------------------------------------------------------------------------- #define CHECK_FOR_NULL_AND_LEN(_buf, _len)\ do{\ if(!_buf) {\ return -1;\ }\ if(!_len) {\ return 0;\ }\ }while(0)\ //! ---------------------------------------------------------------------------- //! \details: nbq //! ---------------------------------------------------------------------------- typedef struct nb_struct { // ------------------------------------------------- // std constructor // ------------------------------------------------- nb_struct(uint32_t a_len): m_data(NULL), m_len(a_len), m_written(0), m_read(0), m_ref(false) { m_data = (char *)malloc(a_len); } // ------------------------------------------------- // std constructor // ------------------------------------------------- nb_struct(char *a_buf, uint32_t a_len): m_data(a_buf), m_len(a_len), m_written(a_len), m_read(0), m_ref(true) {} // ------------------------------------------------- // destructor // ------------------------------------------------- ~nb_struct(void) { if(m_data && !m_ref) { free(m_data); } m_data = NULL; m_len = 0; } uint32_t write_avail(void) { return m_len - m_written;} uint32_t read_avail(void) { return m_written - m_read;} char *data(void) { return m_data; } bool ref(void) const { return m_ref; } uint32_t size(void) { return m_len; } uint32_t written(void) { return m_written; } char *write_ptr(void) { return m_data + m_written; } void write_inc(uint32_t a_inc) { m_written += a_inc; } void write_reset(void) { m_written = 0; m_read = 0;} char *read_ptr(void) { return m_data + m_read; } void read_inc(uint32_t a_inc) { m_read += a_inc; } void read_reset(void) { m_read = 0; } private: // Disallow copy/assign nb_struct& operator=(const nb_struct &); nb_struct(const nb_struct &); char *m_data; uint32_t m_len; uint32_t m_written; uint32_t m_read; bool m_ref; } nb_t; //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- nbq::nbq(uint32_t a_bsize): m_q(), m_bsize(a_bsize), m_cur_write_block(), m_cur_read_block(), m_idx(0), m_cur_write_offset(0), m_total_read_avail(0), m_max_read_queue(-1) { m_cur_write_block = m_q.end(); m_cur_read_block = m_q.end(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- nbq::~nbq(void) { for(nb_list_t::iterator i_b = m_q.begin(); i_b != m_q.end(); ++i_b) { if(*i_b) { delete *i_b; } } } //! ----------------------------------------------------------------------------- //! \details: Write an array of characters to the current write block //! \return: Number of characters written. -1 in case of error. //! \param: a_buf the buffer containing characters to be written to write block //! \param: a_len the length of a_buf //! ----------------------------------------------------------------------------- int64_t nbq::write(const char *a_buf, uint64_t a_len) { CHECK_FOR_NULL_AND_LEN(a_buf, a_len); uint64_t l_left = a_len; uint64_t l_written = 0; const char *l_buf = a_buf; while(l_left) { if(b_write_avail() <= 0) { int32_t l_status = b_write_add_avail(); if(l_status <= 0) { TRC_ERROR("error performing b_write_add_avail\n"); return -1; } } uint32_t l_write_avail = b_write_avail(); uint32_t l_write = (l_left > l_write_avail)?l_write_avail:l_left; memcpy(b_write_ptr(), l_buf, l_write); b_write_incr(l_write); l_left -= l_write; l_buf += l_write; l_written += l_write; } return l_written; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int64_t nbq::write_fd(int a_fd, uint64_t a_len, ssize_t &a_status) { if(!a_len) { return 0; } uint64_t l_left = a_len; uint64_t l_written = 0; while(l_left) { if(b_write_avail() <= 0) { int32_t l_status = b_write_add_avail(); if(l_status <= 0) { // TODO error... return -1; } } uint32_t l_write_avail = b_write_avail(); uint32_t l_write = (l_left > l_write_avail)?l_write_avail:l_left; errno = 0; a_status = ::read(a_fd, b_write_ptr(), l_write); if(a_status > 0) { b_write_incr(a_status); b_read_incr(0); l_left -= a_status; l_written += a_status; } else if((a_status == 0) || ((a_status < 0) && (errno == EAGAIN))) { break; } else if(a_status < 0) { return STATUS_ERROR; } } return l_written; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int64_t nbq::write_q(nbq &a_q) { uint64_t l_left = a_q.read_avail(); uint64_t l_written = 0; while(l_left) { if(b_write_avail() <= 0) { int32_t l_status = b_write_add_avail(); if(l_status <= 0) { TRC_ERROR("b_write_add_avail()\n"); return STATUS_ERROR; } } uint32_t l_write_avail = b_write_avail(); uint32_t l_write = (l_left > l_write_avail)?l_write_avail:l_left; ssize_t l_status = a_q.read(b_write_ptr(), l_write); if(l_status < 0) { TRC_ERROR("a_q.read()\n"); return STATUS_ERROR; } if(l_status == 0) { break; } b_write_incr(l_status); l_left -= l_status; l_written += l_status; } return l_written; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- char nbq::peek(void) const { if(read_avail()) { return *b_read_ptr(); } return '\0'; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int64_t nbq::read(char *a_buf, uint64_t a_len) { if(!a_len) { return 0; } uint64_t l_read = 0; char *l_buf = a_buf; uint64_t l_total_read_avail = read_avail(); uint64_t l_left = (a_len > l_total_read_avail)?l_total_read_avail:a_len; while(l_left) { uint32_t l_read_avail = b_read_avail(); uint32_t l_read_size = (l_left > l_read_avail)?l_read_avail:l_left; if(l_buf) { memcpy(l_buf, b_read_ptr(), l_read_size); l_buf += l_read_size; } b_read_incr(l_read_size); l_left -= l_read_size; l_read += l_read_size; } return l_read; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- uint64_t nbq::read_seek(uint64_t a_off) { reset_read(); return read(NULL, a_off); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- uint64_t nbq::read_from(uint64_t a_off, char *a_buf, uint64_t a_len) { read_seek(a_off); return read(a_buf, a_len); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::reset_read(void) { // reset read ptrs and recalc read available m_total_read_avail = 0; for(nb_list_t::const_iterator i_b = m_q.begin(); i_b != m_q.end(); ++i_b) { (*i_b)->read_reset(); m_total_read_avail += (*i_b)->read_avail(); } m_cur_read_block = m_q.begin(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::reset_write(void) { for(nb_list_t::iterator i_b = m_q.begin(); i_b != m_q.end(); ) { if(!(*i_b)) { ++i_b; continue; } // erase references if((*i_b)->ref()) { delete (*i_b); (*i_b) = NULL; m_q.erase(i_b++); } else { (*i_b)->write_reset(); ++i_b; } } m_cur_write_block = m_q.begin(); m_cur_read_block = m_q.begin(); m_total_read_avail = 0; m_cur_write_offset = 0; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::reset(void) { for(nb_list_t::iterator i_b = m_q.begin(); i_b != m_q.end(); ++i_b) { if(*i_b) { delete *i_b; *i_b = NULL; } } m_q.clear(); m_cur_write_block = m_q.end(); m_cur_read_block = m_q.end(); m_cur_write_offset = 0; m_total_read_avail = 0; } //! ---------------------------------------------------------------------------- //! \details: Free all read //! \return: NA //! \param: NA //! ---------------------------------------------------------------------------- void nbq::shrink(void) { while(m_q.begin() != m_cur_read_block) { nb_t *l_nb = m_q.front(); if(!l_nb) { TRC_ERROR("l_nb == NULL\n"); return; } m_q.pop_front(); m_cur_write_offset -= l_nb->size(); delete l_nb; l_nb = NULL; } if((m_cur_read_block != m_q.end()) && (m_cur_write_block != m_q.end()) && (*m_cur_read_block == *m_cur_write_block)) { nb_t *l_nb = (*m_cur_read_block); if((l_nb->read_avail() == 0) && (l_nb->write_avail() == 0)) { delete l_nb; l_nb = NULL; m_q.clear(); m_cur_write_block = m_q.end(); m_cur_read_block = m_q.end(); m_cur_write_offset = 0; m_total_read_avail = 0; } } } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::print(void) { uint32_t l_total_read_avail = read_avail(); uint32_t l_left = l_total_read_avail; while(l_left) { uint32_t l_read_avail = b_read_avail(); uint32_t l_read_size = (l_left > l_read_avail)?l_read_avail:l_left; TRC_OUTPUT("%.*s", l_read_size, b_read_ptr()); b_read_incr(l_read_size); l_left -= l_read_size; } reset_read(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int32_t nbq::split(nbq **ao_nbq_tail, uint64_t a_offset) { *ao_nbq_tail = NULL; if(!a_offset) { return STATUS_OK; } if(a_offset >= m_cur_write_offset) { TRC_ERROR("requested split at offset: %" PRIu64 " > write_offset: %" PRIu64 "\n", a_offset, m_cur_write_offset); return STATUS_ERROR; } // --------------------------------------- // find block at offset // --------------------------------------- uint64_t i_offset = a_offset; nb_list_t::iterator i_b; for(i_b = m_q.begin(); i_b != m_q.end(); ++i_b) { if(!(*i_b)) { TRC_ERROR("block iter in nbq == NULL\n"); return STATUS_ERROR; } uint32_t l_w = (*i_b)->written(); if(l_w > i_offset) { break; } i_offset -= l_w; } // --------------------------------------- // create new nbq and append remainder // --------------------------------------- nbq *l_nbq = new nbq(m_bsize); if(i_offset > 0) { nb_t &l_b = *(*i_b); if(i_offset >= l_b.written()) { TRC_ERROR("i_offset: %" PRIu64 " >= l_b.written(): %u\n", i_offset, l_b.written()); return STATUS_ERROR; } // write the remainder l_nbq->b_write_add_avail(); l_nbq->write(l_b.data() + i_offset, l_b.written() - i_offset); l_b.write_reset(); l_b.write_inc(i_offset); } // --------------------------------------- // add the tail // --------------------------------------- ++i_b; while (i_b != m_q.end()) { if(!(*i_b)) { TRC_ERROR("block iter in nbq == NULL\n"); return STATUS_ERROR; } //NDBG_PRINT("adding tail block\n"); l_nbq->m_q.push_back(*i_b); (*i_b)->read_reset(); //NDBG_PRINT("removing tail block\n"); m_cur_write_offset -= (*i_b)->written(); l_nbq->m_cur_write_offset += (*i_b)->written(); m_q.erase(i_b++); } l_nbq->m_cur_write_block = --(l_nbq->m_q.end()); l_nbq->m_cur_read_block = l_nbq->m_q.begin(); l_nbq->reset_read(); m_cur_write_block = --m_q.end(); reset_read(); *ao_nbq_tail = l_nbq; return STATUS_OK; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int32_t nbq::join_ref(const nbq &a_nbq_tail) { const nbq &l_nbq_tail = a_nbq_tail; bool l_empty = m_q.empty(); for(nb_list_t::const_iterator i_b = l_nbq_tail.m_q.begin(); i_b != l_nbq_tail.m_q.end(); ++i_b) { if(!(*i_b)) { return STATUS_ERROR; } nb_t &l_b = *(*i_b); nb_t *l_b_ref = new nb_t(l_b.data(), l_b.written()); m_q.push_back(l_b_ref); m_cur_write_offset += l_b_ref->written(); m_total_read_avail += l_b_ref->written(); } m_cur_write_block = m_q.end(); if(l_empty) { m_cur_read_block = m_q.begin(); } // Join nbq with reference nbq return STATUS_OK; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- char * nbq::b_write_ptr(void) { if(m_cur_write_block == m_q.end()) { return NULL; } return (*m_cur_write_block)->write_ptr(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- uint32_t nbq::b_write_avail(void) { if(m_cur_write_block == m_q.end()) { return 0; } return (*m_cur_write_block)->write_avail(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int32_t nbq::b_write_add_avail(void) { nb_t *l_block = new nb_struct(m_bsize); m_q.push_back(l_block); if(m_q.size() == 1) { m_cur_read_block = m_q.begin(); m_cur_write_block = m_q.begin(); } else { if(((*m_cur_write_block)->write_avail() == 0) && (m_cur_write_block != --m_q.end())) { ++m_cur_write_block; } } return (*m_cur_write_block)->write_avail(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::b_write_incr(uint32_t a_len) { m_cur_write_offset += a_len; (*m_cur_write_block)->write_inc(a_len); m_total_read_avail += a_len; if(((*m_cur_write_block)->write_avail() == 0) && (m_cur_write_block != --m_q.end())) { ++m_cur_write_block; } // check for cur read block if((a_len > 0) && ((*m_cur_read_block)->read_avail() == 0)) { ++m_cur_read_block; } } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- char *nbq::b_read_ptr(void) const { if(m_cur_read_block == m_q.end()) { return NULL; } return (*m_cur_read_block)->read_ptr(); } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- int32_t nbq::b_read_avail(void) const { if(m_cur_read_block == m_q.end()) { return 0; } else if(m_cur_read_block == m_cur_write_block) { return m_total_read_avail; } else { return (*m_cur_read_block)->read_avail(); } } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::b_read_incr(uint32_t a_len) { uint32_t l_avail = b_read_avail(); m_total_read_avail -= a_len; l_avail -= a_len; (*m_cur_read_block)->read_inc(a_len); if(!l_avail && m_total_read_avail) { ++m_cur_read_block; } } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::b_display_written(void) { if(m_q.empty()) { return; } uint32_t i_block_num = 0; for(nb_list_t::iterator i_b = m_q.begin(); i_b != m_q.end(); ++i_b, ++i_block_num) { if(!(*i_b)) { return; } NDBG_OUTPUT("+------------------------------------+\n"); NDBG_OUTPUT("| Block: %d -> %p\n", i_block_num, (*i_b)); NDBG_OUTPUT("+------------------------------------+\n"); nb_t &l_b = *(*i_b); mem_display((const uint8_t *)(l_b.data()), l_b.written(), false); if(i_b == m_cur_write_block) { break; } } } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void nbq::b_display_all(void) { uint32_t i_block_num = 0; for(nb_list_t::iterator i_b = m_q.begin(); i_b != m_q.end(); ++i_b, ++i_block_num) { if(!(*i_b)) { return; } NDBG_OUTPUT("+------------------------------------+\n"); NDBG_OUTPUT("| Block: %d -> %p\n", i_block_num, (*i_b)); NDBG_OUTPUT("+------------------------------------+\n"); nb_t &l_b = *(*i_b); mem_display((const uint8_t *)(l_b.data()), l_b.size(), false); } } //! ---------------------------------------------------------------------------- //! Utils... //! ---------------------------------------------------------------------------- //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- char *copy_part(nbq &a_nbq, uint64_t a_off, uint64_t a_len) { char *l_buf = NULL; l_buf = (char *)calloc(1, sizeof(char)*a_len + 1); if(!l_buf) { return NULL; } a_nbq.read_from(a_off, l_buf, a_len); l_buf[a_len] = '\0'; return l_buf; } //! ---------------------------------------------------------------------------- //! \details: TODO //! \return: TODO //! \param: TODO //! ---------------------------------------------------------------------------- void print_part(nbq &a_nbq, uint64_t a_off, uint64_t a_len) { char *l_buf = copy_part(a_nbq, a_off, a_len); TRC_OUTPUT("%.*s", (int)a_len, l_buf); if(l_buf) { free(l_buf); l_buf = NULL; } } } // ns_hurl
25,999
7,807
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ #include "vtkSlicerConfigure.h" // Slicer_VTK_RENDERING_USE_{OpenGL|OpenGL2}_BACKEND // Qt includes #include <QApplication> #include <QTimer> // qMRML includes #include "qMRMLVolumePropertyNodeWidget.h" // MRML includes #include <vtkMRMLVolumePropertyNode.h> // VTK includes #include <vtkSmartPointer.h> #include "qMRMLWidget.h" // this test only works on VTKv6 and later #include <vtkAutoInit.h> #if defined(Slicer_VTK_RENDERING_USE_OpenGL2_BACKEND) VTK_MODULE_INIT(vtkRenderingContextOpenGL2); #else VTK_MODULE_INIT(vtkRenderingContextOpenGL); #endif // STD includes int qMRMLVolumePropertyNodeWidgetTest1(int argc, char * argv [] ) { qMRMLWidget::preInitializeApplication(); QApplication app(argc, argv); qMRMLWidget::postInitializeApplication(); vtkSmartPointer<vtkMRMLVolumePropertyNode> volumePropertyNode = vtkSmartPointer<vtkMRMLVolumePropertyNode>::New(); qMRMLVolumePropertyNodeWidget widget; widget.setMRMLVolumePropertyNode(volumePropertyNode); widget.show(); if (argc < 2 || QString(argv[1]) != "-I" ) { QTimer::singleShot(200, &app, SLOT(quit())); } return app.exec(); }
1,875
636
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ //For now only allows for one solute at a time, jn=-d0*gradc+c*vf //Stiffness does not include effect from different solutes #include "stdafx.h" #include "FEFluidSolutesNaturalFlux.h" #include "FEFluidMaterial.h" #include "FEFluidSolutes.h" #include "FEBioFluidSolutes.h" #include <FECore/FELinearSystem.h> #include <FECore/FEModel.h> #include <FECore/FEAnalysis.h> //----------------------------------------------------------------------------- // Parameter block for pressure loads BEGIN_FECORE_CLASS(FEFluidSolutesNaturalFlux, FESurfaceLoad) ADD_PARAMETER(m_beta, "beta"); ADD_PARAMETER(m_isol , "solute_id"); END_FECORE_CLASS() //----------------------------------------------------------------------------- //! constructor FEFluidSolutesNaturalFlux::FEFluidSolutesNaturalFlux(FEModel* pfem) : FESurfaceLoad(pfem), m_dofW(pfem), m_dofC(pfem) { m_beta = 1.0; m_isol = 1; } //----------------------------------------------------------------------------- //! initialize bool FEFluidSolutesNaturalFlux::Init() { if (m_isol == -1) return false; // set up the dof lists FEModel* fem = GetFEModel(); m_dofC.Clear(); m_dofW.Clear(); m_dofC.AddDof(fem->GetDOFIndex(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::FLUID_CONCENTRATION), m_isol-1)); m_dofW.AddVariable(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::RELATIVE_FLUID_VELOCITY)); m_dof.Clear(); m_dof.AddDofs(m_dofW); m_dof.AddDofs(m_dofC); FESurface& surf = GetSurface(); if (FESurfaceLoad::Init() == false) return false; // get the list of FluidSolutes elements connected to this interface int NF = surf.Elements(); m_elem.resize(NF); for (int j = 0; j<NF; ++j) { FESurfaceElement& el = surf.Element(j); // extract the first of two elements on this interface m_elem[j] = el.m_elem[0]; // get its material and check if FluidSolutes FEMaterial* pm = fem->GetMaterial(m_elem[j]->GetMatID()); FEFluidSolutes* pfsi = dynamic_cast<FEFluidSolutes*>(pm); if (pfsi == nullptr) { pm = fem->GetMaterial(el.m_elem[1]->GetMatID()); pfsi = dynamic_cast<FEFluidSolutes*>(pm); if (pfsi == nullptr) return false; m_elem[j] = el.m_elem[1]; } } return true; } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::Serialize(DumpStream& ar) { FESurfaceLoad::Serialize(ar); if (ar.IsShallow() == false) { ar & m_dofC & m_dofW; } if (ar.IsShallow() == false) { if (ar.IsSaving()) { int NE = (int)m_elem.size(); ar << NE; for (int i = 0; i < NE; ++i) { FEElement* pe = m_elem[i]; int nid = (pe ? pe->GetID() : -1); ar << nid; } } else { FEMesh& mesh = ar.GetFEModel().GetMesh(); int NE, nid; ar >> NE; m_elem.resize(NE, nullptr); for (int i = 0; i < NE; ++i) { ar >> nid; if (nid != -1) { FEElement* pe = mesh.FindElementFromID(nid); assert(pe); m_elem[i] = pe; } } } } } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) { m_psurf->LoadStiffness(LS, m_dof, m_dof, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, const FESurfaceDofShape& dof_b, matrix& Kab) { FESurfaceElement& el = *mp.SurfaceElement(); int iel = el.m_lid; int neln = el.Nodes(); // get the diffusivity FEElement* pe = el.m_elem[0]; FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm); double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp); double d0p = pfsm->GetSolute(m_isol-1)->m_pDiff->Tangent_Free_Diffusivity_Concentration(mp, m_isol-1); double* N = el.H (mp.m_index); double* Gr = el.Gr(mp.m_index); double* Gs = el.Gs(mp.m_index); // tangent vectors vec3d rt[FEElement::MAX_NODES]; m_psurf->GetNodalCoordinates(el, tp.alphaf, rt); vec3d dxr = el.eval_deriv1(rt, mp.m_index); vec3d dxs = el.eval_deriv2(rt, mp.m_index); vec3d n = dxr ^ dxs; //double da = n.unit(); double alpha = tp.alphaf; vector<vec3d> gradN(neln); // Fluid velocity vec3d v = FluidVelocity(mp, tp.alphaf); double c = EffectiveConcentration(mp, tp.alphaf); //vec3d v = FluidVelocityElm(mp); //double c = EffectiveConcentrationElm(mp); vec3d gradc = EffectiveCGrad(mp); vec3d gcnt[2], gcntp[2]; m_psurf->ContraBaseVectors(el, mp.m_index, gcnt); m_psurf->ContraBaseVectorsP(el, mp.m_index, gcntp); for (int i = 0; i<neln; ++i) gradN[i] = (gcnt[0] * alpha + gcntp[0] * (1 - alpha))*Gr[i] + (gcnt[1] * alpha + gcntp[1] * (1 - alpha))*Gs[i]; Kab.zero(); // calculate stiffness component int i = dof_a.index; int j = dof_b.index; vec3d kcw = n*(N[i]*N[j]*c*tp.alphaf); double kcc = n*((-gradc*d0p+v)*N[j]-gradN[j]*d0)*(tp.alphaf*N[i]); Kab[3][0] -= kcw.x; Kab[3][1] -= kcw.y; Kab[3][2] -= kcw.z; Kab[3][3] -= kcc; }); } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::FluidVelocity(FESurfaceMaterialPoint& mp, double alpha) { vec3d vt[FEElement::MAX_NODES]; FESurfaceElement& el = *mp.SurfaceElement(); int neln = el.Nodes(); for (int j = 0; j<neln; ++j) { FENode& node = m_psurf->Node(el.m_lnode[j]); vt[j] = node.get_vec3d(m_dofW[0], m_dofW[1], m_dofW[2])*alpha + node.get_vec3d_prev(m_dofW[0], m_dofW[1], m_dofW[2])*(1 - alpha); } return el.eval(vt, mp.m_index); } //----------------------------------------------------------------------------- double FEFluidSolutesNaturalFlux::EffectiveConcentration(FESurfaceMaterialPoint& mp, double alpha) { double c = 0; FESurfaceElement& el = *mp.SurfaceElement(); double* H = el.H(mp.m_index); int neln = el.Nodes(); for (int j = 0; j < neln; ++j) { FENode& node = m_psurf->Node(el.m_lnode[j]); double cj = node.get(m_dofC[0])*alpha + node.get_prev(m_dofC[0])*(1.0 - alpha); c += cj*H[j]; } return c; } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::EffectiveCGrad(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element vec3d gradc(0.0); FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>()); gradc += spt.m_gradc[m_isol-1]; } gradc /= nint; return gradc; } //----------------------------------------------------------------------------- double FEFluidSolutesNaturalFlux::EffectiveConcentrationElm(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element double c = 0.0; FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>()); c += spt.m_c[m_isol-1]; } c /= nint; return c; } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::FluidVelocityElm(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element vec3d v(0.0); FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidMaterialPoint& fpt = *(mp.ExtractData<FEFluidMaterialPoint>()); v += fpt.m_vft; } v /= nint; return v; } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::LoadVector(FEGlobalVector& R, const FETimeInfo& tp) { m_psurf->LoadVector(R, m_dofC, false, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, vector<double>& fa) { FESurfaceElement& el = *mp.SurfaceElement(); // get the diffusivity FEElement* pe = el.m_elem[0]; FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm); double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp); // tangent vectors vec3d rt[FEElement::MAX_NODES]; m_psurf->GetNodalCoordinates(el, tp.alphaf, rt); vec3d dxr = el.eval_deriv1(rt, mp.m_index); vec3d dxs = el.eval_deriv2(rt, mp.m_index); // normal and area element vec3d n = dxr ^ dxs; //double da = n.unit(); // fluid velocity vec3d v = FluidVelocity(mp, tp.alphaf); double c = EffectiveConcentration(mp, tp.alphaf); //vec3d v = FluidVelocityElm(mp); //double c = EffectiveConcentrationElm(mp); vec3d gradc = EffectiveCGrad(mp); // force vector (change sign for inflow vs outflow) double f = n*(-gradc*d0+v*c)*(m_beta); double H = dof_a.shape; fa[0] = H * f; }); }
11,561
4,190
//EInstruction.cpp // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // Copyright (c) Querysoft Limited 2012 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Implement an x86 instruction emittable #include "ArchQOR.h" #if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 ) #include "ArchQOR/x86/HLAssembler/Emittables/EInstruction.h" #include "ArchQOR/x86/HLAssembler/x86HLAContext.h" #include <assert.h> //------------------------------------------------------------------------------ namespace nsArch { //------------------------------------------------------------------------------ namespace nsx86 { //------------------------------------------------------------------------------ CEInstruction::CEInstruction( Cx86HLAIntrinsics* c, Cmp_unsigned__int32 code, COperand** operandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW : CEmittable( (nsArch::CHighLevelAssemblerBase*)c, EMITTABLE_INSTRUCTION ) { m_uiCode = code; m_uiEmitOptions = c->getEmitOptions(); c->setEmitOptions( 0 );// Each created instruction takes emit options and clears it. m_pOperands = operandsData; m_uiOperandsCount = operandsCount; m_pVariables = 0; m_uiVariablesCount = 0; m_pMemOp = 0; Cmp_unsigned__int32 i; for( i = 0; i < operandsCount; i++ ) { if( m_pOperands[ i ]->isMem() ) { m_pMemOp = dynamic_cast< CMem* >( m_pOperands[ i ] ); break; } } const InstructionDescription* id = &instructionDescription[ m_uiCode ]; m_bIsSpecial = id->isSpecial(); m_bIsFPU = id->isFPU(); m_bIsGPBLoUsed = false; m_bIsGPBHiUsed = false; if( m_bIsSpecial ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: // Special... break; case INST_CBW: case INST_CDQE: case INST_CWDE: // Special... break; case INST_CMPXCHG: case INST_CMPXCHG8B: # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: # endif // ASMJIT_X64 // Special... break; # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_DAA: case INST_DAS: // Special... break; # endif // case INST_IMUL: switch (operandsCount) { case 2: // IMUL dst, src is not special instruction. m_bIsSpecial = false; break; case 3: if( !( m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && m_pOperands[ 2 ]->isVarMem() ) ) { m_bIsSpecial = false; // Only IMUL dst_lo, dst_hi, reg/mem is special, all others not. } break; } break; case INST_MUL: case INST_IDIV: case INST_DIV: // Special... break; case INST_MOV_PTR: // Special... break; case INST_LAHF: case INST_SAHF: // Special... break; case INST_MASKMOVQ: case INST_MASKMOVDQU: // Special... break; case INST_ENTER: case INST_LEAVE: // Special... break; case INST_RET: // Special... break; case INST_MONITOR: case INST_MWAIT: // Special... break; case INST_POP: case INST_POPAD: case INST_POPFD: case INST_POPFQ: // Special... break; case INST_PUSH: case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // Special... break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: // Rot instruction is special only if last operand is variable (register). m_bIsSpecial = m_pOperands[ 1 ]->isVar(); break; case INST_SHLD: case INST_SHRD: // Shld/Shrd instruction is special only if last operand is variable (register). m_bIsSpecial = m_pOperands[ 2 ]->isVar(); break; case INST_RDTSC: case INST_RDTSCP: // Special... break; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: // Special... break; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } } //------------------------------------------------------------------------------ CEInstruction::~CEInstruction() __QCMP_THROW { } //------------------------------------------------------------------------------ void CEInstruction::getVariable( VarData* _candidate, VarAllocRecord*& cur, VarAllocRecord*& var ) { for( var = cur; ;) { if( var == m_pVariables ) { var = cur++; var->vdata = _candidate; var->vflags = 0; var->regMask = 0xFFFFFFFF; break; } var--; if( var->vdata == _candidate ) { break; } } assert( var != 0 ); } //------------------------------------------------------------------------------ void CEInstruction::prepare( CHLAssemblerContextBase& hlac ) __QCMP_THROW { Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac ); /* # define __GET_VARIABLE(__vardata__) \ { \ VarData* _candidate = __vardata__; \ \ for (var = cur; ;) \ { \ if (var == m_pVariables) \ { \ var = cur++; \ var->vdata = _candidate; \ var->vflags = 0; \ var->regMask = 0xFFFFFFFF; \ break; \ } \ \ var--; \ \ if (var->vdata == _candidate) \ { \ break; \ } \ } \ \ assert(var != 0); \ } */ m_uiOffset = cc.GetCurrentOffset(); const InstructionDescription* id = &instructionDescription[ m_uiCode ]; Cmp_unsigned__int32 i, len = m_uiOperandsCount; Cmp_unsigned__int32 variablesCount = 0; for( i = 0; i < len; i++ ) { COperand* o = m_pOperands[ i ]; if( o->isVar() ) { assert( o->getId() != INVALID_VALUE ); VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() ); assert( vdata != 0 ); CBaseVar* pVar = dynamic_cast< CBaseVar* >( o ); if( pVar && pVar->isGPVar() ) { if( pVar->isGPBLo() ) { m_bIsGPBLoUsed = true; vdata->registerGPBLoCount++; }; if( pVar->isGPBHi() ) { m_bIsGPBHiUsed = true; vdata->registerGPBHiCount++; }; } if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } else if( o->isMem() ) { CMem& m( dynamic_cast< CMem& >( *o ) ); if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() ); assert( vdata != 0 ); cc._markMemoryUsed( vdata ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() ); assert( vdata != 0 ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() ); assert( vdata != 0 ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } } } if( !variablesCount ) { cc.IncrementCurrentOffset(); return; } m_pVariables = reinterpret_cast< VarAllocRecord* >( ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->getZone().zalloc( sizeof( VarAllocRecord ) * variablesCount ) ); if( !m_pVariables ) { ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->setError( ERROR_NO_HEAP_MEMORY ); cc.IncrementCurrentOffset(); return; } m_uiVariablesCount = variablesCount; VarAllocRecord* cur = m_pVariables; VarAllocRecord* var = 0; bool _isGPBUsed = m_bIsGPBLoUsed || m_bIsGPBHiUsed; Cmp_unsigned__int32 gpRestrictMask = nsCodeQOR::maskUpToIndex( REG_NUM_GP ); # if ( QOR_ARCH_WORDSIZE == 64 ) if( m_bIsGPBHiUsed ) { gpRestrictMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBP ) | nsCodeQOR::maskFromIndex( REG_INDEX_ESI ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDI ) ; } # endif // ASMJIT_X64 for( i = 0; i < len; i++ ) { COperand* o = m_pOperands[ i ]; if( o->isVar() ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); var->vflags |= VARIABLE_ALLOC_REGISTER; CBaseVar* pVar = dynamic_cast< CBaseVar* >( o ); if( _isGPBUsed ) { CGPVar* pGPVar = dynamic_cast< CGPVar* >( pVar ); # if ( QOR_ARCH_WORDSIZE == 32 ) if( pGPVar->isGPB() ) { var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) ; } # else // Restrict all BYTE registers to RAX/RBX/RCX/RDX if HI BYTE register // is used (REX prefix makes HI BYTE addressing unencodable). if( m_bIsGPBHiUsed ) { if( pGPVar->isGPB() ) { var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); } } # endif // } if( isSpecial() ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; case 3: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_CBW: case INST_CDQE: case INST_CWDE: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_CMPXCHG: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; default: assert( 0 ); } break; case INST_CMPXCHG8B: # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: # endif // ASMJIT_X64 switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; case 3: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; # if ( QOR_ARCH_WORDSIZE == 32 ) case INST_DAA: case INST_DAS: assert( i == 0 ); vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; # endif // ( QOR_ARCH_WORDSIZE == 32 ) case INST_IMUL: case INST_MUL: case INST_IDIV: case INST_DIV: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; default: assert( 0 ); } break; case INST_MOV_PTR: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_LAHF: assert( i == 0 ); vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case INST_SAHF: assert( i == 0 ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case INST_MASKMOVQ: case INST_MASKMOVDQU: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; } break; case INST_ENTER: case INST_LEAVE: // TODO: SPECIAL INSTRUCTION. break; case INST_RET: // TODO: SPECIAL INSTRUCTION. break; case INST_MONITOR: case INST_MWAIT: // TODO: MONITOR/MWAIT (COMPILER). break; case INST_POP: // TODO: SPECIAL INSTRUCTION. break; case INST_POPAD: case INST_POPFD: case INST_POPFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSH: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_SHLD: case INST_SHRD: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_RDTSC: case INST_RDTSCP: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: assert( m_uiCode == INST_RDTSCP ); vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } else { if( i == 0 ) { // CMP/TEST instruction. if( id->code == INST_CMP || id->code == INST_TEST ) { // Read-only case. vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; } // CVTTSD2SI/CVTTSS2SI instructions. else if( id->code == INST_CVTTSD2SI || id->code == INST_CVTTSS2SI ) { // In 32-bit mode the whole destination is replaced. In 64-bit mode // we need to check whether the destination operand size is 64-bits. #if ( QOR_ARCH_WORDSIZE == 64 ) if (m_pOperands[0]->isRegType(REG_TYPE_GPQ)) { #endif // X64 // Write-only case. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; #if ( QOR_ARCH_WORDSIZE == 64 ) } else { // Read/Write. vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; } #endif // ASMJIT_X64 } // MOV/MOVSS/MOVSD instructions. // // If instruction is MOV (source replaces the destination) or // MOVSS/MOVSD and source operand is memory location then register // allocator should know that previous destination value is lost // (write only operation). else if( ( id->isMov()) || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) /* && _operands[1].isMem() */ ) || ( id->code == INST_IMUL && m_uiOperandsCount == 3 && !isSpecial() ) ) { // Write-only case. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; } else if( id->code == INST_LEA ) { // Write. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; } else { // Read/Write. vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; } } else { // Second, third, ... operands are read-only. vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; } if( !m_pMemOp && i < 2 && ( id->oflags[ i ] & InstructionDescription::O_MEM ) != 0 ) { var->vflags |= VARIABLE_ALLOC_MEMORY; } } // If variable must be in specific register we could add some hint to allocator. if( var->vflags & VARIABLE_ALLOC_SPECIAL ) { vdata->prefRegisterMask |= nsCodeQOR::maskFromIndex( var->regMask ); cc._newRegisterHomeIndex( vdata, nsCodeQOR::findFirstBit( var->regMask ) ); } } else if( o->isMem() ) { CMem& m( dynamic_cast< CMem& >( *o ) ); if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); if( i == 0 ) { // If variable is MOV instruction type (source replaces the destination) // or variable is MOVSS/MOVSD instruction then register allocator should // know that previous destination value is lost (write only operation). if( id->isMov() || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) ) ) { // Write only case. vdata->memoryWriteCount++; } else { vdata->memoryRWCount++; } } else { vdata->memoryReadCount++; } } else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ; var->regMask &= gpRestrictMask; } if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ; var->regMask &= gpRestrictMask; } } } // Traverse all variables and update firstEmittable / lastEmittable. This // function is called from iterator that scans emittables using forward // direction so we can use this knowledge to optimize the process. // Similar to ECall::prepare(). for( i = 0; i < m_uiVariablesCount; i++ ) { VarData* v = m_pVariables[ i ].vdata; // Update GP register allocator restrictions. if( isVariableInteger( v->type ) ) { if( m_pVariables[ i ].regMask == 0xFFFFFFFF ) { m_pVariables[ i ].regMask &= gpRestrictMask; } } // Update first/last emittable (begin of variable scope). if( v->firstEmittable == 0 ) { v->firstEmittable = this; } v->lastEmittable = this; } // There are some instructions that can be used to clear register or to set // register to some value (ideal case is all zeros or all ones). // // xor/pxor reg, reg ; Set all bits in reg to 0. // sub/psub reg, reg ; Set all bits in reg to 0. // andn reg, reg ; Set all bits in reg to 0. // pcmpgt reg, reg ; Set all bits in reg to 0. // pcmpeq reg, reg ; Set all bits in reg to 1. if( m_uiVariablesCount == 1 && m_uiOperandsCount > 1 && m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && !m_pMemOp ) { switch( m_uiCode ) { // XOR Instructions. case INST_XOR: case INST_XORPD: case INST_XORPS: case INST_PXOR: // ANDN Instructions. case INST_PANDN: // SUB Instructions. case INST_SUB: case INST_PSUBB: case INST_PSUBW: case INST_PSUBD: case INST_PSUBQ: case INST_PSUBSB: case INST_PSUBSW: case INST_PSUBUSB: case INST_PSUBUSW: // PCMPEQ Instructions. case INST_PCMPEQB: case INST_PCMPEQW: case INST_PCMPEQD: case INST_PCMPEQQ: // PCMPGT Instructions. case INST_PCMPGTB: case INST_PCMPGTW: case INST_PCMPGTD: case INST_PCMPGTQ: // Clear the read flag. This prevents variable alloc/spill. m_pVariables[ 0 ].vflags = VARIABLE_ALLOC_WRITE; m_pVariables[ 0 ].vdata->registerReadCount--; break; } } cc.IncrementCurrentOffset(); //# undef __GET_VARIABLE } //------------------------------------------------------------------------------ nsArch::CEmittable* CEInstruction::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW { Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac ); Cmp_unsigned__int32 i; Cmp_unsigned__int32 variablesCount = m_uiVariablesCount; if( variablesCount > 0 ) { // These variables are used by the instruction and we set current offset // to their work offsets -> getSpillCandidate never return the variable // used this instruction. for( i = 0; i < variablesCount; i++ ) { m_pVariables->vdata->workOffset = cc.GetCurrentOffset(); } // Alloc variables used by the instruction (special first). for( i = 0; i < variablesCount; i++ ) { VarAllocRecord& r = m_pVariables[ i ]; // Alloc variables with specific register first. if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) != 0 ) { cc.allocVar( r.vdata, r.regMask, r.vflags ); } } for( i = 0; i < variablesCount; i++ ) { VarAllocRecord& r = m_pVariables[ i ]; // Alloc variables without specific register last. if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) == 0 ) { cc.allocVar( r.vdata, r.regMask, r.vflags ); } } cc.translateOperands( m_pOperands, m_uiOperandsCount ); } if( m_pMemOp && ( m_pMemOp->getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m_pMemOp->getId() ); assert( vdata != 0 ); switch( vdata->state ) { case VARIABLE_STATE_UNUSED: vdata->state = VARIABLE_STATE_MEMORY; break; case VARIABLE_STATE_REGISTER: vdata->changed = false; cc.unuseVar( vdata, VARIABLE_STATE_MEMORY ); break; } } for( i = 0; i < variablesCount; i++ ) { cc._unuseVarOnEndOfScope( this, &m_pVariables[ i ] ); } return translated(); } //------------------------------------------------------------------------------ void CEInstruction::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW { CCPU* pAssembler = dynamic_cast< CCPU* >( ( dynamic_cast< Cx86HLAIntrinsics& >( ab ) ).getAssembler() ); pAssembler->SetComment( m_szComment ); pAssembler->SetEmitOptions( m_uiEmitOptions ); if( isSpecial() ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: pAssembler->_emitInstruction( m_uiCode ); return; case INST_CBW: case INST_CDQE: case INST_CWDE: pAssembler->_emitInstruction( m_uiCode ); return; case INST_CMPXCHG: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] ); return; case INST_CMPXCHG8B: #if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: #endif // ASMJIT_X64 pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 4 ] ); return; #if ( QOR_ARCH_WORDSIZE == 64 ) case INST_DAA: case INST_DAS: pAssembler->_emitInstruction( m_uiCode ); return; #endif // case INST_IMUL: case INST_MUL: case INST_IDIV: case INST_DIV: // INST dst_lo (implicit), dst_hi (implicit), src (explicit) assert( m_uiOperandsCount == 3 ); pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 2 ] ); return; case INST_MOV_PTR: break; case INST_LAHF: case INST_SAHF: pAssembler->_emitInstruction( m_uiCode ); return; case INST_MASKMOVQ: case INST_MASKMOVDQU: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] ); return; case INST_ENTER: case INST_LEAVE: // TODO: SPECIAL INSTRUCTION. break; case INST_RET: // TODO: SPECIAL INSTRUCTION. break; case INST_MONITOR: case INST_MWAIT: // TODO: MONITOR/MWAIT (COMPILER). break; case INST_POP: case INST_POPAD: case INST_POPFD: case INST_POPFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSH: case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], &Cx86CPUCore::cl ); return; case INST_SHLD: case INST_SHRD: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], &Cx86CPUCore::cl ); return; case INST_RDTSC: case INST_RDTSCP: pAssembler->_emitInstruction( m_uiCode ); return; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: pAssembler->_emitInstruction( m_uiCode ); return; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } switch( m_uiOperandsCount ) { case 0: pAssembler->_emitInstruction( m_uiCode ); break; case 1: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ] ); break; case 2: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ] ); break; case 3: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], m_pOperands[ 2 ] ); break; default: assert( 0 ); break; } } //------------------------------------------------------------------------------ int CEInstruction::getMaxSize() const __QCMP_THROW { // TODO: Do something more exact. return 15; } //------------------------------------------------------------------------------ bool CEInstruction::tryUnuseVar( nsArch::CommonVarData* vdata ) __QCMP_THROW { VarData* v = reinterpret_cast< VarData* >( vdata ); for( Cmp_unsigned__int32 i = 0; i < m_uiVariablesCount; i++ ) { if( m_pVariables[ i ].vdata == v ) { m_pVariables[ i ].vflags |= VARIABLE_ALLOC_UNUSE_AFTER_USE; return true; } } return false; } //------------------------------------------------------------------------------ CETarget* CEInstruction::getJumpTarget() const __QCMP_THROW { return 0; } }//nsx86 }//nsArch #endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
38,680
20,301
/* Copyright (c) 2014-2015 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__ #define __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__ #include "cassandra.h" #include "iterator.hpp" #include "value.hpp" #include "serialization.hpp" namespace cass { class CollectionIterator : public Iterator { public: CollectionIterator(const Value* collection) : Iterator(CASS_ITERATOR_TYPE_COLLECTION) , collection_(collection) , position_(collection->buffer().data()) , index_(-1) , count_(collection_->type() == CASS_VALUE_TYPE_MAP ? (2 * collection_->count()) : collection->count()) {} virtual bool next(); const Value* value() { assert(index_ >= 0 && index_ < count_); return &value_; } private: char* decode_value(char* position); private: const Value* collection_; char* position_; Value value_; int32_t index_; const int32_t count_; }; } // namespace cass #endif
1,507
491
#include "ring_buffer.h" RingBuffer::RingBuffer() { for (uint8_t i = 0; i < N; i++) { _aucBuffer[i] = 0; } clear(); } void RingBuffer::store_char( uint8_t c ) { int i = nextIndex(_iHead); if ( i != _iTail ) { _aucBuffer[_iHead] = c ; _iHead = i ; } } void RingBuffer::clear() { _iHead = 0; _iTail = 0; } int RingBuffer::read_char() { if(_iTail == _iHead) return -1; uint8_t value = _aucBuffer[_iTail]; _iTail = nextIndex(_iTail); return value; } int RingBuffer::available() { int delta = _iHead - _iTail; if(delta < 0) return N + delta; else return delta; } int RingBuffer::availableForStore() { if (_iHead >= _iTail) return N - 1 - _iHead + _iTail; else return _iTail - _iHead - 1; } int RingBuffer::peek() { if(_iTail == _iHead) return -1; return _aucBuffer[_iTail]; } int RingBuffer::nextIndex(int index) { return (uint32_t)(index + 1) % N; } bool RingBuffer::isFull() { return (nextIndex(_iHead) == _iTail); }
1,016
451
// Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include <jsUnits/jsEnergy.h> #include <jsUnits/jsUnitClass.h> #include <Units/Energy.h> #include "jsMomentOfForce.h" #include "jsRotationalStiffness.h" using namespace DNVS::MoFa::Units; Runtime::DynamicPhenomenon jsEnergy::GetPhenomenon() { return EnergyPhenomenon(); } void jsEnergy::init(jsTypeLibrary& typeLibrary) { jsUnitClass<jsEnergy,Energy> cls(typeLibrary); if(cls.reinit()) return; cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsMomentOfForce>); cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsRotationalStiffness>); cls.ImplicitConstructorConversion([](const jsEnergy& val) {return MomentOfForce(val); }); cls.ImplicitConstructorConversion([](const jsEnergy& val) {return RotationalStiffness(val); }); }
1,035
390
// Copyright 2008-2014 Simon Ekström #include "Common.h" #include "FileStream.h" namespace sb { FileStream::FileStream(const File& file) : _file(file) { Assert(_file.IsOpen()); } FileStream::~FileStream() { _file.Close(); } size_t FileStream::Read(void* dst, size_t size) { return _file.Read(dst, (uint32_t)size); } size_t FileStream::Write(const void* src, size_t size) { return _file.Write(src, (uint32_t)size); } int64_t FileStream::Seek(int64_t offset) { return _file.Seek(offset, File::SEEK_ORIGIN_BEGIN); } int64_t FileStream::Tell() const { return _file.Tell(); } int64_t FileStream::Length() const { return _file.Length(); } } // namespace sb
697
313
#include <openssl/bn.h> #include "NtpRsk.h" #include <openssl/rand.h> #include <iostream> /** * A is signature, X is the signed message hash * A^e = X * * e is the RSA exponent, typically 2^16 + 1 * * The proof is d where 1 < d < e (typically 2^16) * * r is a random number, then: * * (A^d *r)^e = X^d * (r^e) mod n * t T * * * (A^d1 *r)^e = X^d1 * (r^e) mod n * (A^d2 *r)^e = X^d2 * (r^e) mod n * (A^d3 *r)^e = X^d3 * (r^e) mod n * (A^d4 *r)^e = X^d4 * (r^e) mod n * (A^d5 *r)^e = X^d5 * (r^e) mod n * * what is published is T = (r^e) * t1 = (A^d1 *r) * t2 = (A^d2 *r) * t3 = (A^d3 *r) * t4 = (A^d4 *r) * t5 = (A^d5 *r) * */ NtpRskSignatureVerificationObject* NtpRsk::signWithNtpRsk(NtpRskSignatureRequestObject *ntpRskSignatureRequestObject) { NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject = new NtpRskSignatureVerificationObject(); const BIGNUM* n = ntpRskSignatureRequestObject->getN(); const BIGNUM* e = ntpRskSignatureRequestObject->getE(); BIGNUM* e2 = BN_new(); BIGNUM* sub = BN_new(); BIGNUM* add = BN_new(); BN_dec2bn(&add, "2"); BN_dec2bn(&sub, "4"); BN_sub(e2, e, sub); BIGNUM* signature = ntpRskSignatureRequestObject->getSignature(); BIGNUM* nm = ntpRskSignatureRequestObject->getNm(); BN_CTX *ctx = BN_CTX_new(); BIGNUM* r = randomBignum(n); BIGNUM* d = BN_new(); BN_mod(d, nm, e2, ctx); BN_add(d, d, add); BIGNUM* t1 = BN_new(); BIGNUM* T = BN_new(); BIGNUM* salt = BN_new(); std::cout << "d1 : " << BN_bn2dec(d) << std::endl; std::cout << "e : " << BN_bn2dec(e) << std::endl; std::cout << "n : " << BN_bn2dec(n) << std::endl; // T = r^v BN_mod_exp(T, r, e, n, ctx); ntpRskSignatureVerificationObject->setT(T); std::cout << "T : " << BN_bn2dec(T) << std::endl; // t1 = (A^d *r) BN_mod_exp(t1, signature, d, n, ctx); BN_mod_mul(t1, t1, r, n, ctx); ntpRskSignatureVerificationObject->setT1(t1); // t2 = (A^d *r) BIGNUM* t2 = BN_new(); BIGNUM* XT = BN_new(); BN_mod_exp(XT, t1, e, n, ctx); BN_dec2bn(&salt, "1618446177786864861468428776289946168463"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t2, signature, d, n, ctx); BN_mod_mul(t2, t2, r, n, ctx); ntpRskSignatureVerificationObject->setT2(t2); // t3 = (A^d *r) BIGNUM* t3 = BN_new(); BN_mod_exp(XT, t2, e, n, ctx); BN_dec2bn(&salt, "2468284666624768462658468131846646451821"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t3, signature, d, n, ctx); BN_mod_mul(t3, t3, r, n, ctx); ntpRskSignatureVerificationObject->setT3(t3); // t4 = (A^d *r) BIGNUM* t4 = BN_new(); BN_mod_exp(XT, t3, e, n, ctx); BN_dec2bn(&salt, "386846284626847646244761844687764462164"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t4, signature, d, n, ctx); BN_mod_mul(t4, t4, r, n, ctx); ntpRskSignatureVerificationObject->setT4(t4); // t5 = (A^d *r) BIGNUM* t5 = BN_new(); BN_mod_exp(XT, t4, e, n, ctx); BN_dec2bn(&salt, "456156843515512741515122247552415322464"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t5, signature, d, n, ctx); BN_mod_mul(t5, t5, r, n, ctx); ntpRskSignatureVerificationObject->setT5(t5); ntpRskSignatureVerificationObject->setPaddedM(ntpRskSignatureRequestObject->getPaddedM()); ntpRskSignatureVerificationObject->setM(ntpRskSignatureRequestObject->getM()); ntpRskSignatureVerificationObject->setNm(ntpRskSignatureRequestObject->getNm()); ntpRskSignatureVerificationObject->setE(ntpRskSignatureRequestObject->getE()); ntpRskSignatureVerificationObject->setN(ntpRskSignatureRequestObject->getN()); ntpRskSignatureVerificationObject->setMdAlg(ntpRskSignatureRequestObject->getMdAlg()); ntpRskSignatureVerificationObject->setSignedPayload(ntpRskSignatureRequestObject->getSignedPayload()); return ntpRskSignatureVerificationObject; } bool NtpRsk::verifyNtpRsk(NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject) { BIGNUM* T = ntpRskSignatureVerificationObject->getT(); BIGNUM* t1 = ntpRskSignatureVerificationObject->getT1(); BIGNUM* t2 = ntpRskSignatureVerificationObject->getT2(); BIGNUM* t3 = ntpRskSignatureVerificationObject->getT3(); BIGNUM* t4 = ntpRskSignatureVerificationObject->getT4(); BIGNUM* t5 = ntpRskSignatureVerificationObject->getT5(); const BIGNUM* e = ntpRskSignatureVerificationObject->getE(); BIGNUM* e2 = BN_new(); BIGNUM* sub = BN_new(); BIGNUM* add = BN_new(); BN_dec2bn(&add, "2"); BN_dec2bn(&sub, "4"); BN_sub(e2, e, sub); const BIGNUM* n = ntpRskSignatureVerificationObject->getN(); BIGNUM* m = ntpRskSignatureVerificationObject->getPaddedM(); BIGNUM* nm = ntpRskSignatureVerificationObject->getNm(); BN_CTX *ctx = BN_CTX_new(); // verify t^v = X^d * T mod n BIGNUM* XT = BN_new(); BIGNUM* salt = BN_new(); BIGNUM* d = BN_new(); BN_mod(d, nm, e2, ctx); BN_add(d, d, add); BN_mod_exp(t1, t1, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t1) != 0) { std::cout << "d1 : " << BN_bn2dec(d) << std::endl; std::cout << "e1 : " << BN_bn2dec(e) << std::endl; std::cout << "n1 : " << BN_bn2dec(n) << std::endl; std::cout << "T1 : " << BN_bn2dec(T) << std::endl; std::cout << "BN_cmp(XT, t1) failed" << std::endl; std::cout << "XT " << BN_bn2dec(XT) << std::endl; std::cout << "t1 " << BN_bn2dec(t1) << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "1618446177786864861468428776289946168463"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t2, t2, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t2) != 0) { std::cout << "BN_cmp(XT, t2) failed"; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "2468284666624768462658468131846646451821"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t3, t3, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t3) != 0) { std::cout << "BN_cmp(XT, t3) failed" << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "386846284626847646244761844687764462164"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t4, t4, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t4) != 0) { std::cout << "BN_cmp(XT, t4) failed" << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "456156843515512741515122247552415322464"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t5, t5, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t5) != 0) { std::cout << "BN_cmp(XT, t5) failed" << std::endl; BN_CTX_free(ctx); return false; } BN_CTX_free(ctx); return true; } BIGNUM* NtpRsk::randomBignum(const BIGNUM* maxSize) { int byteLength = BN_num_bytes(maxSize); unsigned char buf[byteLength]; RAND_bytes(buf, byteLength); return BN_bin2bn(buf, byteLength, NULL); }
7,764
3,785
/*! * \file CCGNSMeshReaderFVM.hpp * \brief Header file for the class CCGNSMeshReaderFVM. * The implementations are in the <i>CCGNSMeshReaderFVM.cpp</i> file. * \author T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 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. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #ifdef HAVE_CGNS #include "cgnslib.h" #endif #include "CMeshReaderFVM.hpp" /*! * \class CCGNSMeshReaderFVM * \brief Reads a CGNS zone into linear partitions for the finite volume solver (FVM). * \author: T. Economon */ class CCGNSMeshReaderFVM: public CMeshReaderFVM { private: #ifdef HAVE_CGNS int cgnsFileID; /*!< \brief CGNS file identifier. */ int cgnsBase; /*!< \brief CGNS database index. */ int cgnsZone; /*!< \brief CGNS zone index. */ int nZones; /*!< \brief Total number of zones in the CGNS file. */ int nSections; /*!< \brief Total number of sections in the CGNS file. */ vector<bool> isInterior; /*!< \brief Vector of booleans to store whether each section in the CGNS file is an interior or boundary section. */ vector<unsigned long> nElems; /*!< \brief Vector containing the local number of elements found within each CGNS section. */ vector<unsigned long> elemOffset; /*!< \brief Global ID offset for each interior section (i.e., the total number of global elements that came before it). */ vector<vector<cgsize_t> > connElems; /*!< \brief Vector containing the local element connectivity found within each CGNS section. First index is the section, second contains the connectivity in format [globalID VTK n1 n2 n3 n4 n5 n6 n7 n8] for each element. */ vector<vector<char> > sectionNames; /*!< \brief Vector for storing the names of each boundary section (marker). */ /*! * \brief Open the CGNS file and checks for errors. * \param[in] val_filename - string name of the CGNS file to be read. */ void OpenCGNSFile(string val_filename); /*! * \brief Reads all CGNS database metadata and checks for errors. */ void ReadCGNSDatabaseMetadata(); /*! * \brief Reads all CGNS zone metadata and checks for errors. */ void ReadCGNSZoneMetadata(); /*! * \brief Reads the grid points from a CGNS zone into linear partitions across all ranks. */ void ReadCGNSPointCoordinates(); /*! * \brief Reads the metadata for each CGNS section in a zone and collect information, including the size and whether it is an interior or boundary section. */ void ReadCGNSSectionMetadata(); /*! * \brief Reads the interior volume elements from one section of a CGNS zone into linear partitions across all ranks. * \param[in] val_section - CGNS section index. */ void ReadCGNSVolumeSection(int val_section); /*! * \brief Reads the surface (boundary) elements from the CGNS zone. Only the master rank currently reads and stores the connectivity, which is linearly partitioned later. * \param[in] val_section - CGNS section index. */ void ReadCGNSSurfaceSection(int val_section); /*! * \brief Reformats the CGNS volume connectivity from file into the standard base class data structures. */ void ReformatCGNSVolumeConnectivity(); /*! * \brief Reformats the CGNS volume connectivity from file into the standard base class data structures. */ void ReformatCGNSSurfaceConnectivity(); /*! * \brief Get the VTK type and string name for a CGNS element type. * \param[in] val_elem_type - CGNS element type. * \param[out] val_vtk_type - VTK type identifier index. * \returns String containing the name of the element type. */ string GetCGNSElementType(ElementType_t val_elem_type, int &val_vtk_type); #endif /*! * \brief Routine to launch non-blocking sends and recvs amongst all processors. * \param[in] bufSend - Buffer of data to be sent. * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage format. * \param[in] sendReq - Array of MPI send requests. * \param[in] bufRecv - Buffer of data to be received. * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative storage format. * \param[in] sendReq - Array of MPI recv requests. * \param[in] countPerElem - Pieces of data per element communicated. */ void InitiateCommsAll(void *bufSend, const int *nElemSend, SU2_MPI::Request *sendReq, void *bufRecv, const int *nElemRecv, SU2_MPI::Request *recvReq, unsigned short countPerElem, unsigned short commType); /*! * \brief Routine to complete the set of non-blocking communications launched with InitiateComms() with MPI_Waitany(). * \param[in] nSends - Number of sends to be completed. * \param[in] sendReq - Array of MPI send requests. * \param[in] nRecvs - Number of receives to be completed. * \param[in] sendReq - Array of MPI recv requests. */ void CompleteCommsAll(int nSends, SU2_MPI::Request *sendReq, int nRecvs, SU2_MPI::Request *recvReq); public: /*! * \brief Constructor of the CCGNSMeshReaderFVM class. */ CCGNSMeshReaderFVM(CConfig *val_config, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Destructor of the CCGNSMeshReaderFVM class. */ ~CCGNSMeshReaderFVM(void); };
6,418
2,000
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/color/color_recipe.h" #include <utility> #include "base/logging.h" #include "ui/color/color_mixer.h" #include "ui/color/color_provider_utils.h" namespace ui { ColorRecipe::ColorRecipe() = default; ColorRecipe::ColorRecipe(const ColorTransform& transform) { *this += transform; } ColorRecipe::ColorRecipe(const ColorRecipe&) = default; ColorRecipe& ColorRecipe::operator=(const ColorRecipe&) = default; ColorRecipe::ColorRecipe(ColorRecipe&&) noexcept = default; ColorRecipe& ColorRecipe::operator=(ColorRecipe&&) noexcept = default; ColorRecipe::~ColorRecipe() = default; ColorRecipe& ColorRecipe::operator+=(const ColorTransform& transform) { transforms_.push_back(transform); return *this; } SkColor ColorRecipe::GenerateResult(SkColor input, const ColorMixer& mixer) const { SkColor output_color = input; for (const auto& transform : transforms_) output_color = transform.Run(output_color, mixer); DVLOG(2) << "ColorRecipe::GenerateResult: InputColor: " << SkColorName(input) << " Result: " << SkColorName(output_color); return output_color; } ColorRecipe operator+(ColorRecipe recipe, const ColorTransform& transform) { recipe += transform; return recipe; } } // namespace ui
1,442
462
#include <showtime/ShowtimeClient.h> #include <showtime/ShowtimeServer.h> #include <showtime/ZstLogging.h> #include <signal.h> using namespace showtime; int s_interrupted = 0; typedef void (*SignalHandlerPointer)(int); void s_signal_handler(int signal_value) { switch (signal_value) { case SIGINT: s_interrupted = 1; case SIGTERM: s_interrupted = 1; case SIGABRT: s_interrupted = 1; case SIGSEGV: s_interrupted = 1; signal(signal_value, SIG_DFL); raise(SIGABRT); default: break; } } void s_catch_signals() { #ifdef WIN32 SignalHandlerPointer previousHandler; previousHandler = signal(SIGSEGV, &s_signal_handler); #else struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset(&action.sa_mask); sigaction(SIGINT, &action, NULL); sigaction(SIGTERM, &action, NULL); sigaction(SIGSEGV, &action, NULL); #endif } class EchoMidi { public: EchoMidi() { m_server.init("EchoMidiServer"); m_client.init("EchoMidi", true); m_client.auto_join_by_name("EchoMidiServer"); ZstURI midi_factory_path = m_client.get_root()->URI() + ZstURI("midi_ports"); auto midi_factory = dynamic_cast<ZstEntityFactory*>(m_client.find_entity(midi_factory_path)); if (midi_factory) { ZstURIBundle bundle; midi_factory->get_creatables(&bundle); for (auto creatable : bundle) { m_client.create_entity(creatable, (std::string(creatable.last().path()) + "_echo").c_str()); } } } ~EchoMidi() { m_server.destroy(); m_client.destroy(); } ShowtimeClient& get_client() { return m_client; } ShowtimeServer& get_server() { return m_server; } private: ShowtimeClient m_client; ShowtimeServer m_server; }; int main(int argc, char** argv){ s_catch_signals(); EchoMidi echo; Log::app(Log::Level::notification, "Listening for midi events..."); while (!s_interrupted) echo.get_client().poll_once(); Log::app(Log::Level::notification, "Quitting"); echo.get_client().destroy(); echo.get_server().destroy(); return 0; }
2,009
824
/* * Copyright (C) 2020 Open Source Robotics Foundation * * 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 <map> #include <rmf_task/requests/Delivery.hpp> namespace rmf_task { namespace requests { //============================================================================== class Delivery::Model : public Task::Model { public: std::optional<Estimate> estimate_finish( const State& initial_state, const Constraints& task_planning_constraints, const TravelEstimator& travel_estimator) const final; rmf_traffic::Duration invariant_duration() const final; Model( const rmf_traffic::Time earliest_start_time, const Parameters& parameters, std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait); private: rmf_traffic::Time _earliest_start_time; Parameters _parameters; std::size_t _pickup_waypoint; std::size_t _dropoff_waypoint; rmf_traffic::Duration _invariant_duration; double _invariant_battery_drain; }; //============================================================================== Delivery::Model::Model( const rmf_traffic::Time earliest_start_time, const Parameters& parameters, std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait) : _earliest_start_time(earliest_start_time), _parameters(parameters), _pickup_waypoint(pickup_waypoint), _dropoff_waypoint(dropoff_waypoint) { // Calculate duration of invariant component of task _invariant_duration = pickup_wait + dropoff_wait; _invariant_battery_drain = _parameters.ambient_sink()->compute_change_in_charge( rmf_traffic::time::to_seconds(pickup_wait + dropoff_wait)); if (_pickup_waypoint != _dropoff_waypoint) { rmf_traffic::agv::Planner::Start start{ _earliest_start_time, _pickup_waypoint, 0.0}; rmf_traffic::agv::Planner::Goal goal{_dropoff_waypoint}; const auto result_to_dropoff = _parameters.planner()->plan(start, goal); auto itinerary_start_time = _earliest_start_time; for (const auto& itinerary : result_to_dropoff->get_itinerary()) { const auto& trajectory = itinerary.trajectory(); const auto& finish_time = *trajectory.finish_time(); const auto itinerary_duration = finish_time - itinerary_start_time; // Compute the invariant battery drain const double dSOC_motion = _parameters.motion_sink()->compute_change_in_charge(trajectory); const double dSOC_device = _parameters.ambient_sink()->compute_change_in_charge( rmf_traffic::time::to_seconds(itinerary_duration)); _invariant_battery_drain += dSOC_motion + dSOC_device; _invariant_duration += itinerary_duration; itinerary_start_time = finish_time; } } } //============================================================================== std::optional<rmf_task::Estimate> Delivery::Model::estimate_finish( const State& initial_state, const Constraints& task_planning_constraints, const TravelEstimator& travel_estimator) const { rmf_traffic::agv::Plan::Start final_plan_start{ initial_state.time().value(), _dropoff_waypoint, initial_state.orientation().value()}; auto state = State().load_basic( std::move(final_plan_start), initial_state.dedicated_charging_waypoint().value(), initial_state.battery_soc().value()); rmf_traffic::Duration variant_duration(0); double battery_soc = initial_state.battery_soc().value(); const bool drain_battery = task_planning_constraints.drain_battery(); const auto& ambient_sink = *_parameters.ambient_sink(); const double battery_threshold = task_planning_constraints.threshold_soc(); // Factor in battery drain while moving to start waypoint of task if (initial_state.waypoint() != _pickup_waypoint) { const auto travel = travel_estimator.estimate( initial_state.extract_plan_start().value(), _pickup_waypoint); if (!travel) return std::nullopt; variant_duration = travel->duration(); if (drain_battery) battery_soc = battery_soc - travel->change_in_charge(); if (battery_soc <= battery_threshold) return std::nullopt; } const rmf_traffic::Time ideal_start = _earliest_start_time - variant_duration; const rmf_traffic::Time wait_until = initial_state.time().value() > ideal_start ? initial_state.time().value() : ideal_start; // Factor in battery drain while waiting to move to start waypoint. If a robot // is initially at a charging waypoint, it is assumed to be continually charging if (drain_battery && wait_until > initial_state.time().value() && initial_state.waypoint() != initial_state.dedicated_charging_waypoint()) { const rmf_traffic::Duration wait_duration( wait_until - initial_state.time().value()); const double dSOC_device = ambient_sink.compute_change_in_charge( rmf_traffic::time::to_seconds(wait_duration)); battery_soc = battery_soc - dSOC_device; if (battery_soc <= battery_threshold) return std::nullopt; } // Factor in invariants state.time(wait_until + variant_duration + _invariant_duration); if (drain_battery) { // Calculate how much battery is drained while waiting for the pickup and // waiting for the dropoff battery_soc -= _invariant_battery_drain; if (battery_soc <= battery_threshold) return std::nullopt; // Check if the robot has enough charge to head back to nearest charger if (_dropoff_waypoint != state.dedicated_charging_waypoint().value()) { const auto travel = travel_estimator.estimate( state.extract_plan_start().value(), state.dedicated_charging_waypoint().value()); if (!travel.has_value()) return std::nullopt; if (battery_soc - travel->change_in_charge() <= battery_threshold) return std::nullopt; } state.battery_soc(battery_soc); } return Estimate(state, wait_until); } //============================================================================== rmf_traffic::Duration Delivery::Model::invariant_duration() const { return _invariant_duration; } //============================================================================== class Delivery::Description::Implementation { public: std::size_t pickup_waypoint; rmf_traffic::Duration pickup_wait; std::size_t dropoff_waypoint; rmf_traffic::Duration dropoff_wait; rmf_task::Payload payload; std::string pickup_from_dispenser; std::string dropoff_to_ingestor; }; //============================================================================== Task::ConstDescriptionPtr Delivery::Description::make( std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait, Payload payload, std::string pickup_from_dispenser, std::string dropoff_to_ingestor) { std::shared_ptr<Description> delivery(new Description()); delivery->_pimpl = rmf_utils::make_impl<Implementation>( Implementation{ pickup_waypoint, pickup_wait, dropoff_waypoint, dropoff_wait, std::move(payload), std::move(pickup_from_dispenser), std::move(dropoff_to_ingestor) }); return delivery; } //============================================================================== Delivery::Description::Description() { // Do nothing } //============================================================================== Task::ConstModelPtr Delivery::Description::make_model( rmf_traffic::Time earliest_start_time, const Parameters& parameters) const { return std::make_shared<Delivery::Model>( earliest_start_time, parameters, _pimpl->pickup_waypoint, _pimpl->pickup_wait, _pimpl->dropoff_waypoint, _pimpl->dropoff_wait); } //============================================================================== auto Delivery::Description::generate_info( const State&, const Parameters& parameters) const -> Info { const auto& graph = parameters.planner()->get_configuration().graph(); return Info{ "Delivery from " + standard_waypoint_name(graph, _pimpl->pickup_waypoint) + " to " + standard_waypoint_name(graph, _pimpl->dropoff_waypoint), "" // TODO(MXG): Add details about the payload }; } //============================================================================== std::size_t Delivery::Description::pickup_waypoint() const { return _pimpl->pickup_waypoint; } //============================================================================== std::string Delivery::Description::pickup_from_dispenser() const { return _pimpl->pickup_from_dispenser; } //============================================================================== std::string Delivery::Description::dropoff_to_ingestor() const { return _pimpl->dropoff_to_ingestor; } //============================================================================== rmf_traffic::Duration Delivery::Description::pickup_wait() const { return _pimpl->pickup_wait; } //============================================================================== rmf_traffic::Duration Delivery::Description::dropoff_wait() const { return _pimpl->dropoff_wait; } //============================================================================== std::size_t Delivery::Description::dropoff_waypoint() const { return _pimpl->dropoff_waypoint; } //============================================================================== const Payload& Delivery::Description::payload() const { return _pimpl->payload; } //============================================================================== ConstRequestPtr Delivery::make( std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait, Payload payload, const std::string& id, rmf_traffic::Time earliest_start_time, ConstPriorityPtr priority, bool automatic, std::string pickup_from_dispenser, std::string dropoff_to_ingestor) { const auto description = Description::make( pickup_waypoint, pickup_wait, dropoff_waypoint, dropoff_wait, std::move(payload), std::move(pickup_from_dispenser), std::move(dropoff_to_ingestor)); return std::make_shared<Request>( id, earliest_start_time, std::move(priority), description, automatic); } } // namespace requests } // namespace rmf_task
11,011
3,448
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2021, Max Wipfli <max.wipfli@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/LexicalPath.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <AK/Vector.h> namespace AK { char s_single_dot = '.'; LexicalPath::LexicalPath(String path) : m_string(canonicalized_path(move(path))) { if (m_string.is_empty()) { m_string = "."; m_dirname = m_string; m_basename = {}; m_title = {}; m_extension = {}; m_parts.clear(); return; } m_parts = m_string.split_view('/'); auto last_slash_index = m_string.view().find_last('/'); if (!last_slash_index.has_value()) { // The path contains a single part and is not absolute. m_dirname = "."sv m_dirname = { &s_single_dot, 1 }; } else if (*last_slash_index == 0) { // The path contains a single part and is absolute. m_dirname = "/"sv m_dirname = m_string.substring_view(0, 1); } else { m_dirname = m_string.substring_view(0, *last_slash_index); } if (m_string == "/") m_basename = m_string; else { VERIFY(m_parts.size() > 0); m_basename = m_parts.last(); } auto last_dot_index = m_basename.find_last('.'); // NOTE: if the dot index is 0, this means we have ".foo", it's not an extension, as the title would then be "". if (last_dot_index.has_value() && *last_dot_index != 0) { m_title = m_basename.substring_view(0, *last_dot_index); m_extension = m_basename.substring_view(*last_dot_index + 1); } else { m_title = m_basename; m_extension = {}; } } Vector<String> LexicalPath::parts() const { Vector<String> vector; vector.ensure_capacity(m_parts.size()); for (auto& part : m_parts) vector.unchecked_append(part); return vector; } bool LexicalPath::has_extension(StringView extension) const { return m_string.ends_with(extension, CaseSensitivity::CaseInsensitive); } String LexicalPath::canonicalized_path(String path) { if (path.is_null()) return {}; // NOTE: We never allow an empty m_string, if it's empty, we just set it to '.'. if (path.is_empty()) return "."; // NOTE: If there are no dots, no '//' and the path doesn't end with a slash, it is already canonical. if (!path.contains("."sv) && !path.contains("//"sv) && !path.ends_with('/')) return path; auto is_absolute = path[0] == '/'; auto parts = path.split_view('/'); size_t approximate_canonical_length = 0; Vector<String> canonical_parts; for (auto& part : parts) { if (part == ".") continue; if (part == "..") { if (canonical_parts.is_empty()) { if (is_absolute) { // At the root, .. does nothing. continue; } } else { if (canonical_parts.last() != "..") { // A .. and a previous non-.. part cancel each other. canonical_parts.take_last(); continue; } } } approximate_canonical_length += part.length() + 1; canonical_parts.append(part); } if (canonical_parts.is_empty() && !is_absolute) canonical_parts.append("."); StringBuilder builder(approximate_canonical_length); if (is_absolute) builder.append('/'); builder.join('/', canonical_parts); return builder.to_string(); } String LexicalPath::absolute_path(String dir_path, String target) { if (LexicalPath(target).is_absolute()) { return LexicalPath::canonicalized_path(target); } return LexicalPath::canonicalized_path(join(dir_path, target).string()); } String LexicalPath::relative_path(StringView a_path, StringView a_prefix) { if (!a_path.starts_with('/') || !a_prefix.starts_with('/')) { // FIXME: This should probably VERIFY or return an Optional<String>. return {}; } if (a_path == a_prefix) return "."; // NOTE: Strip optional trailing slashes, except if the full path is only "/". auto path = canonicalized_path(a_path); auto prefix = canonicalized_path(a_prefix); if (path == prefix) return "."; // NOTE: Handle this special case first. if (prefix == "/"sv) return path.substring_view(1); // NOTE: This means the prefix is a direct child of the path. if (path.starts_with(prefix) && path[prefix.length()] == '/') { return path.substring_view(prefix.length() + 1); } // FIXME: It's still possible to generate a relative path in this case, it just needs some "..". return path; } LexicalPath LexicalPath::append(StringView value) const { return LexicalPath::join(m_string, value); } LexicalPath LexicalPath::parent() const { return append(".."); } }
4,998
1,657
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int left_index = -2; int right_index = -2; //寻找左右边界 left_index = get_left(nums, target); right_index = get_right(nums, target); // 情况一 if (left_index == -2 || right_index == -2) return {-1, -1}; // 情况三 if (right_index - left_index > 1) return {left_index + 1, right_index - 1}; // 情况二 return {-1, -1}; } private: int get_left(vector<int> nums, int target) { int m_num = nums.size(); int left = 0; int right = m_num - 1; int mid = 0; int left_index = -2; while(left <= right) { mid = left + ((right - left) / 2); if(nums[mid] >= target) { right = mid - 1; left_index = right; } else { left = mid + 1; } } return left_index; } int get_right(vector<int> nums, int target) { int m_num = nums.size(); int left = 0; int right = m_num - 1; int mid = 0; int right_index = -2; while(left <= right) { mid = left + ((right - left) / 2); if(nums[mid] > target) { right = mid - 1; } else { left = mid + 1; right_index = left; } } return right_index; } };
1,555
518
#include "FixedTimeStepApp.h" #include "Texture.h" #include "Font.h" #include "Input.h" #include "PhysicsScene.h" #include "Sphere.h" #include "Plane.h" FixedTimeStepApp::FixedTimeStepApp() { } FixedTimeStepApp::~FixedTimeStepApp() { } bool FixedTimeStepApp::startup() { //Increase the 2d line count to maximize the number of objects we can draw aie::Gizmos::create(225U, 225U, 65535U, 65535U); m_2dRenderer = new aie::Renderer2D(); // TODO: remember to change this when redistributing a build! // the following path would be used instead: "./font/consolas.ttf" m_font = new aie::Font("../bin/font/consolas.ttf", 32); m_physicsScene = new PhysicsScene(); m_physicsScene->setGravity(glm::vec2(0, -50)); m_physicsScene->setTimeStep(0.01f); //Plane Plane* plane1 = new Plane(glm::vec2(-1 , 0), 70, glm::vec4(1, 0, 0,1)); Plane* plane2 = new Plane(glm::vec2(1, 0), 70, glm::vec4(1, 0, 0, 1)); Plane* plane3 = new Plane(glm::vec2(0, 1), 30, glm::vec4(1, 0, 0, 1)); Plane* plane4 = new Plane(glm::vec2(0, -1), 30, glm::vec4(1, 0, 0, 1)); m_physicsScene->addActor(plane1); m_physicsScene->addActor(plane2); m_physicsScene->addActor(plane3); m_physicsScene->addActor(plane4); //Crash balls Sphere* ball1 = new Sphere(glm::vec2(-40, 3), glm::vec2(100, 0), 3.0f, 5, glm::vec4(1, 0, 0, 1)); Sphere* ball2 = new Sphere(glm::vec2(40, -3), glm::vec2(-100, 0), 3.0f, 5, glm::vec4(0, 1, 0, 1)); m_physicsScene->addActor(ball1); m_physicsScene->addActor(ball2); ball1->applyForce(glm::vec2(50, 0), ball1->getPosition()); ball2->applyForce(glm::vec2(-45, 0), ball2->getPosition()); return true; } void FixedTimeStepApp::shutdown() { delete m_font; delete m_2dRenderer; } void FixedTimeStepApp::update(float deltaTime) { // input example aie::Input* input = aie::Input::getInstance(); aie::Gizmos::clear(); //Upadates physics m_physicsScene->update(deltaTime); m_physicsScene->updateGizmos(); // exit the application if (input->isKeyDown(aie::INPUT_KEY_ESCAPE)) quit(); } void FixedTimeStepApp::draw() { // wipe the screen to the background colour clearScreen(); // begin drawing sprites m_2dRenderer->begin(); // draw your stuff here! static float aspectRatio = 16 / 9.0f; aie::Gizmos::draw2D(glm::ortho<float>(-100, 100, -100 / aspectRatio, 100 / aspectRatio, -1.0f, 1.0f)); // output some text, uses the last used colour m_2dRenderer->drawText(m_font, "Press ESC to quit", 0, 0); // done drawing sprites m_2dRenderer->end(); }
2,493
1,125
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "data_map.h" #include "rest_handler.h" #include "Enclave_u.h" #include "mock_sawtooth.h" #include "config.h" #include "txn_handler.h" //declare the extern global std::string config::g_key_path; std::string config::g_rest_url; std::string addr1, addr2, addr3; namespace txn_handler { sawtooth::GlobalStateUPtr contextPtr; } using namespace listener; void set_sawtooth_mock() { std::unique_ptr<SawtoothStateMock> mock_ctx_uptr(new SawtoothStateMock); txn_handler::contextPtr = std::move(mock_ctx_uptr); } void SetUpListener() { set_sawtooth_mock(); std::array<uint8_t, ADDRESS_LENGTH / 2> addr_bytes = {}; std::iota(std::begin(addr_bytes), std::end(addr_bytes), 13); addr1 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); std::iota(std::begin(addr_bytes), std::end(addr_bytes), 25); addr2 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); std::iota(std::begin(addr_bytes), std::end(addr_bytes), 41); addr3 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); } TEST(Listener, tl_call_stl_write) { std::string str = "mock value in addr1"; ASSERT_EQ(tl_call_stl_write(addr1.c_str(), str.c_str(), str.size() + 1), 0); } TEST(Listener, tl_call_stl_read) { uint32_t id; std::vector<char> value = {}; std::string res_str = "mock value in addr1"; int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0); ASSERT_EQ(res_len, res_str.size() + 1); value.reserve(res_len); res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len); ASSERT_EQ(res_len, res_str.size() + 1); ASSERT_EQ(std::string(std::begin(value), std::begin(value) + res_len - 1), res_str.c_str()); // read again should return empty string res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len); ASSERT_EQ(res_len, 0); } TEST(Listener, tl_call_stl_delete) { ASSERT_EQ(tl_call_stl_delete(addr1.c_str(), 1), 0); uint32_t id; std::vector<char> value = {}; int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0); ASSERT_EQ(res_len, 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); SetUpListener(); auto ret = RUN_ALL_TESTS(); deleteAllValues(); return ret; }
2,324
962
/********************************************************************* * Copyright (c) 2016 nari * This source is released under the MIT license * http://opensource.org/licenses/mit-license.php * * This source code is a modification of article website below. * http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php * Cppyright (c) Walletfox.com, 2014 * *******************************************************************/ #include "mygraphicsscene.h" #include <QDebug> /* *refer to * How to draw QGraphicsLineItem during run time with mouse coordinates * http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php */ MyGraphicsScene::MyGraphicsScene(QObject* parent) { sceneMode = NoMode; itemToDraw = 0; } void MyGraphicsScene::setLineColor(QString colorname){ lineColor = colorname; } void MyGraphicsScene::clearDraw(){ //lineを消せない //itemToDraw->~QGraphicsLineItem(); if(freeLines.count() > 0){ for(int i = 0; i < freeLines.count() ; i++){ //freeLines.at(i)->setVisible(false); QGraphicsLineItem *item = freeLines.at(i); freeLines.removeAt(i); //これ必要 delete item; //freeLines.at(i)->~QGraphicsLineItem(); } } } void MyGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event){ if(sceneMode == DrawLine) origPoint = event->scenePos(); QGraphicsScene::mousePressEvent(event); } void MyGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event){ if(sceneMode == DrawLine){ if(!itemToDraw && origPoint.x() > 0 && origPoint.y() > 0){ itemToDraw = new QGraphicsLineItem; this->addItem(itemToDraw); freeLines.append(itemToDraw); QPen pen; pen.setColor(lineColor); pen.setWidth(3); pen.setStyle(Qt::SolidLine); itemToDraw->setPen(pen); itemToDraw->setPos(origPoint); } if(origPoint.x() > 0 && origPoint.y() > 0){ itemToDraw->setLine(0,0,event->scenePos().x() - origPoint.x(),event->scenePos().y() - origPoint.y()); } } else QGraphicsScene::mouseMoveEvent(event); } void MyGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ itemToDraw = 0; sceneMode = NoMode; QGraphicsScene::mouseReleaseEvent(event); } void MyGraphicsScene::setMode(Mode mode){ sceneMode = mode; itemToDraw = 0; } void MyGraphicsScene::setModeDraw(){ sceneMode = DrawLine; origPoint.setX(-1); origPoint.setY(-1); itemToDraw = 0; }
2,680
864
// // VectorContainer.cpp // Achoo // // Created by Saad K on 4/22/15. // Copyright (c) 2015 Saad K. All rights reserved. // #include "VectorContainer.h" using namespace std; /** * Innervector is private, and so a method is needed to return the last element of the vector **/ template <class T> T VectorContainer<T>::getBack(){ return innerVector->back(); } /** * Innervector is private, and so a method is needed to return the size of the vector **/ template <class T> int VectorContainer<T>::size(){ return innerVector->size(); } /** * Innervector is private, and so a method is needed to inser an object to the vector **/ template <class T> bool VectorContainer<T>::insert(T toAdd){ transform(toAdd->name.begin(),toAdd->name .end(), toAdd->name.begin(), ::tolower);//lowercase the addition innerVector->push_back(toAdd); return true; } /** * Innervector is private, and so a method is needed to return an object from the vector **/ template <class T> T VectorContainer<T>::get(int index){ if(index > size() || index < 0) return NULL; return (*innerVector)[index]; } /** * Complete search means that it compares the full user input with the full text in disease/symptom. * Used to search diseases **/ template <class T> T VectorContainer<T>::completeSearch(string toSearch){ transform(toSearch.begin(),toSearch.end(), toSearch.begin(), ::tolower);//lowercase the search for (auto s = innerVector->begin(); s != innerVector->end(); s++ ) {//go through each originalResult if((*s)->name == toSearch){ return (*s); } } return NULL; } /** * Initially goes through a disease vector and finds and matches to the users given symptom * Theoretically speaking I don't need the originalResults, the method is being called on originalResults; but I have to include it b/c of tempate<class T>. If this funtction was called on this (e.g object itself), the template prevents it from compiling b/c the template can work with Symptom and Disease and Symptom and Disease don't have certain instance variables such as searchValue **/ template <class T> VectorContainer<Search *> * VectorContainer<T>::initialSearchVector(VectorContainer<Disease *> * diseases, string toSearch){ //toSearch = formatString(toSearch); VectorContainer<Search *> * toReturn; toReturn = new VectorContainer<Search *>; transform(toSearch.begin(),toSearch.end(), toSearch.begin(), ::tolower);//lowercase the search vector<string> wordsInQuery = Utilities::split(toSearch, ' '); for (auto s = diseases->getBeginningIterator(); s != diseases->getEndingIterator(); s++ ) {//go through each originalResult Search * search; search = new Search; (*search).disease = (*s); (*search).searchValue = 0; for (int i = 0; i < wordsInQuery.size(); i++) { if(isValid(wordsInQuery[i])){ for (int z = 0; z < (*s)->symptoms.size(); z++) { double compareResult = (*s)->symptoms[z]->compare(wordsInQuery[i], wordsInQuery.size()); (*search).searchValue += compareResult; (*search).numElementInInput = i; if((toReturn)->size() > 0){ if((toReturn)->getBack()->numElementInInput == i - 1)//if the last element inserted (*search).searchValue++; } if(compareResult > 0) break; } } } if((*search).searchValue > 0){//only add the old result if it has the new symptom too (*toReturn).insert(search); }else{ delete search; } } return toReturn; } /** * Searches a vector containing search objects. Used to narrow down the search * Theoretically speaking I don't need the originalResults, the method is being called on originalResults; but I have to include it b/c of tempate<class T>. If this funtction was called on this (e.g object itself), the template prevents it from compiling b/c the template can work with Symptom and Disease and Symptom and Disease don't have certain instance variables such as searchValue **/ template <class T> VectorContainer<Search *> * VectorContainer<T>::searchSearchVector(VectorContainer<Search *> * originalResults, string newSymp){ VectorContainer<Search *> * toReturn; toReturn = new VectorContainer<Search *>; transform(newSymp.begin(),newSymp.end(), newSymp.begin(), ::tolower);//lowercase the search vector<string> wordsInQuery = Utilities::split(newSymp, ' '); for (auto s = originalResults->getBeginningIterator(); s != originalResults->getEndingIterator(); s++ ) {//go through each originalResult // //Users//Saad//Desktop//achoo//Scraper//diseases.txt Search * search; search = new Search; (*search).disease = (*s)->disease; (*search).searchValue = (*s)->searchValue; for (int i = 0; i < wordsInQuery.size(); i++) { if(isValid(wordsInQuery[i])){ for (int z = 0; z < (*s)->disease->symptoms.size(); z++) { double compareResult = (*s)->disease->symptoms[z]->compare(wordsInQuery[i], wordsInQuery.size()); (*search).searchValue += compareResult; (*search).numElementInInput = i; if((toReturn)->size() > 0){ if((toReturn)->getBack()->numElementInInput == i - 1)//if the last element inserted (*search).searchValue++; } if(compareResult > 0) break; } } } if((*search).searchValue > (*s)->searchValue){//only add the old result if it has the new symptom too (*toReturn).insert(search); }else{ delete search; } } delete originalResults; return toReturn; } /** * Checks if the @param input is valid or not * @pre-condition @param input must be 1 word * @return true if valid, false otherwise **/ template <class T> bool VectorContainer<T>::isValid(string input){ //checks user input for words to remove from search. string toRemove[] = {"i", "me", "a", "have", "had", "since", "days", "my", "am"}; for (string s : toRemove){ if(input == s) return false; } return true; } //returns the beginning iterator, needed to loop through vector and for sort/transform fucntions template <class T> typename vector<T>::iterator VectorContainer<T>::getBeginningIterator(){ return innerVector->begin(); } //returns the ending iterator, needed to loop through vector and for sort/transform fucntions template <class T> typename vector<T>::iterator VectorContainer<T>::getEndingIterator(){ return innerVector->end(); } //allow the VectorContainer to be used with Symptom *, Disease * and Search * template class VectorContainer<Symptom *>; template class VectorContainer<Disease *>; template class VectorContainer<Search *>;
7,236
2,022
// Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan // Licensed under the MIT License. See LICENSE for details. #include <algorithm> #include <cstring> #include <iostream> #include <limits> #include <stdexcept> #include "streams.hpp" namespace crab { CRAB_INLINE void IStream::read(uint8_t *val, size_t count) { while (count != 0) { size_t rc = read_some(val, count); if (rc == 0) throw std::runtime_error("crab::IStream reading from empty stream"); val += rc; count -= rc; } } CRAB_INLINE void OStream::write(const uint8_t *val, size_t count) { while (count != 0) { size_t wc = write_some(val, count); if (wc == 0) throw std::runtime_error("crab::OStream writing to full stream"); val += wc; count -= wc; } } CRAB_INLINE size_t Buffer::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, read_count()); std::memcpy(val, read_ptr(), rc); did_read(rc); return rc; } CRAB_INLINE size_t Buffer::write_some(const uint8_t *val, size_t count) { size_t rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); return rc; } CRAB_INLINE size_t Buffer::read_from(IStream &in) { size_t total_count = 0; while (true) { size_t wc = write_count(); if (wc == 0) break; size_t count = in.read_some(write_ptr(), wc); did_write(count); total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t Buffer::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(read_count(), max_count); if (rc == 0) break; size_t count = out.write_some(read_ptr(), rc); did_read(count); max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE bool Buffer::read_enough_data(IStream &in, size_t count) { if (size() < count) read_from(in); return size() >= count; } CRAB_INLINE bool Buffer::peek(uint8_t *val, size_t count) const { // Compiler thinks memcpy can affect "this", local vars greatly help auto rc = read_count(); auto rc2 = read_count2(); if (rc + rc2 < count) return false; auto rp = read_ptr(); if (rc >= count) { std::memcpy(val, rp, count); return true; } std::memcpy(val, rp, rc); std::memcpy(val + rc, read_ptr2(), count - rc); return true; } /* // Invariant - at least 1 chunk in rope container to avoid ifs Rope::Rope(size_t chunk_size) : chunk_size(chunk_size) { rope.emplace_back(chunk_size); } void Rope::clear() { if (rope.size() >= 1) { Buffer buf = std::move(rope.front()); rope.clear(); rope.push_back(std::move(buf)); } else { rope.clear(); rope.emplace_back(chunk_size); } rope_size = 0; } void Rope::did_write(size_t count) { rope_size += count; rope.back().did_write(count); if (rope.back().full()) rope.emplace_back(chunk_size); } void Rope::did_read(size_t count) { invariant(count <= rope_size, "Rope underflow"); rope_size -= count; rope.front().did_read(count); if (rope.front().empty()) { rope.pop_front(); if (rope.empty()) rope.emplace_back(chunk_size); } } size_t Rope::read_from(IStream &in) { size_t total_count = 0; while (true) { size_t wc = write_count(); if (wc == 0) break; size_t count = in.read_some(write_ptr(), wc); did_write(count); total_count += count; if (count == 0) break; } return total_count; } size_t Rope::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(read_count(), max_count); if (rc == 0) break; size_t count = out.write_some(read_ptr(), rc); did_read(count); max_count -= count; total_count += count; if (count == 0) break; } return total_count; }*/ /*void Buffer::write(const uint8_t *val, size_t count) { size_t rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); val += rc; count -= rc; if (count == 0) return; rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); val += rc; count -= rc; if (count == 0) return; throw std::runtime_error("Buffer overflow"); } void Buffer::write(const char *val, size_t count) { write(reinterpret_cast<const uint8_t *>(val), count); }*/ CRAB_INLINE size_t IMemoryStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, si); std::memcpy(val, data, rc); data += rc; si -= rc; return rc; } CRAB_INLINE size_t IMemoryStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(data, rc); data += count; si -= rc; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OMemoryStream::write_some(const uint8_t *val, size_t count) { size_t rc = std::min(count, si); std::memcpy(data, val, rc); data += rc; si -= rc; return rc; } CRAB_INLINE size_t IVectorStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, rimpl->size() - read_pos); std::memcpy(val, rimpl->data() + read_pos, rc); read_pos += rc; return rc; } CRAB_INLINE size_t IVectorStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(rimpl->data() + read_pos, rc); read_pos += count; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OVectorStream::write_some(const uint8_t *val, size_t count) { wimpl->insert(wimpl->end(), val, val + count); return count; } CRAB_INLINE size_t IStringStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, rimpl->size() - read_pos); std::memcpy(val, rimpl->data() + read_pos, rc); read_pos += rc; return rc; } CRAB_INLINE size_t IStringStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(rimpl->data() + read_pos, rc); read_pos += count; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OStringStream::write_some(const uint8_t *val, size_t count) { wimpl->insert(wimpl->end(), val, val + count); return count; } /* // Some experimental code // Inspirated by boost::streams class IStreamBuffer { static constexpr size_t SMALL_READ = 256; static constexpr size_t BUFFER_SIZE = SMALL_READ * 4; uint8_t buffer_storage[BUFFER_SIZE]; uint8_t *buffer = buffer_storage; size_t buffer_size = 0; IStreamRaw *raw_stream; public: void read(uint8_t *data, size_t size) { if (size <= buffer_size) { // Often, also when zero size std::memcpy(data, buffer, size); buffer += size; buffer_size -= size; return; } // size > 0 here std::memcpy(data, buffer, buffer_size); buffer = buffer_storage; buffer_size = 0; size -= buffer_size; data += buffer_size; if (size < BUFFER_SIZE / 4) { // Often buffer_size = raw_stream->read_some(buffer, BUFFER_SIZE); if (buffer_size == 0) throw std::runtime_error("IStreamRaw underflow"); std::memcpy(data, buffer, size); buffer += size; buffer_size -= size; return; } // size > 0 here while (true) { size_t cou = raw_stream->read_some(data, size); if (cou == 0) throw std::runtime_error("IStreamRaw underflow"); size -= cou; data += cou; if (size == 0) return; } }; }; */ } // namespace crab
8,152
3,228
// Copyright 2017 Gerardo Teruel #ifndef UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_ #define UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_ #include <string> class CifradoVigenere : public Cifrado { private: const std::string key; public: explicit CifradoVigenere(const std::string key) : key(key) {} virtual ~CifradoVigenere() {} virtual std::string decipher(const std::string& cipher) { std::string out = ""; int special = 0; for (int i = 0; i < cipher.size(); i++) { if (cipher[i] == '.' || cipher[i] == ' ') { special++; out.append(1, cipher[i]); } else { /** int to be able to hold negative numbers */ int c = cipher[i] - key[(i - special) % key.size()]; if (c < 0) { out.append(1, 91 + c); } else { out.append(1, (c % 26) + 65); } } } return out; } }; #endif // UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_
935
386
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/2463 #include <cstdio> #include <algorithm> using namespace std; int main(){ int n, m1 = 0, m2 = 0,d; scanf("%d",&n); while(n--){ scanf("%d",&d); m1 = max(0,m1+d); m2 = max(m1,m2); } printf("%d\n",m2); return 0; }
348
154
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "Instruction.h" #include "../Values.h" #include "ALUInstruction.h" #include "BranchInstruction.h" #include "LoadInstruction.h" #include "SemaphoreInstruction.h" #include <cstdbool> #include <memory> using namespace vc4c; using namespace vc4c::qpu_asm; LCOV_EXCL_START std::string Instruction::toASMString() const { if(auto op = as<ALUInstruction>()) return op->toASMString(); if(auto op = as<BranchInstruction>()) return op->toASMString(); if(auto op = as<LoadInstruction>()) return op->toASMString(); if(auto op = as<SemaphoreInstruction>()) return op->toASMString(); throw CompilationError(CompilationStep::CODE_GENERATION, "Invalid instruction type", std::to_string(value)); } std::string Instruction::toHexString(bool withAssemblerCode) const { uint64_t binaryCode = toBinaryCode(); if(withAssemblerCode) { return qpu_asm::toHexString(binaryCode) + "//" + toASMString(); } return qpu_asm::toHexString(binaryCode); } LCOV_EXCL_STOP bool Instruction::isValidInstruction() const { return as<ALUInstruction>() || as<BranchInstruction>() || as<LoadInstruction>() || as<SemaphoreInstruction>(); } Register Instruction::getAddOutput() const { Register reg{RegisterFile::PHYSICAL_ANY, getAddOut()}; if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4) // cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such return Register{RegisterFile::ACCUMULATOR, reg.num}; if(getWriteSwap() == WriteSwap::SWAP) return Register{RegisterFile::PHYSICAL_B, reg.num}; return Register{RegisterFile::PHYSICAL_A, reg.num}; } Register Instruction::getMulOutput() const { Register reg{RegisterFile::PHYSICAL_ANY, getMulOut()}; if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4) // cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such return Register{RegisterFile::ACCUMULATOR, reg.num}; if(getWriteSwap() == WriteSwap::DONT_SWAP) return Register{RegisterFile::PHYSICAL_B, reg.num}; return Register{RegisterFile::PHYSICAL_A, reg.num}; } LCOV_EXCL_START std::string Instruction::toInputRegister( const InputMultiplex mux, const Address regA, const Address regB, const bool hasImmediate) { if(mux == InputMultiplex::ACC0) return "r0"; if(mux == InputMultiplex::ACC1) return "r1"; if(mux == InputMultiplex::ACC2) return "r2"; if(mux == InputMultiplex::ACC3) return "r3"; if(mux == InputMultiplex::ACC4) return "r4"; if(mux == InputMultiplex::ACC5) return "r5"; // general register-file if(mux == InputMultiplex::REGA) { const Register tmp{RegisterFile::PHYSICAL_A, regA}; return tmp.to_string(true, true); } else if(hasImmediate) { // is immediate value return static_cast<SmallImmediate>(regB).to_string(); } else { const Register tmp{RegisterFile::PHYSICAL_B, regB}; return tmp.to_string(true, true); } } std::string Instruction::toOutputRegister(bool regFileA, const Address reg) { const Register tmp{regFileA ? RegisterFile::PHYSICAL_A : RegisterFile::PHYSICAL_B, reg}; return tmp.to_string(true, false); } std::string Instruction::toExtrasString(const Signaling sig, const ConditionCode cond, const SetFlag flags, const Unpack unpack, const Pack pack, bool usesOutputA, bool usesInputAOrR4) { std::string result{}; if(sig != SIGNAL_NONE && sig != SIGNAL_ALU_IMMEDIATE) result += std::string(".") + sig.to_string(); if(cond != COND_ALWAYS) result += std::string(".") + cond.to_string(); if(flags == SetFlag::SET_FLAGS) result += std::string(".") + toString(flags); if(usesInputAOrR4 && unpack.hasEffect()) result += std::string(".") + unpack.to_string(); if(usesOutputA && pack.hasEffect()) result += std::string(".") + pack.to_string(); return result; } std::string qpu_asm::toHexString(const uint64_t code) { // lower half before upper half char buffer[64]; snprintf(buffer, sizeof(buffer), "0x%08x, 0x%08x, ", static_cast<uint32_t>(code & 0xFFFFFFFFLL), static_cast<uint32_t>((code & 0xFFFFFFFF00000000LL) >> 32)); return buffer; } std::string DecoratedInstruction::toASMString(bool addComments) const { auto tmp = instruction.toASMString(); return addComments ? addComment(std::move(tmp)) : tmp; } std::string DecoratedInstruction::toHexString(bool withAssemblerCode) const { auto tmp = instruction.toHexString(withAssemblerCode); if(withAssemblerCode) { return addComment(std::move(tmp)); } return tmp; } std::string DecoratedInstruction::addComment(std::string&& s) const { std::string r; if(!comment.empty()) r = s.append(" // ").append(comment); else r = s; if(!previousComment.empty()) r = "// " + previousComment + "\n" + r; return r; } LCOV_EXCL_STOP
5,170
1,779
// Warning! This file is autogenerated. #include <boost/text/word_break.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(word, breaks_34) { // ÷ 0031 × 002E × 2060 × 0031 ÷ 0027 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 0027 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0031 ÷ 002C ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2c }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002C ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2c }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0031 ÷ 002E × 2060 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2e, 0x2060 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002E × 2060 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3] { std::array<uint32_t, 7> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2e, 0x2060 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); } // ÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷ // ÷ [0.2] <CARRIAGE RETURN (CR)> (CR) × [3.0] <LINE FEED (LF)> (LF) ÷ [3.1] LATIN SMALL LETTER A (ALetter) ÷ [3.2] <LINE FEED (LF)> (LF) ÷ [3.1] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0xd, 0xa, 0x61, 0xa, 0x308 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0061 × 0308 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x61, 0x308 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0020 × 200D ÷ 0646 ÷ // ÷ [0.2] SPACE (WSegSpace) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] ARABIC LETTER NOON (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x20, 0x200d, 0x646 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 0646 × 200D ÷ 0020 ÷ // ÷ [0.2] ARABIC LETTER NOON (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] SPACE (WSegSpace) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x646, 0x200d, 0x20 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 0041 × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x41, 0x41, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 003A × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [6.0] COLON (MidLetter) × [7.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x41, 0x3a, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 ÷ 003A ÷ 003A ÷ 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x3a, 0x3a, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 05D0 × 0027 ÷ // ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.1] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x5d0, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 05D0 × 0022 × 05D0 ÷ // ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.2] QUOTATION MARK (Double_Quote) × [7.3] HEBREW LETTER ALEF (Hebrew_Letter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x5d0, 0x22, 0x5d0 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 0030 × 0030 × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [9.0] DIGIT ZERO (Numeric) × [8.0] DIGIT ZERO (Numeric) × [10.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x30, 0x30, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); } // ÷ 0030 × 002C × 0030 ÷ // ÷ [0.2] DIGIT ZERO (Numeric) × [12.0] COMMA (MidNum) × [11.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x30, 0x2c, 0x30 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0030 ÷ 002C ÷ 002C ÷ 0030 ÷ // ÷ [0.2] DIGIT ZERO (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [999.0] COMMA (MidNum) ÷ [999.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x30, 0x2c, 0x2c, 0x30 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 3031 × 3031 ÷ // ÷ [0.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.0] VERTICAL KANA REPEAT MARK (Katakana) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x3031, 0x3031 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0041 × 005F × 0030 × 005F × 3031 × 005F ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ZERO (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.1] LOW LINE (ExtendNumLet) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x41, 0x5f, 0x30, 0x5f, 0x3031, 0x5f }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); } // ÷ 0041 × 005F × 005F × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x5f, 0x5f, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); } // ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [15.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x200d, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0061 ÷ 1F1E6 × 200D × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x200d, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER D (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x1f1e9, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 1F476 × 1F3FF ÷ 1F476 ÷ // ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [999.0] BABY (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x1f476, 0x1f3ff, 0x1f476 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 1F6D1 × 200D × 1F6D1 ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x1f6d1, 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0061 × 200D × 1F6D1 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 2701 × 200D × 2701 ÷ // ÷ [0.2] UPPER BLADE SCISSORS (Other) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x2701, 0x200d, 0x2701 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0061 × 200D × 2701 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x2701 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷ // ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x1f476, 0x1f3ff, 0x308, 0x200d, 0x1f476, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); } // ÷ 1F6D1 × 1F3FF ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 200D × 1F6D1 × 1F3FF ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x200d, 0x1f6d1, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 200D × 1F6D1 ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 200D × 1F6D1 ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 1F6D1 ÷ 1F6D1 ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) ÷ [999.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); } // ÷ 0061 × 0308 × 200D × 0308 × 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [5.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x61, 0x308, 0x200d, 0x308, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); } // ÷ 0061 ÷ 0020 × 0020 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] SPACE (WSegSpace) × [3.4] SPACE (WSegSpace) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x61, 0x20, 0x20, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 002E ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } }
67,345
32,051
// IPLookup.cpp // Implements the cIPLookup class representing an IP-to-hostname lookup in progress. #include "stdafx.h" #include "IPLookup.h" #include <event2/dns.h> #include "NetworkSingleton.h" #include <log4z.h> using namespace zsummer::log4z; //////////////////////////////////////////////////////////////////////////////// // cIPLookup: cIPLookup::cIPLookup(cNetwork::cResolveNameCallbacksPtr a_Callbacks): m_Callbacks(a_Callbacks) { ASSERT(a_Callbacks != nullptr); } bool cIPLookup::Lookup(const AString & a_IP) { // Parse the IP address string into a sockaddr structure: m_IP = a_IP; sockaddr_storage sa; int salen = static_cast<int>(sizeof(sa)); memset(&sa, 0, sizeof(sa)); if (evutil_parse_sockaddr_port(a_IP.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen) != 0) { LOGD("Failed to parse IP address \"%s\"." << a_IP.c_str()); return false; } // Call the proper resolver based on the address family: // Note that there's no need to store the evdns_request handle returned, LibEvent frees it on its own. switch (sa.ss_family) { case AF_INET: { sockaddr_in * sa4 = reinterpret_cast<sockaddr_in *>(&sa); evdns_base_resolve_reverse(cNetworkSingleton::Get().GetDNSBase(), &(sa4->sin_addr), 0, Callback, this); break; } case AF_INET6: { sockaddr_in6 * sa6 = reinterpret_cast<sockaddr_in6 *>(&sa); evdns_base_resolve_reverse_ipv6(cNetworkSingleton::Get().GetDNSBase(), &(sa6->sin6_addr), 0, Callback, this); break; } default: { LOGWARNING("%s: Unknown address family: %d", __FUNCTION__, sa.ss_family); ASSERT(!"Unknown address family"); return false; } } // switch (address family) return true; } void cIPLookup::Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self) { // Get the Self class: cIPLookup * Self = reinterpret_cast<cIPLookup *>(a_Self); ASSERT(Self != nullptr); // Call the proper callback based on the event received: if ((a_Result != 0) || (a_Addresses == nullptr)) { // An error has occurred, notify the error callback: Self->m_Callbacks->OnError(a_Result, evutil_socket_error_to_string(a_Result)); } else { // Call the success handler: Self->m_Callbacks->OnNameResolved(*(reinterpret_cast<char **>(a_Addresses)), Self->m_IP); Self->m_Callbacks->OnFinished(); } cNetworkSingleton::Get().RemoveIPLookup(Self); } //////////////////////////////////////////////////////////////////////////////// // cNetwork API: bool cNetwork::IPToHostName( const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks ) { auto res = std::make_shared<cIPLookup>(a_Callbacks); cNetworkSingleton::Get().AddIPLookup(res); return res->Lookup(a_IP); }
2,711
1,038
#include "io.hpp" #include <landstalker_lib/tools/json.hpp> #include <landstalker_lib/model/world_teleport_tree.hpp> #include <landstalker_lib/model/entity_type.hpp> #include "../logic_model/world_region.hpp" #include "../logic_model/randomizer_world.hpp" #include "../logic_model/hint_source.hpp" #include "../randomizer_options.hpp" Json SpoilerWriter::build_spoiler_json(const RandomizerWorld& world, const RandomizerOptions& options) { Json json; // Export dark node json["spawnLocation"] = world.spawn_location().id(); json["darkRegion"] = world.dark_region()->name(); // Export hints for(HintSource* hint_source : world.used_hint_sources()) json["hints"][hint_source->description()] = hint_source->text(); if(options.shuffle_tibor_trees()) { json["tiborTrees"] = Json::array(); for(auto& pair : world.teleport_tree_pairs()) json["tiborTrees"].emplace_back(pair.first->name() + " <--> " + pair.second->name()); } // Export item sources for(WorldRegion* region : world.regions()) { for(WorldNode* node : region->nodes()) { for(ItemSource* source : node->item_sources()) { Item* item = world.item(source->item_id()); json["itemSources"][region->name()][source->name()] = item->name(); } } } // Fahl enemies json["fahlEnemies"] = Json::array(); for(EntityType* enemy : world.fahl_enemies()) json["fahlEnemies"].emplace_back(enemy->name()); return json; }
1,570
522
#include <Arduino.h> #include "Task.hpp" #include <map> #include <vector> #include <functional> #ifndef SERVICE_HPP #define SERVICE_HPP #ifdef _DEBUG // This macros works only with string literals, and cannot be used in headers files. #define SERVICES_PRINTF(format, ...) Serial.printf_P(PSTR(format), ##__VA_ARGS__) #define SERVICES_PRINT(text) SERVICES_PRINTF(text) #define SERVICE_PRINTF(format, ...) Serial.printf_P(PSTR("[%s] " format), _ServiceName.c_str(), ##__VA_ARGS__) #define SERVICE_PRINT(text) SERVICE_PRINTF(text) #else #define SERVICES_PRINT(text) #define SERVICES_PRINTF(...) #define SERVICE_PRINTF(...) #define SERVICE_PRINT(text) #endif #define S(name, type) ((type*)Service::Get(name)) struct char_compare { bool operator () (const char *a, const char *b) const { return strcmp(a, b) < 0; } }; enum UpdateType { UPDATE_SYNC, UPDATE_ASYNC }; enum UpdateRequest { NO_UPDATE, DO_UPDATE, ALWAYS_UPDATE }; class Service { public: typedef std::function<void(Service* svc)> EventCallback; typedef std::map<const char*, Service*, char_compare> ServiceMap; typedef std::map<const char*, std::vector<EventCallback>, char_compare> EventMap; Service() {}; virtual void Init() = 0; virtual void Update() = 0; static Service* Get(const char* name); static void BindEvent(const char* event, EventCallback callback); static void InitAll(); static void SyncUpdate(); static void SuspendAsyncUpdates(); protected: static void RegisterService(Service* service, const char* name, std::vector<const char*> events); static void FireEvent(Service* service, const char* event); void SetPeriodicUpdate(unsigned int period, UpdateType ut = UPDATE_ASYNC); void EnablePeriodicUpdate(); void DisablePeriodicUpdate(); UpdateRequest _UpdateRequest; String _ServiceName; private: Task _UpdateTask; // List of service (name,instance) pairs. static ServiceMap _Services; // Map every event name (declared by services in register_service) with one or more callbacks. static EventMap _Events; }; #endif
2,141
702
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/page/scrolling/text_fragment_selector.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { namespace { // The prefix and suffix terms are specified to begin/end with a '-' character. // These methods will find the prefix/suffix and return it without the '-', and // remove the prefix/suffix from the |target_text| string. If not found, we // return an empty string to indicate no prefix/suffix was specified or it // was malformed and should be ignored. String ExtractPrefix(String* target_text) { size_t comma_pos = target_text->find(','); size_t hyphen_pos = target_text->find('-'); if (hyphen_pos != kNotFound && hyphen_pos == comma_pos - 1) { String prefix = target_text->Substring(0, hyphen_pos); target_text->Remove(0, comma_pos + 1); return prefix; } return ""; } String ExtractSuffix(String* target_text) { size_t last_comma_pos = target_text->ReverseFind(','); size_t last_hyphen_pos = target_text->ReverseFind('-'); if (last_hyphen_pos != kNotFound && last_hyphen_pos == last_comma_pos + 1) { String suffix = target_text->Substring(last_hyphen_pos + 1); target_text->Truncate(last_comma_pos); return suffix; } return ""; } } // namespace TextFragmentSelector TextFragmentSelector::Create(String target_text) { SelectorType type; String start; String end; String prefix = ExtractPrefix(&target_text); String suffix = ExtractSuffix(&target_text); size_t comma_pos = target_text.find(','); // If there are more commas, this is an invalid text fragment selector. size_t next_comma_pos = target_text.find(',', comma_pos + 1); if (next_comma_pos != kNotFound) return TextFragmentSelector(kInvalid); if (comma_pos == kNotFound) { type = kExact; start = target_text; end = ""; } else { type = kRange; start = target_text.Substring(0, comma_pos); end = target_text.Substring(comma_pos + 1); } return TextFragmentSelector( type, DecodeURLEscapeSequences(start, DecodeURLMode::kUTF8), DecodeURLEscapeSequences(end, DecodeURLMode::kUTF8), DecodeURLEscapeSequences(prefix, DecodeURLMode::kUTF8), DecodeURLEscapeSequences(suffix, DecodeURLMode::kUTF8)); } TextFragmentSelector::TextFragmentSelector(SelectorType type, const String& start, const String& end, const String& prefix, const String& suffix) : type_(type), start_(start), end_(end), prefix_(prefix), suffix_(suffix) {} TextFragmentSelector::TextFragmentSelector(SelectorType type) : type_(type) {} String TextFragmentSelector::ToString() const { StringBuilder selector; if (!prefix_.IsEmpty()) { selector.Append(EncodeWithURLEscapeSequences(prefix_)); selector.Append("-,"); } if (!start_.IsEmpty()) { selector.Append(EncodeWithURLEscapeSequences(start_)); } if (!end_.IsEmpty()) { selector.Append(","); selector.Append(EncodeWithURLEscapeSequences(end_)); } if (!suffix_.IsEmpty()) { selector.Append(",-"); selector.Append(EncodeWithURLEscapeSequences(suffix_)); } return selector.ToString(); } } // namespace blink
3,555
1,133
/* * Copyright (c) 2022 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "luci/Pass/QuantizePreCheckerPass.h" #include <luci/IR/CircleNodes.h> #include <gtest/gtest.h> class SimpleConv2DGraph { public: SimpleConv2DGraph(bool make_valid) { conv2d_node = g.nodes()->create<luci::CircleConv2D>(); input_1 = g.nodes()->create<luci::CircleInput>(); filter = g.nodes()->create<luci::CircleConst>(); conv2d_node->input(input_1); conv2d_node->filter(filter); if (make_valid) { bias = g.nodes()->create<luci::CircleConst>(); conv2d_node->bias(bias); } else { input_2 = g.nodes()->create<luci::CircleInput>(); conv2d_node->bias(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(conv2d_node); } public: loco::Graph g; private: luci::CircleConv2D *conv2d_node = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *filter = nullptr; luci::CircleConst *bias = nullptr; luci::CircleOutput *output = nullptr; }; class SimpleDepthConv2DGraph { public: SimpleDepthConv2DGraph(bool make_valid) { depth_conv2d_node = g.nodes()->create<luci::CircleDepthwiseConv2D>(); input_1 = g.nodes()->create<luci::CircleInput>(); filter = g.nodes()->create<luci::CircleConst>(); depth_conv2d_node->input(input_1); depth_conv2d_node->filter(filter); if (make_valid) { bias = g.nodes()->create<luci::CircleConst>(); depth_conv2d_node->bias(bias); } else { input_2 = g.nodes()->create<luci::CircleInput>(); depth_conv2d_node->bias(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(depth_conv2d_node); } public: loco::Graph g; private: luci::CircleDepthwiseConv2D *depth_conv2d_node = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *filter = nullptr; luci::CircleConst *bias = nullptr; luci::CircleOutput *output = nullptr; }; class SimpleFCGraph { public: SimpleFCGraph(bool make_valid) { fc_node = g.nodes()->create<luci::CircleFullyConnected>(); input_1 = g.nodes()->create<luci::CircleInput>(); weights = g.nodes()->create<luci::CircleConst>(); fc_node->input(input_1); fc_node->weights(weights); if (make_valid) { bias = g.nodes()->create<luci::CircleConst>(); fc_node->bias(bias); } else { input_2 = g.nodes()->create<luci::CircleInput>(); fc_node->bias(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(fc_node); } public: loco::Graph g; private: luci::CircleFullyConnected *fc_node = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *weights = nullptr; luci::CircleConst *bias = nullptr; luci::CircleOutput *output = nullptr; }; class SimpleInstanceNormGraph { public: SimpleInstanceNormGraph(bool make_valid) { instance_norm_node = g.nodes()->create<luci::CircleInstanceNorm>(); input_1 = g.nodes()->create<luci::CircleInput>(); gamma = g.nodes()->create<luci::CircleConst>(); instance_norm_node->input(input_1); instance_norm_node->gamma(gamma); if (make_valid) { beta = g.nodes()->create<luci::CircleConst>(); instance_norm_node->beta(beta); } else { input_2 = g.nodes()->create<luci::CircleInput>(); instance_norm_node->beta(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(instance_norm_node); } public: loco::Graph g; private: luci::CircleInstanceNorm *instance_norm_node = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *gamma = nullptr; luci::CircleConst *beta = nullptr; luci::CircleOutput *output = nullptr; }; class SimpleTransposeConvGraph { public: SimpleTransposeConvGraph(bool make_valid) { transpose_conv = g.nodes()->create<luci::CircleTransposeConv>(); input_1 = g.nodes()->create<luci::CircleInput>(); input_sizes = g.nodes()->create<luci::CircleConst>(); filter = g.nodes()->create<luci::CircleConst>(); transpose_conv->outBackprop(input_1); transpose_conv->filter(filter); transpose_conv->inputSizes(input_sizes); if (make_valid) { bias = g.nodes()->create<luci::CircleConst>(); transpose_conv->bias(bias); } else { input_2 = g.nodes()->create<luci::CircleInput>(); transpose_conv->bias(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(transpose_conv); } public: loco::Graph g; private: luci::CircleTransposeConv *transpose_conv = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *input_sizes = nullptr; luci::CircleConst *filter = nullptr; luci::CircleConst *bias = nullptr; luci::CircleOutput *output = nullptr; }; class SimplePReluGraph { public: SimplePReluGraph(bool make_valid) { prelu = g.nodes()->create<luci::CirclePRelu>(); input_1 = g.nodes()->create<luci::CircleInput>(); prelu->input(input_1); if (make_valid) { alpha = g.nodes()->create<luci::CircleConst>(); prelu->alpha(alpha); } else { input_2 = g.nodes()->create<luci::CircleInput>(); prelu->alpha(input_2); } output = g.nodes()->create<luci::CircleOutput>(); auto graph_output = g.outputs()->create(); output->index(graph_output->index()); output->from(prelu); } public: loco::Graph g; private: luci::CirclePRelu *prelu = nullptr; luci::CircleInput *input_1 = nullptr; luci::CircleInput *input_2 = nullptr; luci::CircleConst *alpha = nullptr; luci::CircleOutput *output = nullptr; }; TEST(QuantizePreCheckerPassTest, name) { luci::QuantizePreCheckerPass pass{}; auto const name = pass.name(); ASSERT_NE(nullptr, name); } // Test Conv2d TEST(QuantizePreCheckerPassTest, conv2d) { SimpleConv2DGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, conv2d_NEG) { SimpleConv2DGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); } // Test DepthwiseConv2d TEST(QuantizePreCheckerPassTest, depthwise_conv2d) { SimpleDepthConv2DGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, depthwise_conv2d_NEG) { SimpleDepthConv2DGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); } // Test FullyConnected TEST(QuantizePreCheckerPassTest, fully_connected) { SimpleFCGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, fully_connected_NEG) { SimpleFCGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); } // Test InstanceNorm TEST(QuantizePreCheckerPassTest, instance_norm) { SimpleInstanceNormGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, instance_norm_NEG) { SimpleInstanceNormGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); } // Test TransposeConv TEST(QuantizePreCheckerPassTest, transpose_conv) { SimpleTransposeConvGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, transpose_conv_NEG) { SimpleTransposeConvGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); } // Test PRelu TEST(QuantizePreCheckerPassTest, prelu) { SimplePReluGraph valid_graph(true); luci::QuantizePreCheckerPass checker{}; EXPECT_NO_THROW(checker.run(&valid_graph.g)); } TEST(QuantizePreCheckerPassTest, prelu_NEG) { SimplePReluGraph invalid_graph(false); luci::QuantizePreCheckerPass checker{}; EXPECT_ANY_THROW(checker.run(&invalid_graph.g)); }
9,436
3,510
#include "Stepper.h" #include <Arduino.h> uint16_t getPortAddress(char port){ switch (port) { case 'B': return 0x05; case 'C': return 0x08; default://'D' return 0x0B; } } uint16_t getDDrAddress(char port) { switch (port) { case 'B': return 0x04; case 'C': return 0x07; default: //'D' return 0x0A; } } Stepper::Stepper(char *step_port_pin, char *dir_port_pin, double stepper_angle, int micro_stepping) { // set both step and dir ports and pins step_port_addr = getPortAddress(step_port_pin[0]); step_pin = step_port_pin[1] - '0'; dir_port_addr = getPortAddress(dir_port_pin[0]); dir_pin = dir_port_pin[1] - '0'; // set both step and dir as output _SFR_IO8(getDDrAddress(step_port_pin[0])) |= (1 << step_pin); _SFR_IO8(getDDrAddress(dir_port_pin[0])) |= (1 << dir_pin ); // init the direction setDirection(0); //calculate stepper resolution this->angle_per_step = stepper_angle / micro_stepping; // set default speed setSpeedInDegrees(100); } void Stepper::setDirection(uint8_t dir) { dir = dir % 2; //correct the dir if not 1 or 0 this->dir = dir; if (dir == 0) _SFR_IO8(dir_port_addr) &= ~(1 << dir_pin); //set the dir pin to 0 else _SFR_IO8(dir_port_addr) |= (1 << dir_pin); //set the dir pin to 1 } uint8_t Stepper::getDirection() {return dir;} void Stepper::pulseStepPin() { _SFR_IO8(step_port_addr) &= ~(1 << step_pin); //set pin to 0 //_delay_us(1); //delay for meeting condition _SFR_IO8(step_port_addr) |= (1 << step_pin); //set pin to 1 } void Stepper::makeAstep() { if (rotateMotor) { current_tick++; if (current_tick == ticks_for_one_step) //this condition controlls the speed of the motor { current_tick = 0; if (isInSpinMode) // keep spinning pulseStepPin(); else if (current_step != target_steps) // target angle not reached yet { pulseStepPin(); current_step++; } else { stop(); //stop the motor if (__onTagetReached != nullptr) __onTagetReached();// trigger callback, } } } } //this takes only positive values void Stepper::moveWithAngle(double angle){ //stop, cancel spin and reset current_steps stop(); // calculate target steps target_steps = abs(round(angle / angle_per_step)); //move towards target rotateMotor = true; } void Stepper::moveWithSteps(uint32_t steps) { //stop, cancel spin and reset all states stop(); // calculate target steps target_steps = steps; //move towards target rotateMotor = true; } void Stepper::stop(){ rotateMotor = false; isInSpinMode = false; current_tick = 0; current_step = 0; target_steps = 0; } void Stepper::spin(){ isInSpinMode = true; rotateMotor = true; } void Stepper::setSpeedInDegrees(uint16_t spd) { speed = abs(spd) / angle_per_step; //convert deg/sec to step/sec if (speed >= MAX_SPEED) speed = MAX_SPEED; ticks_for_one_step = round(MAX_SPEED / speed); current_tick = 0; // reset tick } void Stepper::setSpeedInSteps(uint16_t spd) { speed = abs(spd); if (speed >= MAX_SPEED) speed = MAX_SPEED; ticks_for_one_step = round(MAX_SPEED / speed); current_tick = 0; // reset tick } uint16_t Stepper::getSpeedInDegrees() { return (uint16_t)(speed * angle_per_step); } uint16_t Stepper::getSpeedInSteps() { return (uint16_t)speed; } void Stepper::setStepperIndex(uint8_t stepper_index){ this->stepper_index = stepper_index; }; uint8_t Stepper::getStepperIndex(){ return stepper_index; }; void Stepper::setOnTargetReachedCallback(void (*callback)(void)){ __onTagetReached = callback; }
4,000
1,444
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.UI.ToggleGroup #include "UnityEngine/UI/ToggleGroup.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Predicate`1<T> template<typename T> class Predicate_1; // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; } // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Toggle class Toggle; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::UI::ToggleGroup::$$c); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::ToggleGroup::$$c*, "UnityEngine.UI", "ToggleGroup/<>c"); // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class ToggleGroup::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9 static ::UnityEngine::UI::ToggleGroup::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9 static void _set_$$9(::UnityEngine::UI::ToggleGroup::$$c* value); // Get static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0 static ::System::Predicate_1<::UnityEngine::UI::Toggle*>* _get_$$9__13_0(); // Set static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0 static void _set_$$9__13_0(::System::Predicate_1<::UnityEngine::UI::Toggle*>* value); // Get static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0 static ::System::Func_2<::UnityEngine::UI::Toggle*, bool>* _get_$$9__14_0(); // Set static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0 static void _set_$$9__14_0(::System::Func_2<::UnityEngine::UI::Toggle*, bool>* value); // static private System.Void .cctor() // Offset: 0x1145354 static void _cctor(); // System.Boolean <AnyTogglesOn>b__13_0(UnityEngine.UI.Toggle x) // Offset: 0x11453BC bool $AnyTogglesOn$b__13_0(::UnityEngine::UI::Toggle* x); // System.Boolean <ActiveToggles>b__14_0(UnityEngine.UI.Toggle x) // Offset: 0x11453D4 bool $ActiveToggles$b__14_0(::UnityEngine::UI::Toggle* x); // public System.Void .ctor() // Offset: 0x11453B4 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ToggleGroup::$$c* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::UI::ToggleGroup::$$c::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ToggleGroup::$$c*, creationType>())); } }; // UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::UI::ToggleGroup::$$c::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0 // Il2CppName: <AnyTogglesOn>b__13_0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0)> { static const MethodInfo* get() { static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<AnyTogglesOn>b__13_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x}); } }; // Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0 // Il2CppName: <ActiveToggles>b__14_0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0)> { static const MethodInfo* get() { static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<ActiveToggles>b__14_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x}); } }; // Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
5,675
2,052
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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 <jni.h> #include "OniProperties.h" #include "OniEnums.h" #include "OniCAPI.h" #include "org_openni_NativeMethods.h" #include <XnPlatform.h> #ifdef ANDROID #include <android/log.h> #endif #define DEBUG 1 #if DEBUG && defined(ANDROID) #include <android/log.h> # define LOGD(x...) __android_log_print(ANDROID_LOG_INFO,"OpenNIJNI",x) # define LOGE(x...) __android_log_print(ANDROID_LOG_ERROR,"OpenNIJNI",x) #else # define LOGD(...) # define LOGE(...) #endif using namespace openni; JavaVM* g_pVM = NULL; jclass g_videoStreamClass; jclass g_openNIClass; jclass g_deviceInfoClass; class JNIEnvSupplier { public: JNIEnvSupplier() : m_pEnv(NULL), m_bShouldDetach(FALSE) { if (JNI_EDETACHED == g_pVM->GetEnv((void**)&m_pEnv, JNI_VERSION_1_2)) { g_pVM->AttachCurrentThread((void**)&m_pEnv, NULL); m_bShouldDetach = TRUE; } } ~JNIEnvSupplier() { if (m_bShouldDetach) { g_pVM->DetachCurrentThread(); } } JNIEnv* GetEnv() { return m_pEnv; } private: JNIEnv* m_pEnv; XnBool m_bShouldDetach; }; void SetOutArgObjectValue(JNIEnv*env, jobject p, jobject value) { jclass cls = env->GetObjectClass(p); jfieldID fieldID = env->GetFieldID(cls, "mValue", "Ljava/lang/Object;"); env->SetObjectField(p, fieldID, value); } void SetOutArgVideoModeValue(JNIEnv*env, jobject p, jobject value) { SetOutArgObjectValue(env, p, value); } void SetOutArgDoubleValue(JNIEnv*env, jobject p, double value) { jclass cls = env->FindClass("java/lang/Double"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(D)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgLongValue(JNIEnv*env, jobject p, XnUInt64 value) { jclass cls = env->FindClass("java/lang/Long"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(J)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgIntValue(JNIEnv*env, jobject p, int value) { jclass cls = env->FindClass("java/lang/Integer"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(I)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgShortValue(JNIEnv*env, jobject p, short value) { jclass cls = env->FindClass("java/lang/Short"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(S)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgByteValue(JNIEnv*env, jobject p, XnUInt8 value) { jclass cls = env->FindClass("java/lang/Byte"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(B)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgBoolValue(JNIEnv*env, jobject p, jboolean value) { jclass cls = env->FindClass("java/lang/Boolean"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(Z)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgFloatValue(JNIEnv*env, jobject p, jfloat value) { jclass cls = env->FindClass("java/lang/Float"); jmethodID ctor = env->GetMethodID(cls, "<init>", "(F)V"); SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value)); } void SetOutArgStringValue(JNIEnv*env, jobject p, const XnChar* value) { SetOutArgObjectValue(env, p, env->NewStringUTF(value)); } JNIEnv *g_env; JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameRelease (JNIEnv *, jclass, jlong frame) { // oniFrameRelease((OniFrame*)frame); } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameAddRef (JNIEnv *, jclass, jlong frame) { //oniFrameAddRef((OniFrame*)frame); } static void ONI_CALLBACK_TYPE callback(OniStreamHandle streamHandle, void*) { JNIEnvSupplier suplier; jmethodID methodID = suplier.GetEnv()->GetStaticMethodID(g_videoStreamClass, "onFrameReady", "(J)V"); jlong handle = (jlong)streamHandle; suplier.GetEnv()->CallStaticVoidMethod(g_videoStreamClass, methodID, handle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceCreateStream (JNIEnv *env, jclass, jlong device, jint sensorType, jobject videoStreamObj) { OniStreamHandle* streamHandle; jint status = oniDeviceCreateStream((OniDeviceHandle)device, (OniSensorType)sensorType, (OniStreamHandle*)&streamHandle); if (status == ONI_STATUS_OK) { jclass videoStreamCls = env->FindClass("org/openni/VideoStream"); jfieldID fieldID = env->GetFieldID(videoStreamCls, "mStreamHandle", "J"); env->SetLongField(videoStreamObj, fieldID, (jlong)streamHandle); OniCallbackHandle handle = 0; status = oniStreamRegisterNewFrameCallback((OniStreamHandle)streamHandle, callback, videoStreamCls, &handle); fieldID = env->GetFieldID(videoStreamCls, "mCallbackHandle", "J"); env->SetLongField(videoStreamObj, fieldID, (jlong)handle); } return status; } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamDestroy (JNIEnv *, jclass, jlong streamHandle, jlong callbackHandle) { oniStreamUnregisterNewFrameCallback((OniStreamHandle)streamHandle,(OniCallbackHandle)callbackHandle); oniStreamDestroy((OniStreamHandle)streamHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamStart (JNIEnv *, jclass, jlong streamHandle) { return oniStreamStart((OniStreamHandle)streamHandle); } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamStop (JNIEnv *, jclass, jlong streamHandle) { oniStreamStop((OniStreamHandle)streamHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamReadFrame (JNIEnv *env, jclass, jlong streamHandle, jobject outArgObj) { OniFrame* pOniFrame; int status = oniStreamReadFrame((OniStreamHandle)streamHandle, &pOniFrame); if (status == STATUS_OK) { jclass videoFrameRefCls = env->FindClass("org/openni/VideoFrameRef"); jmethodID videoFrameCtor = env->GetMethodID(videoFrameRefCls, "<init>", "(J)V"); jobject videoFrameRefObj = env->NewObject(videoFrameRefCls, videoFrameCtor, (jlong)pOniFrame); jfieldID fieldID = env->GetFieldID(videoFrameRefCls, "mTimestamp", "J"); env->SetLongField(videoFrameRefObj,fieldID, (jlong)pOniFrame->timestamp); fieldID = env->GetFieldID(videoFrameRefCls, "mIndex", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->frameIndex); fieldID = env->GetFieldID(videoFrameRefCls, "mWidth", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->width); fieldID = env->GetFieldID(videoFrameRefCls, "mHeight", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->height); fieldID = env->GetFieldID(videoFrameRefCls, "mIsCropping", "Z"); env->SetBooleanField(videoFrameRefObj,fieldID, (pOniFrame->croppingEnabled == TRUE)); fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigX", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginX); fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigY", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginY); fieldID = env->GetFieldID(videoFrameRefCls, "mStride", "I"); env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->stride); jclass byteOrderCls = env->FindClass("java/nio/ByteOrder"); jfieldID littleEndianField = env->GetStaticFieldID(byteOrderCls, "LITTLE_ENDIAN", "Ljava/nio/ByteOrder;"); jobject littleEndian = env->GetStaticObjectField(byteOrderCls, littleEndianField); jclass byteBufferCls = env->FindClass("java/nio/ByteBuffer"); jmethodID orderMethodId = env->GetMethodID(byteBufferCls, "order", "(Ljava/nio/ByteOrder;)Ljava/nio/ByteBuffer;"); jobject buffer = env->NewDirectByteBuffer(pOniFrame->data, pOniFrame->dataSize); env->CallObjectMethod(buffer, orderMethodId, littleEndian); fieldID = env->GetFieldID(videoFrameRefCls, "mData", "Ljava/nio/ByteBuffer;"); env->SetObjectField(videoFrameRefObj,fieldID, buffer); jclass sensorTypeCls = env->FindClass("org/openni/SensorType"); jmethodID sensorFromNative = env->GetStaticMethodID(sensorTypeCls, "fromNative", "(I)Lorg/openni/SensorType;"); jobject sensorTypeObj = env->CallStaticObjectMethod(sensorTypeCls, sensorFromNative, pOniFrame->sensorType); fieldID = env->GetFieldID(videoFrameRefCls, "mSensorType", "Lorg/openni/SensorType;"); env->SetObjectField(videoFrameRefObj,fieldID, sensorTypeObj); jclass videoModeCls = env->FindClass("org/openni/VideoMode"); jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V"); jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, (jint)pOniFrame->videoMode.resolutionX, (jint)pOniFrame->videoMode.resolutionY, (jint)pOniFrame->videoMode.fps, (jint)pOniFrame->videoMode.pixelFormat); fieldID = env->GetFieldID(videoFrameRefCls, "mVideoMode", "Lorg/openni/VideoMode;"); env->SetObjectField(videoFrameRefObj,fieldID, videoModeObj); SetOutArgObjectValue(env, outArgObj, videoFrameRefObj); // release this frame. The java object is its owner now. oniFrameRelease(pOniFrame); } return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getCropping (JNIEnv *env, jclass, jlong streamHandle, jobject origXOutArg, jobject origYOutArg, jobject widthOurArg, jobject heightOurArg) { OniCropping cropping; int size = sizeof(cropping); int status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, &size); SetOutArgIntValue(env, origXOutArg, cropping.originX); SetOutArgIntValue(env, origYOutArg, cropping.originY); SetOutArgIntValue(env, widthOurArg, cropping.width); SetOutArgIntValue(env, heightOurArg, cropping.height); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setCropping (JNIEnv *, jclass, jlong streamHandle, jint originX, jint originY, jint width, jint height) { OniCropping cropping; cropping.enabled = true; cropping.originX = originX; cropping.originY = originY; cropping.width = width; cropping.height = height; return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping)); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isCroppingSupported (JNIEnv *, jclass, jlong streamHandle) { return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING) == TRUE); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_resetCropping (JNIEnv *, jclass, jlong streamHandle) { OniCropping cropping; cropping.enabled = FALSE; return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping)); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getVideoMode (JNIEnv *env, jclass, jlong streamHandle, jobject videoModeArgOutObj) { jclass videoModeCls = env->FindClass("org/openni/VideoMode"); jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V"); OniVideoMode videoMode; int size = sizeof(OniVideoMode); jint status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, &size); jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX, videoMode.resolutionY, videoMode.fps, videoMode.pixelFormat); SetOutArgVideoModeValue(env, videoModeArgOutObj, videoModeObj); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setVideoMode (JNIEnv *, jclass, jlong streamHandle, jint resX, jint resY, jint fps, jint pixelFormat) { OniVideoMode videoMode; int size = sizeof(OniVideoMode); videoMode.resolutionX = resX; videoMode.resolutionY = resY; videoMode.fps = fps; videoMode.pixelFormat = (OniPixelFormat)pixelFormat; return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, size); } JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniStreamGetSensorInfo (JNIEnv *env, jclass, jlong streamHandle) { jclass arrayListCls = (*env).FindClass("java/util/ArrayList"); jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V")); jclass videoModeCls = (*env).FindClass("org/openni/VideoMode"); jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V"); const OniSensorInfo* sensorInfo = oniStreamGetSensorInfo((OniStreamHandle)streamHandle); int i = 0; while (i < sensorInfo->numSupportedVideoModes) { OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i]; jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX, videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat); (*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj); i++; } jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo"); jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj); return obj; } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_hasSensor (JNIEnv *, jclass, jlong deviceHandle, jint sensorType) { const OniSensorInfo* pInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType); if (pInfo == NULL) { return false; } return true; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetIntProperty (JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj) { int value = 0; int size = sizeof(value); int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size); SetOutArgIntValue(env, argOutObj, value); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetBoolProperty (JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj) { OniBool value = false; int size = sizeof(value); int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size); SetOutArgBoolValue(env, argOutObj, value == TRUE); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetFloatProperty (JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj) { float value = 0; int size = sizeof(value); int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size); SetOutArgFloatValue(env, argOutObj, value); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JII (JNIEnv *, jclass, jlong streamHandle, jint property, jint value) { int size = sizeof(value); return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIZ (JNIEnv *, jclass, jlong streamHandle, jint property, jboolean value) { OniBool val = value?TRUE:FALSE; int size = sizeof(val); return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &val, size); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIF (JNIEnv *, jclass, jlong streamHandle, jint property, jfloat value) { int size = sizeof(value); return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniStreamIsPropertySupported (JNIEnv *, jclass, jlong streamHandle, jint property) { return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, property) == TRUE); } JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetSensorInfo (JNIEnv *env, jclass, jlong deviceHandle, jint sensorType) { jclass arrayListCls = (*env).FindClass("java/util/ArrayList"); jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V")); jclass videoModeCls = (*env).FindClass("org/openni/VideoMode"); jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V"); const OniSensorInfo* sensorInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType); if (sensorInfo == NULL) return NULL; int i = 0; while (i < sensorInfo->numSupportedVideoModes) { OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i]; jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX, videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat); (*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj); i++; } jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo"); jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj); return obj; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceEnableDepthColorSync (JNIEnv *, jclass, jlong deviceHandle) { return oniDeviceEnableDepthColorSync((OniDeviceHandle)deviceHandle); } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniDeviceDisableDepthColorSync (JNIEnv *, jclass, jlong deviceHandle) { return oniDeviceDisableDepthColorSync((OniDeviceHandle)deviceHandle); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceGetDepthColorSyncEnabled (JNIEnv *, jclass, jlong deviceHandle) { return (jboolean)oniDeviceGetDepthColorSyncEnabled((OniDeviceHandle)deviceHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_seek (JNIEnv *, jclass, jlong deviceHandle, jlong streamHandle, jint frameIndex) { OniSeek seek; seek.frameIndex = frameIndex; seek.stream = (OniStreamHandle)streamHandle; return oniDeviceInvoke((OniDeviceHandle)deviceHandle, DEVICE_COMMAND_SEEK, &seek, sizeof(seek)); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isImageRegistrationModeSupported (JNIEnv *, jclass, jlong deviceHandle, jint mode) { return (oniDeviceIsImageRegistrationModeSupported((OniDeviceHandle)deviceHandle, (OniImageRegistrationMode)mode) == TRUE); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getImageRegistrationMode (JNIEnv *env, jclass, jlong deviceHandle, jobject argOutObj) { ImageRegistrationMode mode; int size = sizeof(mode); int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, &size); SetOutArgIntValue(env, argOutObj, mode); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setImageRegistrationMode (JNIEnv *, jclass, jlong deviceHandle, jint mode) { return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, sizeof(mode)); } JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetInfo (JNIEnv *env, jclass, jlong deviceHandle) { OniDeviceInfo deviceInfo; oniDeviceGetInfo((OniDeviceHandle)deviceHandle, &deviceInfo); jobject nameObj = env->NewStringUTF(deviceInfo.name); jobject uriObj = env->NewStringUTF(deviceInfo.uri); jobject vendorObj = env->NewStringUTF(deviceInfo.vendor); jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo"); return (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"), uriObj, vendorObj, nameObj, deviceInfo.usbVendorId, deviceInfo.usbProductId); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderStart (JNIEnv *, jclass, jlong recorderHandle) { return oniRecorderStart((OniRecorderHandle)recorderHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderDestroy (JNIEnv *, jclass, jlong recorderHandle) { return oniRecorderDestroy((OniRecorderHandle*)&recorderHandle); } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniRecorderStop (JNIEnv *, jclass, jlong recorderHandle) { oniRecorderStop((OniRecorderHandle)recorderHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderAttachStream (JNIEnv *, jclass, jlong recorderHandle, jlong streamHadle, jboolean allowLossy) { return oniRecorderAttachStream((OniRecorderHandle)recorderHandle, (OniStreamHandle)streamHadle, allowLossy); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetIntProperty (JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj) { int value; int size = sizeof(value); int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size); SetOutArgIntValue(env, argOutObj, value); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetBoolProperty (JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj) { OniBool value; int size = sizeof(value); int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size); SetOutArgBoolValue(env, argOutObj, (value==TRUE)?JNI_TRUE:JNI_FALSE); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetFloatProperty (JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj) { float value; int size = sizeof(float); int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size); SetOutArgFloatValue(env, argOutObj, value); return rc; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JII (JNIEnv *, jclass, jlong deviceHandle, jint property, jint value) { return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value)); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIZ (JNIEnv *, jclass, jlong deviceHandle, jint property, jboolean value) { OniBool oniValue = (value == JNI_TRUE)?TRUE:FALSE; return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &oniValue, sizeof(oniValue)); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIF (JNIEnv *, jclass, jlong deviceHandle, jint property, float value) { return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value)); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsPropertySupported (JNIEnv *, jclass, jlong deviceHandle, jint property) { return (oniDeviceIsPropertySupported((OniDeviceHandle)deviceHandle, property) == TRUE); } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsCommandSupported (JNIEnv *, jclass, jlong deviceHandle, jint command) { return (oniDeviceIsCommandSupported((OniDeviceHandle)deviceHandle, command) == TRUE); } static void ONI_CALLBACK_TYPE deviceConnectedCallback(const OniDeviceInfo* pInfo, void*) { JNIEnvSupplier suplier; JNIEnv *env = suplier.GetEnv(); jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceConnected", "(Lorg/openni/DeviceInfo;)V"); jobject nameObj = env->NewStringUTF(pInfo->name); jobject uriObj = env->NewStringUTF(pInfo->uri); jobject vendorObj = env->NewStringUTF(pInfo->vendor); jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"), uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId); env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj); } static void ONI_CALLBACK_TYPE deviceDisconnectedCallback(const OniDeviceInfo* pInfo, void*) { JNIEnvSupplier suplier; JNIEnv *env = suplier.GetEnv(); jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceDisconnected", "(Lorg/openni/DeviceInfo;)V"); jobject nameObj = env->NewStringUTF(pInfo->name); jobject uriObj = env->NewStringUTF(pInfo->uri); jobject vendorObj = env->NewStringUTF(pInfo->vendor); jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"), uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId); env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj); } static void ONI_CALLBACK_TYPE deviceStateChangedCallback(const OniDeviceInfo* pInfo, OniDeviceState state, void*) { JNIEnvSupplier suplier; JNIEnv *env = suplier.GetEnv(); jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceStateChanged", "(Lorg/openni/DeviceInfo;I)V"); jobject nameObj = env->NewStringUTF(pInfo->name); jobject uriObj = env->NewStringUTF(pInfo->uri); jobject vendorObj = env->NewStringUTF(pInfo->vendor); jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"), uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId); env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj, state); } static OniCallbackHandle callbackHandle = 0; JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniInitialize (JNIEnv *env, jclass) { int status = oniInitialize(ONI_API_VERSION); if (status == ONI_STATUS_OK) { OniDeviceCallbacks callbacks; callbacks.deviceConnected = deviceConnectedCallback; callbacks.deviceDisconnected = deviceDisconnectedCallback; callbacks.deviceStateChanged = deviceStateChangedCallback; status = oniRegisterDeviceCallbacks(&callbacks, env, &callbackHandle); } return status; } JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniShutdown (JNIEnv *, jclass) { if (callbackHandle != 0) oniUnregisterDeviceCallbacks(callbackHandle); return oniShutdown(); } JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniGetVersion (JNIEnv *env , jclass) { OniVersion version = oniGetVersion(); jclass versionCls = env->FindClass("org/openni/Version"); return (*env).NewObject(versionCls, (*env).GetMethodID(versionCls, "<init>", "(IIII)V"), version.major, version.minor, version.maintenance, version.build); } JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetExtendedError (JNIEnv *env , jclass) { return env->NewStringUTF(oniGetExtendedError()); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniGetDeviceList (JNIEnv *env, jclass, jobject deviceListObj) { OniDeviceInfo* m_pDeviceInfos; int m_deviceInfoCount; jint status = oniGetDeviceList(&m_pDeviceInfos, &m_deviceInfoCount); if (status == 0) { for (int i = 0; i < m_deviceInfoCount; i++) { jobject nameObj = env->NewStringUTF(m_pDeviceInfos[i].name); jobject uriObj = env->NewStringUTF(m_pDeviceInfos[i].uri); jobject vendorObj = env->NewStringUTF(m_pDeviceInfos[i].vendor); jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo"); jobject deviceInfObj = (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"), uriObj, vendorObj, nameObj, m_pDeviceInfos[i].usbVendorId, m_pDeviceInfos[i].usbProductId); jclass vectorCls = (*env).FindClass("java/util/List"); jmethodID methodId = (*env).GetMethodID(vectorCls, "add", "(Ljava/lang/Object;)Z"); (*env).CallBooleanMethod(deviceListObj, methodId, deviceInfObj); } } return status; } JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniWaitForAnyStream (JNIEnv *env, jclass, jlongArray streamsArray, jobject outArgObj, jint timeout) { jlong *streams = env->GetLongArrayElements(streamsArray, JNI_FALSE); int size = env->GetArrayLength(streamsArray); int id = 0; int rc = oniWaitForAnyStream((OniStreamHandle*)streams, size, &id, timeout); env->ReleaseLongArrayElements(streamsArray, streams, JNI_ABORT); SetOutArgIntValue(env, outArgObj, id); return rc == ONI_STATUS_OK; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterWorldToDepth (JNIEnv *env, jclass, jlong streamHandle, jfloat worldX, jfloat worldY, jfloat worldZ, jobject depthXOutArg, jobject depthYOutArg, jobject depthZOutArg) { float x,y,z; int status = oniCoordinateConverterWorldToDepth((OniStreamHandle)streamHandle, worldX, worldY, worldZ, &x, &y, &z); SetOutArgFloatValue(env, depthXOutArg, x); SetOutArgFloatValue(env, depthYOutArg, y); SetOutArgFloatValue(env, depthZOutArg, z); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToWorld (JNIEnv *env, jclass, jlong streamHandle, jfloat depthX, jfloat depthY, jfloat depthZ, jobject colorXOutArg, jobject colorYOutArg, jobject colorZOutArg) { float x,y,z; int status = oniCoordinateConverterDepthToWorld((OniStreamHandle)streamHandle, depthX, depthY, depthZ, &x, &y, &z); SetOutArgFloatValue(env, colorXOutArg, x); SetOutArgFloatValue(env, colorYOutArg, y); SetOutArgFloatValue(env, colorZOutArg, z); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToColor (JNIEnv *env, jclass, jlong depthHandle, jlong colorHandle, jint depthX, jint depthY, jshort depthZ, jobject colorXOutArg, jobject colorYOutArg) { int x,y; int status = oniCoordinateConverterDepthToColor((OniStreamHandle)depthHandle, (OniStreamHandle)colorHandle, depthX, depthY, depthZ, &x, &y); SetOutArgIntValue(env, colorXOutArg, x); SetOutArgIntValue(env, colorYOutArg, y); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCreateRecorder (JNIEnv *env, jclass, jstring filename, jobject recorder) { OniRecorderHandle handle; jclass recorderCls = env->FindClass("org/openni/Recorder"); const char * str = env->GetStringUTFChars(filename, JNI_FALSE); int status = oniCreateRecorder(str, &handle); jfieldID fieldID = env->GetFieldID(recorderCls, "mRecorderHandle", "J"); env->SetLongField(recorder, fieldID, (long)handle); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Ljava_lang_String_2Lorg_openni_Device_2 (JNIEnv *env, jclass, jstring uriStrObj, jobject device) { OniDeviceHandle handle; const char * str = env->GetStringUTFChars(uriStrObj, JNI_FALSE); int status = oniDeviceOpen(str, &handle); jclass deviceCls = env->FindClass("org/openni/Device"); jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J"); env->SetLongField(device, fieldID, (long)handle); return status; } static const char* ANY_DEVICE = NULL; JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Lorg_openni_Device_2 (JNIEnv *env, jclass, jobject device) { OniDeviceHandle handle; int status = oniDeviceOpen(ANY_DEVICE, &handle); jclass deviceCls = env->FindClass("org/openni/Device"); jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J"); env->SetLongField(device, fieldID, (long)handle); return status; } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceClose (JNIEnv *, jclass, jlong deviceHandle) { return oniDeviceClose((OniDeviceHandle)deviceHandle); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogOutputFolder (JNIEnv * env, jclass, jstring path) { const char * str = env->GetStringUTFChars(path, JNI_FALSE); return oniSetLogOutputFolder(str); } JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetLogFileName (JNIEnv *env, jclass) { XnChar fileName[XN_FILE_MAX_PATH]; oniGetLogFileName(fileName, sizeof(fileName)); return env->NewStringUTF(fileName); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogMinSeverity (JNIEnv *, jclass, jint minSeverity) { return oniSetLogMinSeverity(minSeverity); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogConsoleOutput (JNIEnv *, jclass, jboolean enabled) { return oniSetLogConsoleOutput(enabled); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogFileOutput (JNIEnv *, jclass, jboolean enabled) { return oniSetLogFileOutput(enabled); } JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogAndroidOutput (JNIEnv *, jclass, jboolean enabled) { (void)(enabled); #ifdef ANDROID return oniSetLogAndroidOutput(enabled); #else return ONI_STATUS_NOT_SUPPORTED; #endif }
33,720
12,260
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/favicon_source.h" #include <cmath> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram_functions.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h" #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_service.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" #include "components/favicon/core/history_ui_favicon_request_handler.h" #include "components/favicon_base/favicon_url_parser.h" #include "components/history/core/browser/top_sites.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "extensions/common/manifest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" #include "ui/gfx/codec/png_codec.h" #include "ui/native_theme/native_theme.h" #include "ui/resources/grit/ui_resources.h" #include "url/gurl.h" namespace { // web_contents->GetLastCommittedURL in general will not necessarily yield the // original URL that started the request, but we're only interested in verifying // if it was issued by a history page, for whom this is the case. If it is not // possible to obtain the URL, we return the empty GURL. GURL GetUnsafeRequestOrigin(const content::WebContents::Getter& wc_getter) { content::WebContents* web_contents = wc_getter.Run(); return web_contents ? web_contents->GetLastCommittedURL() : GURL(); } bool ParseHistoryUiOrigin(const GURL& url, favicon::HistoryUiFaviconRequestOrigin* origin) { GURL history_url(chrome::kChromeUIHistoryURL); if (url == history_url) { *origin = favicon::HistoryUiFaviconRequestOrigin::kHistory; return true; } if (url == history_url.Resolve(chrome::kChromeUIHistorySyncedTabs)) { *origin = favicon::HistoryUiFaviconRequestOrigin::kHistorySyncedTabs; return true; } return false; } } // namespace FaviconSource::FaviconSource(Profile* profile, chrome::FaviconUrlFormat url_format) : profile_(profile->GetOriginalProfile()), url_format_(url_format) {} FaviconSource::~FaviconSource() { } std::string FaviconSource::GetSource() { switch (url_format_) { case chrome::FaviconUrlFormat::kFaviconLegacy: return chrome::kChromeUIFaviconHost; case chrome::FaviconUrlFormat::kFavicon2: return chrome::kChromeUIFavicon2Host; } NOTREACHED(); return ""; } void FaviconSource::StartDataRequest( const GURL& url, const content::WebContents::Getter& wc_getter, content::URLDataSource::GotDataCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const std::string path = content::URLDataSource::URLToRequestPath(url); favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS); if (!favicon_service) { SendDefaultResponse(std::move(callback)); return; } chrome::ParsedFaviconPath parsed; bool success = chrome::ParseFaviconPath(path, url_format_, &parsed); if (!success) { SendDefaultResponse(std::move(callback)); return; } GURL page_url(parsed.page_url); GURL icon_url(parsed.icon_url); if (!page_url.is_valid() && !icon_url.is_valid()) { SendDefaultResponse(std::move(callback)); return; } if (url_format_ == chrome::FaviconUrlFormat::kFaviconLegacy) { const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile_) ->enabled_extensions() .GetExtensionOrAppByURL(GetUnsafeRequestOrigin(wc_getter)); if (extension) { base::UmaHistogramEnumeration("Extensions.FaviconResourceRequested", extension->GetType(), extensions::Manifest::NUM_LOAD_TYPES); } } int desired_size_in_pixel = std::ceil(parsed.size_in_dip * parsed.device_scale_factor); if (parsed.page_url.empty()) { // Request by icon url. // TODO(michaelbai): Change GetRawFavicon to support combination of // IconType. favicon_service->GetRawFavicon( icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel, base::BindOnce(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), std::move(callback), parsed), &cancelable_task_tracker_); } else { // Intercept requests for prepopulated pages if TopSites exists. scoped_refptr<history::TopSites> top_sites = TopSitesFactory::GetForProfile(profile_); if (top_sites) { for (const auto& prepopulated_page : top_sites->GetPrepopulatedPages()) { if (page_url == prepopulated_page.most_visited.url) { ui::ScaleFactor resource_scale_factor = ui::GetSupportedScaleFactor(parsed.device_scale_factor); std::move(callback).Run( ui::ResourceBundle::GetSharedInstance() .LoadDataResourceBytesForScale(prepopulated_page.favicon_id, resource_scale_factor)); return; } } } favicon::HistoryUiFaviconRequestOrigin parsed_history_ui_origin; if (!parsed.allow_favicon_server_fallback || !ParseHistoryUiOrigin(GetUnsafeRequestOrigin(wc_getter), &parsed_history_ui_origin)) { // Request from local storage only. // TODO(victorvianna): Expose fallback_to_host in FaviconRequestHandler // API and move the explanatory comment for |fallback_to_host| here. const bool fallback_to_host = true; favicon_service->GetRawFaviconForPageURL( page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, fallback_to_host, base::BindOnce(&FaviconSource::OnFaviconDataAvailable, base::Unretained(this), std::move(callback), parsed), &cancelable_task_tracker_); return; } // Request from both local storage and favicon server using // HistoryUiFaviconRequestHandler. favicon::HistoryUiFaviconRequestHandler* history_ui_favicon_request_handler = HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext( profile_); if (!history_ui_favicon_request_handler) { SendDefaultResponse(std::move(callback), parsed); return; } history_ui_favicon_request_handler->GetRawFaviconForPageURL( page_url, desired_size_in_pixel, base::BindOnce(&FaviconSource::OnFaviconDataAvailable, weak_ptr_factory_.GetWeakPtr(), std::move(callback), parsed), parsed_history_ui_origin); } } std::string FaviconSource::GetMimeType(const std::string&) { // We need to explicitly return a mime type, otherwise if the user tries to // drag the image they get no extension. return "image/png"; } bool FaviconSource::AllowCaching() { return false; } bool FaviconSource::ShouldReplaceExistingSource() { // Leave the existing DataSource in place, otherwise we'll drop any pending // requests on the floor. return false; } bool FaviconSource::ShouldServiceRequest( const GURL& url, content::BrowserContext* browser_context, int render_process_id) { if (url.SchemeIs(chrome::kChromeSearchScheme)) { return InstantService::ShouldServiceRequest(url, browser_context, render_process_id); } return URLDataSource::ShouldServiceRequest(url, browser_context, render_process_id); } ui::NativeTheme* FaviconSource::GetNativeTheme() { return ui::NativeTheme::GetInstanceForNativeUi(); } void FaviconSource::OnFaviconDataAvailable( content::URLDataSource::GotDataCallback callback, const chrome::ParsedFaviconPath& parsed, const favicon_base::FaviconRawBitmapResult& bitmap_result) { if (bitmap_result.is_valid()) { // Forward the data along to the networking system. std::move(callback).Run(bitmap_result.bitmap_data.get()); } else { SendDefaultResponse(std::move(callback), parsed); } } void FaviconSource::SendDefaultResponse( content::URLDataSource::GotDataCallback callback, const chrome::ParsedFaviconPath& parsed) { if (!parsed.show_fallback_monogram) { SendDefaultResponse(std::move(callback), parsed.size_in_dip, parsed.device_scale_factor); return; } int icon_size = std::ceil(parsed.size_in_dip * parsed.device_scale_factor); SkBitmap bitmap = favicon::GenerateMonogramFavicon(GURL(parsed.page_url), icon_size, icon_size); std::vector<unsigned char> bitmap_data; bool result = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_data); DCHECK(result); std::move(callback).Run(base::RefCountedBytes::TakeVector(&bitmap_data)); } void FaviconSource::SendDefaultResponse( content::URLDataSource::GotDataCallback callback) { SendDefaultResponse(std::move(callback), 16, 1.0f); } void FaviconSource::SendDefaultResponse( content::URLDataSource::GotDataCallback callback, int size_in_dip, float scale_factor) { const bool dark = GetNativeTheme()->ShouldUseDarkColors(); int resource_id; switch (size_in_dip) { case 64: resource_id = dark ? IDR_DEFAULT_FAVICON_DARK_64 : IDR_DEFAULT_FAVICON_64; break; case 32: resource_id = dark ? IDR_DEFAULT_FAVICON_DARK_32 : IDR_DEFAULT_FAVICON_32; break; default: resource_id = dark ? IDR_DEFAULT_FAVICON_DARK : IDR_DEFAULT_FAVICON; break; } std::move(callback).Run(LoadIconBytes(scale_factor, resource_id)); } base::RefCountedMemory* FaviconSource::LoadIconBytes(float scale_factor, int resource_id) { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( resource_id, ui::GetSupportedScaleFactor(scale_factor)); }
10,643
3,365
#ifndef event_manager_hh_INCLUDED #define event_manager_hh_INCLUDED #include "utils.hh" #include <chrono> #include <unordered_set> namespace Kakoune { class FDWatcher { public: using Callback = std::function<void (FDWatcher& watcher)>; FDWatcher(int fd, Callback callback); ~FDWatcher(); int fd() const { return m_fd; } void run() { m_callback(*this); } private: int m_fd; Callback m_callback; }; using Clock = std::chrono::steady_clock; using TimePoint = Clock::time_point; class Timer { public: using Callback = std::function<void (Timer& timer)>; Timer(TimePoint date, Callback callback); ~Timer(); TimePoint next_date() const { return m_date; } void set_next_date(TimePoint date) { m_date = date; } void run(); private: TimePoint m_date; Callback m_callback; }; // The EventManager provides an interface to file descriptor // based event handling. // // The program main loop should call handle_next_events() // until it's time to quit. class EventManager : public Singleton<EventManager> { public: EventManager(); ~EventManager(); void handle_next_events(); // force the watchers associated with fd to be executed // on next handle_next_events call. void force_signal(int fd); private: friend class FDWatcher; friend class Timer; std::unordered_set<FDWatcher*> m_fd_watchers; std::unordered_set<Timer*> m_timers; std::vector<int> m_forced_fd; TimePoint m_last; }; } #endif // event_manager_hh_INCLUDED
1,557
536
#include "L298Motors.h" L298Motors::L298Motors(L298& _leftMotor, L298& _rightMotor) : Motors{_leftMotor, _rightMotor} { } void L298Motors::begin() { // Only implement the 2 motors using the same PWM driver (timer) L298 &leftMotor = static_cast<L298&>(m_leftMotor); L298 &rightMotor = static_cast<L298&>(m_rightMotor); // Only use the left config for both motors m_leftPwmConfig.frequency = m_leftMotor.m_timerFrequency; m_leftPwmConfig.period = m_leftMotor.m_timerPeriod; m_leftPwmConfig.callback = NULL; // no pwm callback m_leftPwmConfig.channels[leftMotor.m_channelA].mode = (leftMotor.m_isAComplementaryChannel ? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH : PWM_OUTPUT_ACTIVE_HIGH); m_leftPwmConfig.channels[leftMotor.m_channelB].mode = (leftMotor.m_isBComplementaryChannel ? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH : PWM_OUTPUT_ACTIVE_HIGH); m_leftPwmConfig.channels[rightMotor.m_channelA].mode = (rightMotor.m_isAComplementaryChannel ? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH : PWM_OUTPUT_ACTIVE_HIGH); m_leftPwmConfig.channels[rightMotor.m_channelB].mode = (rightMotor.m_isBComplementaryChannel ? PWM_COMPLEMENTARY_OUTPUT_ACTIVE_HIGH : PWM_OUTPUT_ACTIVE_HIGH); pwmStart(m_leftMotor.m_driver, &m_leftPwmConfig); stop(); }
1,321
595
/* Copyright 2018 Tymoteusz Blazejczyk * * 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 "logic/axi4/stream/reset_sequence.hpp" using logic::axi4::stream::reset_sequence; reset_sequence::reset_sequence() : reset_sequence{"reset_sequence"} { } reset_sequence::reset_sequence(const std::string& name) : uvm::uvm_sequence<reset_sequence_item>{name}, items{} { } reset_sequence::~reset_sequence() = default; void reset_sequence::pre_body() { if (starting_phase != nullptr) { starting_phase->raise_objection(this); } } void reset_sequence::body() { UVM_INFO(get_name(), "Starting reset sequence", uvm::UVM_FULL); for (auto& item : items) { start_item(&item); finish_item(&item); } UVM_INFO(get_name(), "Finishing reset sequence", uvm::UVM_FULL); } void reset_sequence::post_body() { if (starting_phase != nullptr) { starting_phase->drop_objection(this); } }
1,460
470
#include "boo/inputdev/NintendoPowerA.hpp" #include <array> #include <cstring> #include "boo/inputdev/DeviceSignature.hpp" namespace boo { NintendoPowerA::NintendoPowerA(DeviceToken* token) : TDeviceBase<INintendoPowerACallback>(dev_typeid(NintendoPowerA), token) {} NintendoPowerA::~NintendoPowerA() = default; void NintendoPowerA::deviceDisconnected() { std::lock_guard lk{m_callbackLock}; if (m_callback != nullptr) { m_callback->controllerDisconnected(); } } void NintendoPowerA::initialCycle() {} void NintendoPowerA::transferCycle() { std::array<uint8_t, 8> payload; const size_t recvSz = receiveUSBInterruptTransfer(payload.data(), payload.size()); if (recvSz != payload.size()) { return; } NintendoPowerAState state; std::memcpy(&state, payload.data(), sizeof(state)); std::lock_guard lk{m_callbackLock}; if (state != m_last && m_callback != nullptr) { m_callback->controllerUpdate(state); } m_last = state; } void NintendoPowerA::finalCycle() {} void NintendoPowerA::receivedHIDReport(const uint8_t* data, size_t length, HIDReportType tp, uint32_t message) {} bool NintendoPowerAState::operator==(const NintendoPowerAState& other) const { return std::memcmp(this, &other, sizeof(NintendoPowerAState)) == 0; } bool NintendoPowerAState::operator!=(const NintendoPowerAState& other) const { return !operator==(other); } } // namespace boo
1,399
487
#define PNG_NO_SETJMP #include <stdio.h> #include <stdlib.h> #include <string> #include <png.h> #include <exception> int main( int argc, const char **argv ) { if( argc < 3 ) { printf( "%s", "USE: bin2png [in] [out]\n" ); return 1; } FILE *infile = NULL; FILE *outfile = NULL; png_structp png_ptr = NULL; png_infop png_info = NULL; png_bytep rowp = NULL; try { if( ( infile = fopen( argv[ 1 ], "rb" ) ) == NULL ) throw std::exception( ( std::string() + "problem opening: " + argv[ 1 ] ).c_str() ); if( ( outfile = fopen( argv[ 2 ], "wb" ) ) == NULL ) throw std::exception( ( std::string() + "problem opening: " + argv[ 2 ] ).c_str() ); if( ( png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ) ) == NULL ) throw std::exception( ( std::string() + "png_create_struct" ).c_str() ); if( ( png_info = png_create_info_struct( png_ptr ) ) == NULL ) throw std::exception( ( std::string() + "png_create_info_struct" ).c_str() ); fseek( infile, 0, SEEK_END ); png_int_32 data_size = ftell( infile ); fseek( infile, 0, SEEK_SET ); png_init_io( png_ptr, outfile ); std::string str_data_size = std::to_string(data_size); png_text title_text; title_text.compression = PNG_TEXT_COMPRESSION_NONE; title_text.key = "size"; title_text.text_length = str_data_size.length(); title_text.text = (png_charp)str_data_size.c_str(); png_set_text( png_ptr, png_info, &title_text, 1 ); png_uint_32 val = (png_uint_32)ceil( sqrt( (float)data_size / 3.f ) ); png_uint_32 width = val; png_uint_32 height = val; png_set_IHDR( png_ptr, png_info, width, height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); png_write_info( png_ptr, png_info ); png_int_32 row_size = 3 * width; rowp = new png_byte[ row_size ]; for( png_uint_32 i = 0; i < height; ++i ) { fread( rowp, row_size, 1, infile ); png_write_row( png_ptr, rowp ); } png_write_flush( png_ptr ); png_write_end( png_ptr, png_info ); } catch( std::exception exc ) { printf( "%s", exc.what() ); } catch( ... ) { printf( "%s", "caught unexpected exception\n" ); } if( rowp ) delete[] rowp; if( png_info ) png_destroy_info_struct( png_ptr, &png_info ); if( png_ptr ) png_destroy_write_struct( &png_ptr, &png_info ); if( outfile ) fclose( outfile ); if( infile ) fclose( infile ); return 0; }
2,406
1,095
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL EPFL * * 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. */ /*! \file write_dimacs.hpp \brief Write networks CNF encoding to DIMACS format \author Mathias Soeken */ #pragma once #include <cstdint> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <fmt/format.h> #include "../traits.hpp" #include "../algorithms/cnf.hpp" namespace mockturtle { /*! \brief Writes network into CNF DIMACS format * * It also adds unit clauses for the outputs. Therefore a satisfying solution * is one that makes all outputs 1. * * \param ntk Logic network * \param out Output stream */ template <class Ntk> void write_dimacs(Ntk const& ntk, std::ostream& out = std::cout) { std::stringstream clauses; uint32_t num_clauses = 0u; const auto lits = generate_cnf(ntk, [&](std::vector<uint32_t> const& clause) { for (auto lit : clause) { const auto var = (lit / 2) + 1; const auto pol = lit % 2; clauses << fmt::format("{}{} ", pol ? "-" : "", var); } clauses << fmt::format("0\n"); ++num_clauses; }); for (auto lit : lits) { const auto var = (lit / 2) + 1; const auto pol = lit % 2; clauses << fmt::format("{}{} 0\n", pol ? "-" : "", var); ++num_clauses; } out << fmt::format("p cnf {} {}\n{}", ntk.size(), num_clauses, clauses.str()); } /*! \brief Writes network into CNF DIMACS format * * It also adds unit clauses for the outputs. Therefore a satisfying solution * is one that makes all outputs 1. * * \param ntk Logic network * \param filename Filename */ template <class Ntk> void write_dimacs(Ntk const& ntk, std::string const& filename) { std::ofstream os(filename.c_str(), std::ofstream::out); write_dimacs(ntk, os); os.close(); } } /* namespace mockturtle */
3,023
1,012
/* Copyright (c) 2015 Jacob R. Lifshay * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgement in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "context.h" #include "types/type.h" std::shared_ptr<TypeNode> CompilerContext::constructTypeNodeHelper(std::shared_ptr<TypeNode> retval) { std::size_t theHash = retval->getHash(); auto range = types.equal_range(theHash); for(auto i = range.first; i != range.second; ++i) { if(*retval == *std::get<1>(*i)) return std::get<1>(*i); } types.emplace(theHash, retval); return retval; }
1,347
392
#ifndef COBALT_PLATFORM_HPP_INCLUDED #define COBALT_PLATFORM_HPP_INCLUDED #pragma once #include <boost/predef.h> #define $on(...) __VA_ARGS__ #define $off(...) //////////////////////////////////////////////////////////////////////////////// // Windows #if BOOST_OS_WINDOWS #include <winapifamily.h> #define $windows $on #if defined(WINAPI_FAMILY) && WINAPI_FAMILY == WINAPI_PARTITION_APP #define $windows_app $on #endif #endif // BOOST_OS_WINDOWS #ifdef $windows #define $not_windows $off #else #define $windows $off #define $not_windows $on #endif // $windows #ifdef $windows_app #define $not_windows_app $off #else #define $windows_app $off #define $not_windows_app $on #endif // $windows_app //////////////////////////////////////////////////////////////////////////////// // iOS #if BOOST_OS_IOS #include <TargetConditionals.h> #define $ios $on #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR #define $ios_simulator $on #endif #endif // BOOST_OS_IOS #ifdef $ios #define $not_ios $off #else #define $ios $off #define $not_ios $on #endif // $ios #ifdef $ios_simulator #define $not_ios_simulator $off #else #define $ios_simulator $off #define $not_ios_simulator $on #endif // $ios_simulator //////////////////////////////////////////////////////////////////////////////// // macOS #if BOOST_OS_MACOS #define $macos $on #endif // BOOST_OS_MACOS #ifdef $macos #define $not_macos $off #else #define $macos $off #define $not_macos $on #endif // $macos //////////////////////////////////////////////////////////////////////////////// // Android #if BOOST_OS_ANDROID #define $android $on #endif // BOOST_OS_ANDROID #ifdef $android #define $not_android $off #else #define $android $off #define $not_android $on #endif // $android //////////////////////////////////////////////////////////////////////////////// // Linux #if BOOST_OS_LINUX #define $linux $on #endif // BOOST_OS_LINUX #ifdef $linux #define $not_linux $off #else #define $linux $off #define $not_linux $on #endif // $linux //////////////////////////////////////////////////////////////////////////////// // Desktop | Mobile #if BOOST_OS_WINDOWS || BOOST_OS_MACOS || BOOST_OS_LINUX #define $desktop $on #endif // #ifdef $desktop #define $mobile $off #else #define $desktop $off #define $mobile $on #endif // $linux #endif // COBALT_PLATFORM_HPP_INCLUDED
2,351
823
/*========================================================================= Copyright (c) 2007, Los Alamos National Security, LLC All rights reserved. Copyright 2007. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <math.h> #include "Partition.h" #include "CosmoHaloFinderP.h" using namespace std; ///////////////////////////////////////////////////////////////////////// // // Parallel manager for serial CosmoHaloFinder // Particle data space is partitioned for the number of processors // which currently is a factor of two but is easily extended. Particles // are read in from files where each processor reads one file into a buffer, // extracts the particles which really belong on the processor (ALIVE) and // those in a buffer region around the edge (DEAD). The buffer is then // passed round robin to every other processor so that all particles are // examined by all processors. All dead particles are tagged with the // neighbor zone (26 neighbors in 3D) so that later halos can be associated // with zones. // // The serial halo finder is called on each processor and returns enough // information so that it can be determined if a halo is completely ALIVE, // completely DEAD, or mixed. A mixed halo that is shared between on two // processors is kept by the processor that contains it in one of its // high plane neighbors, and is given up if contained in a low plane neighbor. // // Mixed halos that cross more than two processors are bundled up and sent // to the MASTER processor which decides the processor that should own it. // ///////////////////////////////////////////////////////////////////////// CosmoHaloFinderP::CosmoHaloFinderP() : haloData(NULL), haloList(NULL), haloStart(NULL), haloSize(NULL) { // Get the number of processors and rank of this processor this->numProc = Partition::getNumProc(); this->myProc = Partition::getMyProc(); // Get the number of processors in each dimension Partition::getDecompSize(this->layoutSize); // Get my position within the Cartesian topology Partition::getMyPosition(this->layoutPos); // Get the neighbors of this processor Partition::getNeighbors(this->neighbor); // For each neighbor zone, how many dead particles does it contain to start // and how many dead halos does it contain after the serial halo finder // For analysis but not necessary to run the code // for (int n = 0; n < NUM_OF_NEIGHBORS; n++) { this->deadParticle[n] = 0; this->deadHalo[n] = 0; } } CosmoHaloFinderP::~CosmoHaloFinderP() { for (unsigned int i = 0; i < this->myMixedHalos.size(); i++) delete this->myMixedHalos[i]; if(this->haloList) { delete [] this->haloList; } if(this->haloStart) { delete [] this->haloStart; } if(this->haloSize) { delete [] this->haloSize; } if(this->haloData) { for (int dim = 0; dim < DIMENSION; dim++) delete this->haloData[dim]; delete [] this->haloData; } } ///////////////////////////////////////////////////////////////////////// // // Set parameters for the serial halo finder // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::setParameters( const string& outName, POSVEL_T _rL, POSVEL_T _deadSz, long _np, int _pmin, POSVEL_T _bb) { // Particles for this processor output to file ostringstream oname, hname; if (this->numProc == 1) { oname << outName; hname << outName; } else { oname << outName << "." << myProc; hname << outName << ".halo." << myProc; } this->outFile = oname.str(); this->outHaloFile = hname.str(); // Halo finder parameters this->np = _np; this->pmin = _pmin; this->bb = _bb; this->boxSize = _rL; this->deadSize = _deadSz; // First version of this code distributed the dead particles on a processor // by taking the x,y,z position and adding or subtracting boxSize in all // combinations. This revised x,y,z was then normalized and added to the // haloData array which was passed to each serial halo finder. // This did not get the same answer as the standalone serial version which // read the x,y,z and normalized without adding or subtracting boxSize first. // Then when comparing distance the normalized "np" was used for subtraction. // By doing things in this order some particles were placed slightly off, // which was enough for particles to be included in halos where they should // not have been. In this first version, since I had placed particles by // subtracting first, I made "periodic" false figuring all particles were // placed where they should go. // // In the second version I normalize the dead particles, even from wraparound, // using the actual x,y,z. So when looking at a processor the alive particles // will appear all together and the wraparound will properly be on the other // side of the box. Combined with doing this is setting "periodic" to true // so that the serial halo finder works as it does in the standalone case // and the normalization and subtraction from np happens in the same order. // // Third version went back to the first version because we need // contiguous locations coming out of the halo finder for the center finder this->haloFinder.np = _np; this->haloFinder.pmin = _pmin; this->haloFinder.bb = _bb; this->haloFinder.rL = _rL; this->haloFinder.periodic = false; this->haloFinder.textmode = "ascii"; // Serial halo finder wants normalized locations on a grid superimposed // on the physical rL grid. Grid size is np and number of particles in // the problem is np^3 this->normalizeFactor = (POSVEL_T)((1.0 * _np) / _rL); #ifndef USE_VTK_COSMO if (this->myProc == MASTER) { cout << endl << "------------------------------------" << endl; cout << "np: " << this->np << endl; cout << "bb: " << this->bb << endl; cout << "pmin: " << this->pmin << endl << endl; } #endif } ///////////////////////////////////////////////////////////////////////// // // Set the particle vectors that have already been read and which // contain only the alive particles for this processor // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::setParticles( vector<POSVEL_T>* xLoc, vector<POSVEL_T>* yLoc, vector<POSVEL_T>* zLoc, vector<POSVEL_T>* xVel, vector<POSVEL_T>* yVel, vector<POSVEL_T>* zVel, vector<POTENTIAL_T>* potential, vector<ID_T>* id, vector<MASK_T>* maskData, vector<STATUS_T>* state) { this->particleCount = (long)xLoc->size(); // Extract the contiguous data block from a vector pointer this->xx = &(*xLoc)[0]; this->yy = &(*yLoc)[0]; this->zz = &(*zLoc)[0]; this->vx = &(*xVel)[0]; this->vy = &(*yVel)[0]; this->vz = &(*zVel)[0]; this->pot = &(*potential)[0]; this->tag = &(*id)[0]; this->mask = &(*maskData)[0]; this->status = &(*state)[0]; } ///////////////////////////////////////////////////////////////////////// // // Execute the serial halo finder on the particles for this processor // Both ALIVE and DEAD particles we collected and normalized into // haloData which is in the form that the serial halo finder wants // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::executeHaloFinder() { // Allocate data pointer which is sent to the serial halo finder this->haloData = new POSVEL_T*[DIMENSION]; for (int dim = 0; dim < DIMENSION; dim++) this->haloData[dim] = new POSVEL_T[this->particleCount]; // Fill it with normalized x,y,z of all particles on this processor for (int p = 0; p < this->particleCount; p++) { this->haloData[0][p] = this->xx[p] * this->normalizeFactor; this->haloData[1][p] = this->yy[p] * this->normalizeFactor; this->haloData[2][p] = this->zz[p] * this->normalizeFactor; } this->haloFinder.setParticleLocations(haloData); this->haloFinder.setNumberOfParticles(this->particleCount); this->haloFinder.setMyProc(this->myProc); this->haloFinder.setOutFile(this->outFile); #ifndef USE_VTK_COSMO cout << "Rank " << setw(3) << this->myProc << " RUNNING SERIAL HALO FINDER on " << particleCount << " particles" << endl; #endif #ifndef USE_SERIAL_COSMO MPI_Barrier(Partition::getComm()); #endif if (this->particleCount > 0) this->haloFinder.Finding(); #ifndef USE_SERIAL_COSMO MPI_Barrier(Partition::getComm()); #endif } ///////////////////////////////////////////////////////////////////////// // // At this point each serial halo finder ran and // the particles handed to it included alive and dead. Get back the // halo tag array and figure out the indices of the particles in each halo // and translate that into absolute particle tags and note alive or dead // // After the serial halo finder has run the halo tag is the INDEX of the // lowest particle in the halo on this processor. It is not the absolute // particle tag id over the entire problem. // // Serial partindex i = 0 haloTag = 0 haloSize = 1 // Serial partindex i = 1 haloTag = 1 haloSize = 1 // Serial partindex i = 2 haloTag = 2 haloSize = 1 // Serial partindex i = 3 haloTag = 3 haloSize = 1 // Serial partindex i = 4 haloTag = 4 haloSize = 2 // Serial partindex i = 5 haloTag = 5 haloSize = 1 // Serial partindex i = 6 haloTag = 6 haloSize = 1616 // Serial partindex i = 7 haloTag = 7 haloSize = 1 // Serial partindex i = 8 haloTag = 8 haloSize = 2 // Serial partindex i = 9 haloTag = 9 haloSize = 1738 // Serial partindex i = 10 haloTag = 10 haloSize = 4 // Serial partindex i = 11 haloTag = 11 haloSize = 1 // Serial partindex i = 12 haloTag = 12 haloSize = 78 // Serial partindex i = 13 haloTag = 12 haloSize = 0 // Serial partindex i = 14 haloTag = 12 haloSize = 0 // Serial partindex i = 15 haloTag = 12 haloSize = 0 // Serial partindex i = 16 haloTag = 16 haloSize = 2 // Serial partindex i = 17 haloTag = 17 haloSize = 1 // Serial partindex i = 18 haloTag = 6 haloSize = 0 // Serial partindex i = 19 haloTag = 6 haloSize = 0 // Serial partindex i = 20 haloTag = 6 haloSize = 0 // Serial partindex i = 21 haloTag = 6 haloSize = 0 // // Halo of size 1616 has the low particle tag of 6 and other members are // 18,19,20,21 indicated by a tag of 6 and haloSize of 0 // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::collectHalos() { // Halo tag returned from the serial halo finder is actually the index // of the particle on this processor. Must map to get to actual tag // which is common information between all processors. this->haloTag = haloFinder.getHaloTag(); // Record the halo size of each particle on this processor this->haloSize = new int[this->particleCount]; this->haloAliveSize = new int[this->particleCount]; this->haloDeadSize = new int[this->particleCount]; // Create a list of particles in any halo by recording the index of the // first particle and having that index give the index of the next particle // Last particle index reports a -1 // List is built by iterating on the tags and storing in opposite order so this->haloList = new int[this->particleCount]; this->haloStart = new int[this->particleCount]; for (int p = 0; p < this->particleCount; p++) { this->haloList[p] = -1; this->haloStart[p] = p; this->haloSize[p] = 0; this->haloAliveSize[p] = 0; this->haloDeadSize[p] = 0; } // Build the chaining mesh of particles in all the halos and count particles buildHaloStructure(); // Mixed halos are saved separately so that they can be merged processMixedHalos(); delete [] this->haloAliveSize; delete [] this->haloDeadSize; } ///////////////////////////////////////////////////////////////////////// // // Examine every particle on this processor, both ALIVE and DEAD // For that particle increment the count for the corresponding halo // which is indicated by the lowest particle index in that halo // Also build the haloList so that we can find all particles in any halo // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::buildHaloStructure() { // Build the chaining mesh so that all particles in a halo can be found // This will include even small halos which will be excluded later for (int p = 0; p < this->particleCount; p++) { // Chain backwards the halo particles // haloStart is the index of the last particle in a single halo in haloList // The value found in haloList is the index of the next particle if (this->haloTag[p] != p) { this->haloList[p] = haloStart[this->haloTag[p]]; this->haloStart[this->haloTag[p]] = p; } // Count particles in the halos if (this->status[p] == ALIVE) this->haloAliveSize[this->haloTag[p]]++; else this->haloDeadSize[this->haloTag[p]]++; this->haloSize[this->haloTag[p]]++; } // Iterate over particles and create a CosmoHalo for halos with size > pmin // only for the mixed halos, not for those completely alive or dead this->numberOfAliveHalos = 0; this->numberOfDeadHalos = 0; this->numberOfMixedHalos = 0; // Only the first particle id for a halo records the size // Succeeding particles which are members of a halo have a size of 0 // Record the start index of any legal halo which will allow the // following of the chaining mesh to identify all particles in a halo this->numberOfHaloParticles = 0; for (ID_T p = 0; p < this->particleCount; p++) { if (this->haloSize[p] >= this->pmin) { if (this->haloAliveSize[p] > 0 && this->haloDeadSize[p] == 0) { this->numberOfAliveHalos++; this->numberOfHaloParticles += this->haloAliveSize[p]; // Save start of legal alive halo for halo properties this->halos.push_back(this->haloStart[p]); this->haloCount.push_back(this->haloAliveSize[p]); } else if (this->haloDeadSize[p] > 0 && this->haloAliveSize[p] == 0) { this->numberOfDeadHalos++; } else { this->numberOfMixedHalos++; CosmoHalo* halo = new CosmoHalo(p, this->haloAliveSize[p], this->haloDeadSize[p]); this->myMixedHalos.push_back(halo); } } } #ifndef USE_VTK_COSMO #ifdef DEBUG cout << "Rank " << this->myProc << " #alive halos = " << this->numberOfAliveHalos << " #dead halos = " << this->numberOfDeadHalos << " #mixed halos = " << this->numberOfMixedHalos << endl; #endif #endif } ///////////////////////////////////////////////////////////////////////// // // Mixed halos (which cross several processors) have been collected // By applying a high/low rule most mixed halos are assigned immediately // to one processor or another. This requires extra processing so that // it is known which neighbor processors share the halo. // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::processMixedHalos() { // Iterate over all particles and add tags to large mixed halos for (ID_T p = 0; p < this->particleCount; p++) { // All particles in the same halo have the same haloTag if (this->haloSize[this->haloTag[p]] >= pmin && this->haloAliveSize[this->haloTag[p]] > 0 && this->haloDeadSize[this->haloTag[p]] > 0) { // Check all each mixed halo to see which this particle belongs to for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { // If the tag of the particle matches the halo ID it belongs if (this->haloTag[p] == this->myMixedHalos[h]->getHaloID()) { // Add the index to that mixed halo. Also record which neighbor // the dead particle is associated with for merging this->myMixedHalos[h]->addParticle( p, this->tag[p], this->status[p]); // For debugging only if (this->status[p] > 0) this->deadHalo[this->status[p]]++; // Do some bookkeeping for the final output // This processor should output all ALIVE particles, unless they // are in a mixed halo that ends up being INVALID // This processor should output none of the DEAD particles, // unless they are in a mixed halo that ends up being VALID // So since this particle is in a mixed halo set it to MIXED // which is going to be one less than ALIVE. Later when we // determine we have a VALID mixed, we'll add one to the status // for every particle turning all into ALIVE // Now when we output we only do the ALIVE particles this->status[p] = MIXED; } } } } // Iterate over the mixed halos that were just created checking to see if // the halo is on the "high" side of the 3D data space or not // If it is on the high side and is shared with one other processor, keep it // If it is on the low side and is shared with one other processor, delete it // Any remaining halos are shared with more than two processors and must // be merged by having the MASTER node decide // for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { int lowCount = 0; int highCount = 0; set<int>* neighbors = this->myMixedHalos[h]->getNeighbors(); set<int>::iterator iter; set<int> haloNeighbor; for (iter = neighbors->begin(); iter != neighbors->end(); ++iter) { if ((*iter) == X1 || (*iter) == Y1 || (*iter) == Z1 || (*iter) == X1_Y1 || (*iter) == Y1_Z1 || (*iter) == Z1_X1 || (*iter) == X1_Y1_Z1) { highCount++; } else { lowCount++; } // Neighbor zones are on what actual processors haloNeighbor.insert(this->neighbor[(*iter)]); } // Halo is kept by this processor and is marked as VALID // May be in multiple neighbor zones, but all the same processor neighbor if (highCount > 0 && lowCount == 0 && haloNeighbor.size() == 1) { this->numberOfAliveHalos++; this->numberOfMixedHalos--; this->myMixedHalos[h]->setValid(VALID); int id = this->myMixedHalos[h]->getHaloID(); int newAliveParticles = this->myMixedHalos[h]->getAliveCount() + this->myMixedHalos[h]->getDeadCount(); this->numberOfHaloParticles += newAliveParticles; // Add this halo to valid halos on this processor for // subsequent halo properties analysis this->halos.push_back(this->haloStart[id]); this->haloCount.push_back(newAliveParticles); // Output trick - since the status of this particle was marked MIXED // when it was added to the mixed CosmoHalo vector, and now it has // been declared VALID, change it to ALIVE even if it was dead before vector<ID_T>* particles = this->myMixedHalos[h]->getParticles(); vector<ID_T>::iterator iter2; for (iter2 = particles->begin(); iter2 != particles->end(); ++iter2) this->status[(*iter2)] = ALIVE; } // Halo will be kept by some other processor and is marked INVALID // May be in multiple neighbor zones, but all the same processor neighbor else if (highCount == 0 && lowCount > 0 && haloNeighbor.size() == 1) { this->numberOfDeadHalos++; this->numberOfMixedHalos--; this->myMixedHalos[h]->setValid(INVALID); } // Remaining mixed halos must be examined by MASTER and stay UNMARKED // Sort them on the tag field for easy comparison else { this->myMixedHalos[h]->setValid(UNMARKED); this->myMixedHalos[h]->sortParticleTags(); } } // If only one processor is running there are no halos to merge if (this->numProc == 1) for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) this->myMixedHalos[h]->setValid(INVALID); } ///////////////////////////////////////////////////////////////////////// // // Using the MASTER node merge all mixed halos so that only one processor // takes credit for them. // // Each processor containing mixed halos that are UNMARKED sends: // Rank // Number of mixed halos to merge // for each halo // id // number of alive (for debugging) // number of dead (for debugging) // first MERGE_COUNT particle ids (for merging) // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::mergeHalos() { // What size integer buffer is needed to hold the largest halo data int maxNumberOfMixed; int numberOfMixed = (int)this->myMixedHalos.size(); #ifdef USE_SERIAL_COSMO maxNumberOfMixed = numberOfMixed; #else MPI_Allreduce((void*) &numberOfMixed, (void*) &maxNumberOfMixed, 1, MPI_INT, MPI_MAX, Partition::getComm()); #endif // If there are no halos to merge, return if (maxNumberOfMixed == 0) return; // Everyone creates the buffer for maximum halos // MASTER will receive into it, others will send from it int haloBufSize = maxNumberOfMixed * MERGE_COUNT * 2; ID_T* haloBuffer = new ID_T[haloBufSize]; // MASTER moves its own mixed halos to mixed halo vector (change index to tag) // then gets messages from others and creates those mixed halos collectMixedHalos(haloBuffer, haloBufSize); #ifndef USE_SERIAL_COSMO MPI_Barrier(Partition::getComm()); #endif // MASTER has all data and runs algorithm to make decisions assignMixedHalos(); #ifndef USE_SERIAL_COSMO MPI_Barrier(Partition::getComm()); #endif // MASTER sends merge results to all processors sendMixedHaloResults(haloBuffer, haloBufSize); #ifndef USE_SERIAL_COSMO MPI_Barrier(Partition::getComm()); #endif // Collect totals for result checking int totalAliveHalos; #ifdef USE_SERIAL_COSMO totalAliveHalos = this->numberOfAliveHalos; #else MPI_Allreduce((void*) &this->numberOfAliveHalos, (void*) &totalAliveHalos, 1, MPI_INT, MPI_SUM, Partition::getComm()); #endif int totalAliveHaloParticles; #ifdef USE_SERIAL_COSMO totalAliveHaloParticles = this->numberOfHaloParticles; #else MPI_Allreduce((void*) &this->numberOfHaloParticles, (void*) &totalAliveHaloParticles, 1, MPI_INT, MPI_SUM, Partition::getComm()); #endif #ifndef USE_VTK_COSMO if (this->myProc == MASTER) { cout << endl; cout << "Total halos found: " << totalAliveHalos << endl; cout << "Total halo particles: " << totalAliveHaloParticles << endl; } #endif for (unsigned int i = 0; i < this->allMixedHalos.size(); i++) delete this->allMixedHalos[i]; delete [] haloBuffer; } ///////////////////////////////////////////////////////////////////////// // // MASTER collects all mixed halos which are UNMARKED from all processors // including its own mixed halos // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::collectMixedHalos #ifdef USE_SERIAL_COSMO (ID_T* , int ) #else (ID_T* haloBuffer, int haloBufSize) #endif { // How many processors have mixed halos int haveMixedHalo = (this->numberOfMixedHalos > 0 ? 1 : 0); int processorsWithMixedHalos; #ifdef USE_SERIAL_COSMO processorsWithMixedHalos = haveMixedHalo; #else MPI_Allreduce((void*) &haveMixedHalo, (void*) &processorsWithMixedHalos, 1, MPI_INT, MPI_SUM, Partition::getComm()); #endif // MASTER moves its own mixed halos to mixed halo vector (change index to tag) // then gets messages from others and creates those mixed halos #ifndef USE_SERIAL_COSMO if (this->myProc == MASTER) { #endif // If MASTER has any mixed halos add them to the mixed halo vector if (this->numberOfMixedHalos > 0) { processorsWithMixedHalos--; for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { if (this->myMixedHalos[h]->getValid() == UNMARKED) { CosmoHalo* halo = new CosmoHalo( this->myMixedHalos[h]->getHaloID(), this->myMixedHalos[h]->getAliveCount(), this->myMixedHalos[h]->getDeadCount()); halo->setRankID(this->myProc); this->allMixedHalos.push_back(halo); // Translate index of particle to tag of particle vector<ID_T>* tags = this->myMixedHalos[h]->getTags(); for (int i = 0; i < MERGE_COUNT; i++) halo->addParticle((*tags)[i]); } } } #ifndef USE_SERIAL_COSMO // Wait on messages from other processors and process int notReceived = processorsWithMixedHalos; MPI_Status mpistatus; while (notReceived > 0) { // Get message containing mixed halo information #ifdef ID_64 MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MPI_ANY_SOURCE, 0, Partition::getComm(), &mpistatus); #else MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MPI_ANY_SOURCE, 0, Partition::getComm(), &mpistatus); #endif // Gather halo information from the message int index = 0; int rank = haloBuffer[index++]; int numMixed = haloBuffer[index++]; for (int m = 0; m < numMixed; m++) { ID_T id = haloBuffer[index++]; int aliveCount = haloBuffer[index++]; int deadCount = haloBuffer[index++]; // Create the CosmoHalo to hold the data and add to vector CosmoHalo* halo = new CosmoHalo(id, aliveCount, deadCount); halo->setRankID(rank); this->allMixedHalos.push_back(halo); for (int t = 0; t < MERGE_COUNT; t++) halo->addParticle(haloBuffer[index++]); } notReceived--; } #ifndef USE_VTK_COSMO cout << "Number of halos to merge: " << this->allMixedHalos.size() << endl; #endif } // Other processors bundle up mixed and send to MASTER else { int index = 0; if (this->numberOfMixedHalos > 0) { haloBuffer[index++] = this->myProc; haloBuffer[index++] = this->numberOfMixedHalos; for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { if (this->myMixedHalos[h]->getValid() == UNMARKED) { haloBuffer[index++] = this->myMixedHalos[h]->getHaloID(); haloBuffer[index++] = this->myMixedHalos[h]->getAliveCount(); haloBuffer[index++] = this->myMixedHalos[h]->getDeadCount(); vector<ID_T>* tags = this->myMixedHalos[h]->getTags(); for (int i = 0; i < MERGE_COUNT; i++) { haloBuffer[index++] = (*tags)[i]; } } } MPI_Request request; #ifdef ID_64 MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, MASTER, 0, Partition::getComm(), &request); #else MPI_Isend(haloBuffer, haloBufSize, MPI_INT, MASTER, 0, Partition::getComm(), &request); #endif } } #endif // USE_SERIAL_COSMO } ///////////////////////////////////////////////////////////////////////// // // MASTER has collected all the mixed halos and decides which processors // will get which by matching them up // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::assignMixedHalos() { // MASTER has all data and runs algorithm to make decisions if (this->myProc == MASTER) { #ifndef USE_VTK_COSMO #ifdef DEBUG for (int m = 0; m < this->allMixedHalos.size(); m++) { vector<ID_T>* tags = this->allMixedHalos[m]->getTags(); cout << "Mixed Halo " << m << ": " << " rank=" << this->allMixedHalos[m]->getRankID() << " index=" << this->allMixedHalos[m]->getHaloID() << " tag=" << (*tags)[0] << " alive=" << this->allMixedHalos[m]->getAliveCount() << " dead=" << this->allMixedHalos[m]->getDeadCount() << endl; } #endif #endif // Iterate over mixed halo vector and match and mark // Remember that I can have 3 or 4 that match for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) { // If this halo has not already been paired with another if (this->allMixedHalos[m]->getPartners()->empty() == true) { // Current mixed halo has the most alive particles so far int numberAlive = this->allMixedHalos[m]->getAliveCount(); int haloWithLeastAlive = m; // Iterate on the rest of the mixed halos unsigned int n = m + 1; while (n < this->allMixedHalos.size()) { // Compare to see if there are a number of tags in common int match = compareHalos(this->allMixedHalos[m], this->allMixedHalos[n]); // Keep track of the mixed halo with the most alive particles if (match > 0) { if (numberAlive > this->allMixedHalos[n]->getAliveCount()) { numberAlive = this->allMixedHalos[n]->getAliveCount(); haloWithLeastAlive = n; } this->allMixedHalos[m]->addPartner(n); this->allMixedHalos[n]->addPartner(m); this->allMixedHalos[m]->setValid(INVALID); this->allMixedHalos[n]->setValid(INVALID); } n++; } // Mixed halo with the least alive particles gets it as VALID this->allMixedHalos[haloWithLeastAlive]->setValid(VALID); } } #ifndef USE_VTK_COSMO #ifdef DEBUG for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) { cout << "Mixed Halo " << m; if (this->allMixedHalos[m]->getValid() == VALID) cout << " is VALID on " << " Rank " << this->allMixedHalos[m]->getRankID(); cout << " partners with "; set<int>::iterator iter; set<int>* partner = this->allMixedHalos[m]->getPartners(); for (iter = partner->begin(); iter != partner->end(); ++iter) cout << (*iter) << " "; cout << endl; } #endif #endif } } ///////////////////////////////////////////////////////////////////////// // // Compare the tags of two halos to see if they are somewhat the same // This needs to be made better // ///////////////////////////////////////////////////////////////////////// int CosmoHaloFinderP::compareHalos(CosmoHalo* halo1, CosmoHalo* halo2) { vector<ID_T>* member1 = halo1->getTags(); vector<ID_T>* member2 = halo2->getTags(); int numFound = 0; for (unsigned int i = 0; i < member1->size(); i++) { bool done = false; unsigned int j = 0; while (!done && (*member1)[i] >= (*member2)[j] && j < member2->size()) { if ((*member1)[i] == (*member2)[j]) { done = true; numFound++; } j++; } } if (numFound == 0) return numFound; else return numFound; } ///////////////////////////////////////////////////////////////////////// // // MASTER sends the result of the merge back to the processors which // label their previously UNMARKED mixed halos as VALID or INVALID // VALID halos have all their particles made ALIVE for output // INVALID halos have all their particles made DEAD because other // processors will report them // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::sendMixedHaloResults #ifdef USE_SERIAL_COSMO (ID_T* haloBuffer, int) #else (ID_T* haloBuffer, int haloBufSize) #endif { #ifndef USE_SERIAL_COSMO // MASTER sends merge results to all processors if (this->myProc == MASTER) { #endif // Share the information // Send to each processor the rank, id, and valid status // Use the same haloBuffer int index = 0; haloBuffer[index++] = (ID_T)this->allMixedHalos.size(); for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) { haloBuffer[index++] = this->allMixedHalos[m]->getRankID(); haloBuffer[index++] = this->allMixedHalos[m]->getHaloID(); haloBuffer[index++] = this->allMixedHalos[m]->getValid(); } #ifndef USE_SERIAL_COSMO MPI_Request request; for (int proc = 1; proc < this->numProc; proc++) { #ifdef ID_64 MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, proc, 0, Partition::getComm(), &request); #else MPI_Isend(haloBuffer, haloBufSize, MPI_INT, proc, 0, Partition::getComm(), &request); #endif } #endif // MASTER must claim the mixed halos assigned to him for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) { if (this->allMixedHalos[m]->getRankID() == MASTER && this->allMixedHalos[m]->getValid() == VALID) { // Locate the mixed halo in question for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { int id = this->myMixedHalos[h]->getHaloID(); if (id == this->allMixedHalos[m]->getHaloID()) { this->myMixedHalos[h]->setValid(VALID); int newAliveParticles = this->myMixedHalos[h]->getAliveCount() + this->myMixedHalos[h]->getDeadCount(); this->numberOfHaloParticles += newAliveParticles; this->numberOfAliveHalos++; // Add this halo to valid halos on this processor for // subsequent halo properties analysis this->halos.push_back(this->haloStart[id]); this->haloCount.push_back(newAliveParticles); // Output trick - since the status of this particle was marked MIXED // when it was added to the mixed CosmoHalo vector, and now it has // been declared VALID, change it to ALIVE even if it was dead vector<ID_T>* particles = this->myMixedHalos[h]->getParticles(); vector<ID_T>::iterator iter; for (iter = particles->begin(); iter != particles->end(); ++iter) this->status[(*iter)] = ALIVE; } } } } #ifndef USE_SERIAL_COSMO } // Other processors wait for result and adjust their halo vector else { MPI_Status mpistatus; #ifdef ID_64 MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MASTER, 0, Partition::getComm(), &mpistatus); #else MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MASTER, 0, Partition::getComm(), &mpistatus); #endif // Unpack information to see which of mixed halos are still valid int index = 0; int numMixed = haloBuffer[index++]; for (int m = 0; m < numMixed; m++) { int rank = haloBuffer[index++]; int id = haloBuffer[index++]; int valid = haloBuffer[index++]; // If this mixed halo is on my processor if (rank == this->myProc && valid == VALID) { // Locate the mixed halo in question for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) { if (this->myMixedHalos[h]->getHaloID() == id) { this->myMixedHalos[h]->setValid(VALID); int newAliveParticles = this->myMixedHalos[h]->getAliveCount() + this->myMixedHalos[h]->getDeadCount(); this->numberOfHaloParticles += newAliveParticles; this->numberOfAliveHalos++; // Add this halo to valid halos on this processor for // subsequent halo properties analysis this->halos.push_back(this->haloStart[id]); this->haloCount.push_back(newAliveParticles); // Output trick - since the status of this particle was marked MIXED // when it was added to the mixed CosmoHalo vector, and now it has // been declared VALID, change it to ALIVE even if it was dead vector<ID_T>* particles = this->myMixedHalos[h]->getParticles(); vector<ID_T>::iterator iter; for (iter = particles->begin(); iter != particles->end(); ++iter) this->status[(*iter)] = ALIVE; } } } } } #endif // USE_SERIAL_COSMO } #ifndef USE_VTK_COSMO ///////////////////////////////////////////////////////////////////////// // // Write the output of the halo finder in the form of the input .cosmo file // // Encoded mixed halo VALID or INVALID into the status array such that // ALIVE particles that are part of an INVALID mixed array will not write // but DEAD particles that are part of a VALID mixed array will be written // // In order to make the output consistent with the serial output where the // lowest tagged particle in a halo owns the halo, work must be done to // identify the lowest tag. This is because as particles are read onto // this processor using the round robin read of every particle, those // particles are no longer in tag order. When the serial halo finder is // called it has to use the index of the particle on this processor which // is no longer the tag. // // p haloTag tag haloSize // 0 0 523 3 // 1 0 522 0 // 2 0 266 0 // // In the above example the halo will be credited to 523 instead of 266 // because the index of 523 is 0 and the index of 266 is 2. So we must // make a pass to map the indexes. // ///////////////////////////////////////////////////////////////////////// void CosmoHaloFinderP::writeTaggedParticles() { // Map the index of the particle on this process to the index of the // particle with the lowest tag value so that the written output refers // to the lowest tag as being the owner of the halo int* mapIndex = new int[this->particleCount]; for (int p = 0; p < this->particleCount; p++) mapIndex[p] = p; // If the tag for the first particle of this halo is bigger than the tag // for this particle, change the map to identify this particle as the lowest for (int p = 0; p < this->particleCount; p++) { if (this->tag[mapIndex[this->haloTag[p]]] > this->tag[p]) mapIndex[this->haloTag[p]] = p; } // Write the tagged particle file ofstream* outStream = new ofstream(this->outFile.c_str(), ios::out); string textMode = "ascii"; char str[1024]; string ascii = "ascii"; if (textMode == "ascii") { // Output all ALIVE particles that were not part of a mixed halo // unless that halo is VALID. Output only the DEAD particles that are // part of a VALID halo. This was encoded when mixed halos were found // so any ALIVE particle is VALID for (int p = 0; p < this->particleCount; p++) { if (this->status[p] == ALIVE) { // Every alive particle appears in the particle output sprintf(str, "%12.4E %12.4E ", this->xx[p], this->vx[p]); *outStream << str; sprintf(str, "%12.4E %12.4E ", this->yy[p], this->vy[p]); *outStream << str; sprintf(str, "%12.4E %12.4E ", this->zz[p], this->vz[p]); *outStream << str; int result = (this->haloSize[this->haloTag[p]] < this->pmin) ? -1: this->tag[mapIndex[this->haloTag[p]]]; sprintf(str, "%12d %12d\n", result, this->tag[p]); *outStream << str; } } } else { // output in COSMO form for (int p = 0; p < this->particleCount; p++) { float fBlock[COSMO_FLOAT]; fBlock[0] = this->xx[p]; fBlock[1] = this->vx[p]; fBlock[2] = this->yy[p]; fBlock[3] = this->vy[p]; fBlock[4] = this->zz[p]; fBlock[5] = this->vz[p]; fBlock[6] = (this->haloSize[this->haloTag[p]] < this->pmin) ? -1.0: 1.0 * this->tag[this->haloTag[p]]; outStream->write((char *)fBlock, COSMO_FLOAT * sizeof(float)); int iBlock[COSMO_INT]; iBlock[0] = this->tag[p]; outStream->write((char *)iBlock, COSMO_INT * sizeof(int)); } } outStream->close(); delete outStream; delete [] mapIndex; } #endif // USE_VTK_COSMO
42,528
13,780
#include "rapidcheck/gen/detail/ExecHandler.h" #include "rapidcheck/Gen.h" namespace rc { namespace gen { namespace detail { ExecHandler::ExecHandler(Recipe &recipe) : m_recipe(recipe) , m_random(m_recipe.random) , m_it(begin(m_recipe.ingredients)) {} rc::detail::Any ExecHandler::onGenerate(const Gen<rc::detail::Any> &gen) { rc::detail::ImplicitScope newScope; Random random = m_random.split(); if (m_it == end(m_recipe.ingredients)) { m_it = m_recipe.ingredients.insert(m_it, gen(random, m_recipe.size)); } auto current = m_it++; return current->value(); } } // namespace detail } // namespace gen } // namespace rc
653
245
#include "TestClass.h" #include "../test.h" namespace aoc2018_day13 { TEST_F(Tests2018Day13, part_1_test) { auto sol = part_1("../2018/day13/input_test.in"); ASSERT_EQ(sol.first, 7); ASSERT_EQ(sol.second, 3); } TEST_F(Tests2018Day13, part_1_real_test) { auto sol = part_1("../2018/day13/input.in"); ASSERT_EQ(sol.first, 103); ASSERT_EQ(sol.second, 85); } TEST_F(Tests2018Day13, part_2_test) { auto sol = part_2("../2018/day13/input_test2.in"); ASSERT_EQ(sol.first, 6); ASSERT_EQ(sol.second, 4); } TEST_F(Tests2018Day13, part_2_real_test) { auto sol = part_2("../2018/day13/input.in"); ASSERT_EQ(sol.first, 88); ASSERT_EQ(sol.second, 64); } }
774
368
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h" #include "base/time/time.h" #include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h" #include "chrome/browser/ui/views/tabs/new_tab_button.h" #include "components/feature_engagement/public/event_constants.h" #include "components/feature_engagement/public/feature_constants.h" #include "components/feature_engagement/public/tracker.h" namespace { const int kDefaultNewTabPromoShowTimeInHours = 2; constexpr char kNewTabObservedSessionTimeKey[] = "new_tab_in_product_help_observed_session_time_key"; } // namespace namespace feature_engagement { NewTabTracker::NewTabTracker(Profile* profile) : FeatureTracker( profile, &kIPHNewTabFeature, kNewTabObservedSessionTimeKey, base::TimeDelta::FromHours(kDefaultNewTabPromoShowTimeInHours)) {} NewTabTracker::~NewTabTracker() = default; void NewTabTracker::OnNewTabOpened() { GetTracker()->NotifyEvent(events::kNewTabOpened); } void NewTabTracker::OnOmniboxNavigation() { GetTracker()->NotifyEvent(events::kOmniboxInteraction); } void NewTabTracker::OnOmniboxFocused() { if (ShouldShowPromo()) ShowPromo(); } void NewTabTracker::OnPromoClosed() { GetTracker()->Dismissed(kIPHNewTabFeature); } void NewTabTracker::OnSessionTimeMet() { GetTracker()->NotifyEvent(events::kNewTabSessionTimeMet); } void NewTabTracker::ShowPromo() { NewTabButton::ShowPromoForLastActiveBrowser(); } void NewTabTracker::CloseBubble() { NewTabButton::CloseBubbleForLastActiveBrowser(); } } // namespace feature_engagement
1,796
609
/* Debounce - v1.1 - November 19, 2014. Arduino library for button debouncing. Clearly based on the debounce example from the site: http://arduino.cc/en/Tutorial/Debounce Created by William Koch. Released into the public domain. */ #include "Debounce.h" // Debounces an input pin. // 50ms as default debounce delay. Debounce::Debounce(byte button, boolean invert, boolean pullup) { pinMode(button, pullup ? INPUT_PULLUP : INPUT); _button = button; _delay = 50; // default delay. _state = _lastState = _reading = (invert ^ digitalRead(_button)); _last = millis(); _count = 0; _invert = invert; } // Debounces an input pin. // Adjustable debounce delay. Debounce::Debounce(byte button, unsigned long delay, boolean invert, boolean pullup) { pinMode(button, pullup ? INPUT_PULLUP : INPUT); _button = button; _delay = delay; // user defined delay. _state = _lastState = _reading = (invert ^ digitalRead(_button)); _last = millis(); _count = 0; _invert = invert; } byte Debounce::read() { _reading = _invert ^ digitalRead(_button); // get current button state. if (_reading != _lastState) { // detect edge: current vs last state: _last = millis(); // store millis if change was detected. _wait = true; // Just to avoid calling millis() unnecessarily. } if (_wait && (millis() - _last) > _delay) { // after the delay has passed: if (_reading != _state) { // if the change wasn't stored yet: _count++; // Stores each change. _state = _reading; // store the button state change. _wait = false; } } _lastState = _reading; return _state; } // Returns the number of times the button was pressed. unsigned int Debounce::count() { Debounce::read(); return _count / 2; // Counts only a full press + release. } void Debounce::resetCount() { _count = 0; return; }
1,991
628
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <map> #include "gflags/gflags.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/field_trial.h" #include "webrtc/test/run_test.h" #include "webrtc/typedefs.h" #include "webrtc/video/loopback.h" namespace webrtc { namespace flags { DEFINE_int32(width, 640, "Video width."); size_t Width() { return static_cast<size_t>(FLAGS_width); } DEFINE_int32(height, 480, "Video height."); size_t Height() { return static_cast<size_t>(FLAGS_height); } DEFINE_int32(fps, 30, "Frames per second."); int Fps() { return static_cast<int>(FLAGS_fps); } DEFINE_int32(min_bitrate, 50, "Minimum video bitrate."); size_t MinBitrate() { return static_cast<size_t>(FLAGS_min_bitrate); } DEFINE_int32(start_bitrate, 300, "Video starting bitrate."); size_t StartBitrate() { return static_cast<size_t>(FLAGS_start_bitrate); } DEFINE_int32(max_bitrate, 800, "Maximum video bitrate."); size_t MaxBitrate() { return static_cast<size_t>(FLAGS_max_bitrate); } int MinTransmitBitrate() { return 0; } // No min padding for regular video. DEFINE_string(codec, "VP8", "Video codec to use."); std::string Codec() { return static_cast<std::string>(FLAGS_codec); } DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost."); int LossPercent() { return static_cast<int>(FLAGS_loss_percent); } DEFINE_int32(link_capacity, 0, "Capacity (kbps) of the fake link. 0 means infinite."); int LinkCapacity() { return static_cast<int>(FLAGS_link_capacity); } DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets."); int QueueSize() { return static_cast<int>(FLAGS_queue_size); } DEFINE_int32(avg_propagation_delay_ms, 0, "Average link propagation delay in ms."); int AvgPropagationDelayMs() { return static_cast<int>(FLAGS_avg_propagation_delay_ms); } DEFINE_int32(std_propagation_delay_ms, 0, "Link propagation delay standard deviation in ms."); int StdPropagationDelayMs() { return static_cast<int>(FLAGS_std_propagation_delay_ms); } DEFINE_bool(logs, false, "print logs to stderr"); DEFINE_string( force_fieldtrials, "", "Field trials control experimental feature code which can be forced. " "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" " will assign the group Enable to field trial WebRTC-FooFeature. Multiple " "trials are separated by \"/\""); DEFINE_int32(num_temporal_layers, 0, "Number of temporal layers. Set to 1-4 to override."); size_t NumTemporalLayers() { return static_cast<size_t>(FLAGS_num_temporal_layers); } } // namespace flags void Loopback() { test::Loopback::Config config{flags::Width(), flags::Height(), flags::Fps(), flags::MinBitrate(), flags::StartBitrate(), flags::MaxBitrate(), 0, // No min transmit bitrate. flags::Codec(), flags::NumTemporalLayers(), flags::LossPercent(), flags::LinkCapacity(), flags::QueueSize(), flags::AvgPropagationDelayMs(), flags::StdPropagationDelayMs(), flags::FLAGS_logs}; test::Loopback loopback(config); loopback.Run(); } } // namespace webrtc int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); google::ParseCommandLineFlags(&argc, &argv, true); webrtc::test::InitFieldTrialsFromString( webrtc::flags::FLAGS_force_fieldtrials); webrtc::test::RunTest(webrtc::Loopback); return 0; }
4,287
1,418
#include <kernel.hpp> #include <os.hpp> #include <kernel/memory.hpp> #define HIGHMEM_LOCATION (1ull << 45) //#define LIU_DEBUG 1 #ifdef LIU_DEBUG #define PRATTLE(fmt, ...) kprintf(fmt, ##__VA_ARGS__) #else #define PRATTLE(fmt, ...) /* fmt */ #endif void kernel::setup_liveupdate() { #if defined(ARCH_x86_64) // highmem location kernel::state().liveupdate_loc = HIGHMEM_LOCATION; #else // other platforms, without paging kernel::state().liveupdate_loc = kernel::state().liveupdate_phys; #endif const size_t size = kernel::state().liveupdate_size; if (size == 0) return; PRATTLE("Setting up LiveUpdate from %p to %p, %zx\n", (void*) kernel::state().liveupdate_phys, (void*) kernel::state().liveupdate_loc, size); #if defined(ARCH_x86_64) os::mem::vmmap().assign_range({ kernel::state().liveupdate_phys, kernel::state().liveupdate_phys + kernel::state().liveupdate_size-1, "LiveUpdate physical" }); // move location to high memory PRATTLE("virtual_move %p to %p (%zu bytes)\n", (void*) kernel::state().liveupdate_phys, (void*) kernel::state().liveupdate_loc, size); os::mem::virtual_move(kernel::state().liveupdate_phys, size, kernel::state().liveupdate_loc, "LiveUpdate"); #endif }
1,302
456
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> //[doc_managed_aligned_allocation #include <boost/interprocess/managed_shared_memory.hpp> #include <cassert> //<- #include "../test/get_process_id_name.hpp" //-> int main() { using namespace boost::interprocess; //Remove shared memory on construction and destruction struct shm_remove { //<- #if 1 shm_remove() { shared_memory_object::remove(test::get_process_id_name()); } ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); } #else //-> shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } //<- #endif //-> } remover; //Managed memory segment that allocates portions of a shared memory //segment with the default management algorithm //<- #if 1 managed_shared_memory managed_shm(create_only, test::get_process_id_name(), 65536); #else //-> managed_shared_memory managed_shm(create_only, "MySharedMemory", 65536); //<- #endif //-> const std::size_t Alignment = 128; //Allocate 100 bytes aligned to Alignment from segment, throwing version void *ptr = managed_shm.allocate_aligned(100, Alignment); //Check alignment assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0); //Deallocate it managed_shm.deallocate(ptr); //Non throwing version ptr = managed_shm.allocate_aligned(100, Alignment, std::nothrow); //Check alignment assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0); //Deallocate it managed_shm.deallocate(ptr); //If we want to efficiently allocate aligned blocks of memory //use managed_shared_memory::PayloadPerAllocation value assert(Alignment > managed_shared_memory::PayloadPerAllocation); //This allocation will maximize the size of the aligned memory //and will increase the possibility of finding more aligned memory ptr = managed_shm.allocate_aligned (3*Alignment - managed_shared_memory::PayloadPerAllocation, Alignment); //Check alignment assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0); //Deallocate it managed_shm.deallocate(ptr); return 0; } //] /* #include <vector> #include <boost/interprocess/managed_windows_shared_memory.hpp> int main() { using namespace boost::interprocess; typedef boost::interprocess:: managed_windows_shared_memory shared_segment; std::vector<void *> ptrs; shared_segment m_segment(create_only, "shmem", 4096*16); try{ while(1){ //Now I have several allocate_aligned operations: ptrs.push_back(m_segment.allocate_aligned(128, 128)); } } catch(...){ m_segment.deallocate(ptrs.back()); ptrs.pop_back(); ptrs.push_back(m_segment.allocate_aligned(128, 128)); } return 0; } */ #include <boost/interprocess/detail/config_end.hpp>
3,507
1,183
/*---------------------------------------------------------------------------------*/ /* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */ /* */ /* NOMAD - Version 4 has been created by */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* The copyright of NOMAD - version 4 is owned by */ /* Charles Audet - Polytechnique Montreal */ /* Sebastien Le Digabel - Polytechnique Montreal */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */ /* NSERC (Natural Sciences and Engineering Research Council of Canada), */ /* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */ /* for Data Valorization) */ /* */ /* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */ /* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */ /* and Exxon Mobil. */ /* */ /* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */ /* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */ /* Exxon Mobil. */ /* */ /* Contact information: */ /* Polytechnique Montreal - GERAD */ /* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ /* e-mail: nomad@gerad.ca */ /* */ /* This program is free software: you can redistribute it and/or modify it */ /* under the terms of the GNU Lesser General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or (at your */ /* option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, but WITHOUT */ /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */ /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License */ /* for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* You can find information on the NOMAD software at www.gerad.ca/nomad */ /*---------------------------------------------------------------------------------*/ #include "../Algos/MeshBase.hpp" NOMAD::MeshBase::MeshBase(const std::shared_ptr<NOMAD::PbParameters> pbParams) : _n(pbParams->getAttributeValue<size_t>("DIMENSION")), _pbParams(pbParams), _initialMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_MESH_SIZE")), _minMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_MESH_SIZE")), _initialFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_FRAME_SIZE")), _minFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_FRAME_SIZE")), _lowerBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("LOWER_BOUND")), _upperBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("UPPER_BOUND")) { init(); } void NOMAD::MeshBase::init() { if ( _pbParams->toBeChecked() ) { throw NOMAD::Exception(__FILE__, __LINE__, "Parameters::checkAndComply() needs to be called before constructing a mesh."); } } NOMAD::ArrayOfDouble NOMAD::MeshBase::getRho(void) const { NOMAD::ArrayOfDouble rho(_n); for (size_t i = 0; i < _n; i++) { rho[i] = getRho(i); } return rho; } NOMAD::ArrayOfDouble NOMAD::MeshBase::getdeltaMeshSize(void) const { NOMAD::ArrayOfDouble delta(_n); for (size_t i = 0; i < _n; i++) { delta[i] = getdeltaMeshSize(i); } return delta; } NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSize() const { NOMAD::ArrayOfDouble Delta(_n); for (size_t i = 0; i < _n; i++) { Delta[i] = getDeltaFrameSize(i); } return Delta; } NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSizeCoarser() const { NOMAD::ArrayOfDouble Delta(_n); for (size_t i = 0; i < _n; i++) { Delta[i] = getDeltaFrameSizeCoarser(i); } return Delta; } void NOMAD::MeshBase::setDeltas(const NOMAD::ArrayOfDouble &deltaMeshSize, const NOMAD::ArrayOfDouble &deltaFrameSize) { for (size_t i = 0; i < _n; i++) { setDeltas(i, deltaMeshSize[i], deltaFrameSize[i]); } } /*-----------------------------------------------------------*/ /* scale and project on the mesh */ /*-----------------------------------------------------------*/ NOMAD::Double NOMAD::MeshBase::scaleAndProjectOnMesh(size_t i, const NOMAD::Double &l) const { // Not defined for MeshBase. throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase."); } NOMAD::ArrayOfDouble NOMAD::MeshBase::scaleAndProjectOnMesh( const NOMAD::Direction &dir) const { // Not defined for MeshBase. throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase."); } NOMAD::Point NOMAD::MeshBase::projectOnMesh(const NOMAD::Point& point, const NOMAD::Point& frameCenter) const { // Not defined for MeshBase. throw NOMAD::Exception(__FILE__, __LINE__, "projectOnMesh() not defined for MeshBase."); } bool NOMAD::MeshBase::verifyPointIsOnMesh(const NOMAD::Point& point, const NOMAD::Point& center) const { bool isOnMesh = true; for (size_t i = 0; i < point.size(); i++) { NOMAD::Double pointRebaseI = point[i]; NOMAD::Double centerI = center[i]; NOMAD::Double deltaI = getdeltaMeshSize(i); if ( (_lowerBound[i].isDefined() && _lowerBound[i] == pointRebaseI) || (_upperBound[i].isDefined() && _upperBound[i] == pointRebaseI)) { isOnMesh = true; } else { if (!centerI.isMultipleOf(deltaI)) { // Rebase point on the mesh centered on center Point pointRebaseI -= centerI; } if (!pointRebaseI.isMultipleOf(deltaI)) { isOnMesh = false; break; } } } return isOnMesh; } std::ostream& NOMAD::operator<<(std::ostream& os, const NOMAD::MeshBase& mesh) { os << "DELTA_MESH_SIZE " << mesh.getdeltaMeshSize() << std::endl; os << "DELTA_FRAME_SIZE " << mesh.getDeltaFrameSize() << std::endl; return os; } std::istream& NOMAD::operator>>(std::istream& is, NOMAD::MeshBase& mesh) { size_t n = mesh.getSize(); // Read line by line std::string name; NOMAD::ArrayOfDouble deltaMeshSize(n), deltaFrameSize(n); while (is >> name && is.good() && !is.eof()) { if ("DELTA_MESH_SIZE" == name) { is >> deltaMeshSize; } else if ("DELTA_FRAME_SIZE" == name) { is >> deltaFrameSize; } else { // Put back name to istream. Maybe there is a simpler way. for (unsigned i = 0; i < name.size(); i++) { is.unget(); } break; } } mesh.setDeltas(deltaMeshSize, deltaFrameSize); return is; }
8,941
2,559
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define mk make_pair void checkmin(int &x,int y){if(x>y) x=y;} void checkmax(int &x,int y){if(x<y) x=y;} void checkmin(ll &x,ll y){if(x>y) x=y;} void checkmax(ll &x,ll y){if(x<y) x=y;} #define out(x) cerr<<#x<<'='<<x<<' ' #define outln(x) cerr<<#x<<'='<<x<<endl #define sz(x) (int)(x).size() inline int read(){ int x=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();} while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } const int N=100005; int n; vector<int> v[N]; ll up[N],down[N],deg[N],ans=0; void dfs1(int u,int f){ up[u]=deg[u]; for(auto &to : v[u]){ if(to==f) continue; dfs1(to,u); up[u]+=up[to]; } down[u]=2*n-2-up[u]; } ll mx1[N],mx2[N]; ll dp[N],dp2[N],sum[N],sz[N]; void dfs2(int u,int f){ dp[u]=down[u]; ll mx=0; sum[u]=down[u]; sz[u]=1; for(auto &to : v[u]){ if(to==f) continue; dfs2(to,u); if(mx1[u]<dp[to]) mx2[u]=mx1[u],mx1[u]=dp[to]; else if(mx2[u]<dp[to]) mx2[u]=dp[to]; sz[u]+=sz[to]; } dp[u]+=mx1[u]; } void dfs3(int u,int f,ll S){ if(f!=-1){ dp2[u]=dp2[f]+(2*n-2-(up[f]-up[u])-S); if(dp[u]==mx1[f]) checkmax(dp2[u],mx2[f]+(2*n-2-(up[f]-up[u])-S)); else checkmax(dp2[u],mx1[f]+(2*n-2-(up[f]-up[u])-S)); } checkmax(ans,dp2[u]); for(auto &to : v[u]){ if(to==f) continue; dfs3(to,u,u==1 ? 0 : S+up[f]-up[u]); } } int main() { n=read(); for(int i=1;i<n;i++){ int x=read(),y=read(); v[x].push_back(y); v[y].push_back(x); deg[x]++; deg[y]++; } dfs1(1,-1); dfs2(1,-1); ans=dp[1]; dfs3(1,-1,0); printf("%.5lf\n",(double)ans); return 0; }
1,820
964
/* You have some sticks with positive integer lengths. You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining. Return the minimum cost of connecting all the given sticks into one stick in this way. Example 1: Input: sticks = [2,4,3] Output: 14 Example 2: Input: sticks = [1,8,3,5] Output: 30 Constraints: 1 <= sticks.length <= 10^4 1 <= sticks[i] <= 10^4 */ class Solution { public: int connectSticks(vector<int>& sticks) { int ans = 0; priority_queue<int, vector<int> ,greater<int>> pq(sticks.begin(), sticks.end()); while (pq.size() != 1){ int s1 = pq.top();pq.pop(); int s2 = pq.top();pq.pop(); pq.push(s1+s2); ans += s1 + s2; } return ans; } };
855
308
#include "Polygon.h" #include <algorithm> #include <numeric> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm.hpp> #include "Vector.h" #include "Vertex.h" Polygon::classification Polygon::classify(const Plane& plane) const { size_t count = points.size(); size_t front = 0, back = 0, onplane = 0; for (const auto& p : points) { auto test = plane.evaluate(p); if (test <= 0) back++; if (test >= 0) front++; if (test == 0) onplane++; } if (onplane == count) return Polygon::classification::onPlane; if (front == count) return Polygon::classification::front; if (back == count) return Polygon::classification::back; return Polygon::classification::spanning; } Vertex Polygon::origin() const { return std::accumulate(points.cbegin(), points.cend(), Vertex{ 0, 0, 0 }) / double(points.size()); } Plane Polygon::plane() const { if(points.size() < 3) return Plane(); return { points[0], points[1], points[2] }; } void Polygon::rotate(const Vertex & point, const Matrix3d & rotmat) { for (auto &p : points) p = p.rotate(point, rotmat); } void Polygon::move(const Vertex & v) { for (auto &p : points) p += v; } void Polygon::moveTo(const Vertex & p) { Vertex dist = p - origin(); for (auto &p : points) p += dist; } void Polygon::scale(const Vertex &scale) { this->scale(origin(), scale); } void Polygon::scale(const Vertex& origin, const Vertex& scale) { for (auto &point : points) { Vertex vec = Vector::diff(origin, point).vec(); vec.x(vec.x() * scale.x()); vec.y(vec.y() * scale.y()); vec.z(vec.z() * scale.z()); point = origin + vec; } } void Polygon::sliceThis(const Plane &plane) { auto[back, front] = slice(plane); if (!back.points.empty() && !front.points.empty()) points = back.points; } std::pair<Polygon, Polygon> Polygon::slice(const Plane& plane) const { auto classification = classify(plane); std::pair<Polygon, Polygon> ret; if (classification != classification::spanning) { if (classification == classification::back) ret.first = *this; else if (classification == classification::front) ret.second = *this; return ret; } size_t prev = 0; for (size_t i = 0; i <= points.size(); i++) { size_t index = i % points.size(); Vertex end = points[index]; auto c = plane.evaluate(end); if (i > 0 && c != 0 && prev != 0 && c != prev) { Vertex start = points[i - 1]; Vector line = Vector::diff(start, end); Vertex intersect = Plane::intersectPoint(plane, line); if (!Vertex::isVertex(intersect)) throw new std::exception("Expected intersection"); ret.first.points.push_back(intersect); ret.second.points.push_back(intersect); } if (i < points.size()) { if (c <= 0) ret.first.points.push_back(end); if (c >= 0) ret.second.points.push_back(end); } prev = c; } return ret; } void Polygon::flip() { std::reverse(points.begin(), points.end()); } void Polygon::roundPoints(size_t precision) { double exp = std::pow(10, precision); std::transform(points.begin(), points.end(), points.begin(), [exp](Vertex v) { v.x(std::round(v.x() * exp) / exp); v.y(std::round(v.y() * exp) / exp); v.z(std::round(v.z() * exp) / exp); return v; }); } Vertex Polygon::intersectPoint(const Vector& line, int flags) const { Plane plane = this->plane(); auto point = Plane::intersectPoint(plane, line); Vertex defaultRet = (flags & lineBoundsFlag::RETURN_END_ON_FAIL) > 0 ? line.end() : Vertex(); flags = flags & lineBoundsFlag::ALLOW_BOTH; if (!Vertex::isVertex(point)) return defaultRet; bool test = testCollision(point); if (!test) return defaultRet; if (flags != lineBoundsFlag::ALLOW_BOTH) { double position = line.calculatePosition(point); if ((lineBoundsFlag::ALLOW_BACK & flags) == 0 && (position < 0 || doubleeq(position, 0))) return defaultRet; if ((lineBoundsFlag::ALLOW_FRONT & flags) == 0 && (position > 1 || doubleeq(position, 1))) return defaultRet; } return point; } bool Polygon::testCollision(const Vertex& point) const { double sum = 0; for (size_t n = 0; n < points.size(); n++) { Vertex p1 = points[n] - point; Vertex p2 = points[(n + 1) % points.size()] - point; double nom = p1.length() * p2.length(); if (doubleeq(nom, 0)) return false; sum += acos(p1.dotProduct(p2) / nom); } return doubleeq(sum, M_PI * 2); } bool Polygon::testCollision(const Vector& line, int flags) const { // Ensure method returns NaN vector if it fails so we can test it. Vertex intersect = intersectPoint(line, flags); if (!Vertex::isVertex(intersect)) return false; return true; } bool Polygon::testCollision(const Polygon& polygon) const { if (&polygon == this) return true; if (points.size() < 3 || polygon.points.size() < 3) return false; Vertex thisNorm = this->plane().normal(); Vertex polyNorm = polygon.plane().normal(); if (thisNorm == polyNorm || thisNorm == -polyNorm) return false; for (size_t n = 0; n < points.size(); n++) { Vector line = Vector::diff(points[n], points[(n + 1) % points.size()]); if (polygon.testCollision(line, ALLOW_NONE)) return true; } for (size_t n = 0; n < polygon.points.size(); n++) { Vector line = Vector::diff(polygon.points[n], polygon.points[(n + 1) % polygon.points.size()]); if (this->testCollision(line, ALLOW_NONE)) return true; } return false; } Polygon::Polygon(const Plane & p) { auto dir = p.closestAxisToNormal(); auto tempV = dir == Vertex::unitZ ? -Vertex::unitY : -Vertex::unitZ; auto normal = p.normal(); auto up = tempV.crossProduct(normal).normalize(); auto right = normal.crossProduct(up).normalize(); points = { p.p1() + right + up, p.p1() - right + up, p.p1() - right - up, p.p1() + right + up }; auto orig = origin(); std::transform(points.begin(), points.end(), points.begin(), [&orig](Vertex v) { return (v - orig).normalize() * 10'000'000.0 + orig; }); } Polygon::Polygon(const std::initializer_list<Vertex>& points) : points(points) { }
5,987
2,354
/* LLVM LOCAL begin (ENTIRE FILE!) */ /* High-level LLVM backend interface Copyright (C) 2005 Free Software Foundation, Inc. Contributed by Evan Cheng (evan.cheng@apple.com) This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //===----------------------------------------------------------------------===// // This is a C++ source file that implements specific llvm alpha ABI. //===----------------------------------------------------------------------===// #include "llvm-abi.h" #include "llvm-internal.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" extern "C" { #include "toplev.h" } static LLVMContext &Context = getGlobalContext(); enum alpha_builtin { ALPHA_BUILTIN_CMPBGE, ALPHA_BUILTIN_EXTBL, ALPHA_BUILTIN_EXTWL, ALPHA_BUILTIN_EXTLL, ALPHA_BUILTIN_EXTQL, ALPHA_BUILTIN_EXTWH, ALPHA_BUILTIN_EXTLH, ALPHA_BUILTIN_EXTQH, ALPHA_BUILTIN_INSBL, ALPHA_BUILTIN_INSWL, ALPHA_BUILTIN_INSLL, ALPHA_BUILTIN_INSQL, ALPHA_BUILTIN_INSWH, ALPHA_BUILTIN_INSLH, ALPHA_BUILTIN_INSQH, ALPHA_BUILTIN_MSKBL, ALPHA_BUILTIN_MSKWL, ALPHA_BUILTIN_MSKLL, ALPHA_BUILTIN_MSKQL, ALPHA_BUILTIN_MSKWH, ALPHA_BUILTIN_MSKLH, ALPHA_BUILTIN_MSKQH, ALPHA_BUILTIN_UMULH, ALPHA_BUILTIN_ZAP, ALPHA_BUILTIN_ZAPNOT, ALPHA_BUILTIN_AMASK, ALPHA_BUILTIN_IMPLVER, ALPHA_BUILTIN_RPCC, ALPHA_BUILTIN_THREAD_POINTER, ALPHA_BUILTIN_SET_THREAD_POINTER, /* TARGET_MAX */ ALPHA_BUILTIN_MINUB8, ALPHA_BUILTIN_MINSB8, ALPHA_BUILTIN_MINUW4, ALPHA_BUILTIN_MINSW4, ALPHA_BUILTIN_MAXUB8, ALPHA_BUILTIN_MAXSB8, ALPHA_BUILTIN_MAXUW4, ALPHA_BUILTIN_MAXSW4, ALPHA_BUILTIN_PERR, ALPHA_BUILTIN_PKLB, ALPHA_BUILTIN_PKWB, ALPHA_BUILTIN_UNPKBL, ALPHA_BUILTIN_UNPKBW, /* TARGET_CIX */ ALPHA_BUILTIN_CTTZ, ALPHA_BUILTIN_CTLZ, ALPHA_BUILTIN_CTPOP, ALPHA_BUILTIN_max }; /* TargetIntrinsicLower - For builtins that we want to expand to normal LLVM * code, emit the code now. If we can handle the code, this macro should emit * the code, return true. */ bool TreeToLLVM::TargetIntrinsicLower(tree exp, unsigned FnCode, const MemRef *DestLoc, Value *&Result, const Type *ResultType, std::vector<Value*> &Ops) { switch (FnCode) { case ALPHA_BUILTIN_UMULH: { Value *Arg0 = Ops[0]; Value *Arg1 = Ops[1]; Arg0 = Builder.CreateZExt(Arg0, IntegerType::get(Context, 128)); Arg1 = Builder.CreateZExt(Arg1, IntegerType::get(Context, 128)); Result = Builder.CreateMul(Arg0, Arg1); Result = Builder.CreateLShr(Result, ConstantInt::get( Type::getInt64Ty(Context), 64)); Result = Builder.CreateTrunc(Result, Type::getInt64Ty(Context)); return true; } case ALPHA_BUILTIN_CMPBGE: { Value *Arg0 = Ops[0]; Value *Arg1 = Ops[1]; Value* cmps[8]; for (unsigned x = 0; x < 8; ++x) { Value* LHS = Builder.CreateLShr(Arg0, ConstantInt::get( Type::getInt64Ty(Context), x*8)); LHS = Builder.CreateTrunc(LHS, Type::getInt8Ty(Context)); Value* RHS = Builder.CreateLShr(Arg1, ConstantInt::get( Type::getInt64Ty(Context), x*8)); RHS = Builder.CreateTrunc(RHS, Type::getInt8Ty(Context)); Value* cmps = Builder.CreateICmpUGE(LHS, RHS); cmps = Builder.CreateIsNotNull(cmps); cmps = Builder.CreateZExt(cmps, Type::getInt64Ty(Context)); cmps = Builder.CreateShl(cmps, ConstantInt::get( Type::getInt64Ty(Context), x)); if (x == 0) Result = cmps; else Result = Builder.CreateOr(Result,cmps); } return true; } case ALPHA_BUILTIN_EXTBL: case ALPHA_BUILTIN_EXTWL: case ALPHA_BUILTIN_EXTLL: case ALPHA_BUILTIN_EXTQL: { unsigned long long mask = 0; switch (FnCode) { case ALPHA_BUILTIN_EXTBL: mask = 0x00000000000000FFULL; break; case ALPHA_BUILTIN_EXTWL: mask = 0x000000000000FFFFULL; break; case ALPHA_BUILTIN_EXTLL: mask = 0x00000000FFFFFFFFULL; break; case ALPHA_BUILTIN_EXTQL: mask = 0xFFFFFFFFFFFFFFFFULL; break; }; Value *Arg0 = Ops[0]; Value *Arg1 = Builder.CreateAnd(Ops[1], ConstantInt::get( Type::getInt64Ty(Context), 7)); Arg0 = Builder.CreateLShr(Arg0, Arg1); Result = Builder.CreateAnd(Arg0, ConstantInt::get( Type::getInt64Ty(Context), mask)); return true; } case ALPHA_BUILTIN_EXTWH: case ALPHA_BUILTIN_EXTLH: case ALPHA_BUILTIN_EXTQH: { unsigned long long mask = 0; switch (FnCode) { case ALPHA_BUILTIN_EXTWH: mask = 0x000000000000FFFFULL; break; case ALPHA_BUILTIN_EXTLH: mask = 0x00000000FFFFFFFFULL; break; case ALPHA_BUILTIN_EXTQH: mask = 0xFFFFFFFFFFFFFFFFULL; break; }; Value *Arg0 = Ops[0]; Value *Arg1 = Builder.CreateAnd(Ops[1], ConstantInt::get( Type::getInt64Ty(Context), 7)); Arg1 = Builder.CreateSub(ConstantInt::get( Type::getInt64Ty(Context), 64), Arg1); Arg0 = Builder.CreateShl(Arg0, Arg1); Result = Builder.CreateAnd(Arg0, ConstantInt::get( Type::getInt64Ty(Context), mask)); return true; } default: break; } return false; } bool llvm_alpha_should_return_scalar_as_shadow(const Type* Ty) { if (Ty && Ty->isIntegerTy(128)) return true; return false; } /* LLVM LOCAL end (ENTIRE FILE!) */
6,426
2,575
#include <iostream> #include <vector> using namespace std; struct three{unsigned long a,b,k;}; unsigned long long averageOperations(vector<three> data, unsigned long long N, unsigned long long M) { long double average=0; for(unsigned long long i=0; i<M; ++i) { unsigned long diff=data[i].b-data[i].a; ++diff; average+=(long double)(data[i].k*diff); } return ((unsigned long long)(average/=N)); } void Run() { //enter values of N && M unsigned long long N,M; cin>>N>>M; //enter value of a,b && k for M operations vector<three> data; for(unsigned long long i=0; i<M; ++i) { three temp; cin>>temp.a>>temp.b>>temp.k; data.push_back(temp); } cout<<averageOperations(data,N,M)<<endl; } int main() { Run(); return 0; }
822
349
// ====================================================================== // // Brad T. Aagaard // U.S. Geological Survey // // ====================================================================== // // C++ application to extract depth (in meters) of specified Vs (m/s) // in the San Francisco Bay Area seismic velocity model at a list of // points. #include "cencalvm/query/VMQuery.h" // USES VMQuery #include "cencalvm/storage/ErrorHandler.h" // USES ErrorHandler #include <stdlib.h> // USES exit() #include <stdio.h> // USES EOF #include <unistd.h> // USES getopt() #include <fstream> // USES std::ifstream, std::ofstream #include <iomanip> // USES setw(), setiosflags(), resetiosflags() #include <iostream> // USES std::cerr #include <sstream> // USES std::ostringstream #include <cassert> // USES assert() #include <stdexcept> // USES std::runtime_error() #include <string> // USES std::string #include <cmath> // USES log(), ceil() // ---------------------------------------------------------------------- // Dump usage to stderr. void usage(void) { // usage std::cerr << "usage: cencalvmisosurface [-h] -v vs -i fileIn -o fileOut -d dbfile\n" << " [-e dbextfile] [-c cacheSize] [-s squashLimit] [-z elevMin]\n" << "\n" << " -v vs Value of shear wave speed for isosurface\n" << " -s squashLim Turn on squashing of topography and set limit\n" << " -i fileIn File containing list of locations: 'lon lat'.\n" << " -o fileOut Output file with locations and elev of isosurface.\n" << " -d dbfile Etree database file to query.\n" << " -e dbextfile Etree extended database file to query.\n" << " -c cacheSize Size of cache in MB to use in query\n" << " -s squashLim Turn on squashing of topography and set limit\n" << " -z elevMin Minimum elevation to consider for isosurface\n" << " -h Display usage and exit.\n"; } // usage // ---------------------------------------------------------------------- // Parse command line arguments. void parseArgs(double* vs, std::string* filenameIn, std::string* filenameOut, std::string* filenameDB, std::string* filenameDBExt, int* cacheSize, double* squashLimit, double* elevMin, int argc, char** argv) { // parseArgs assert(0 != vs); assert(0 != filenameIn); assert(0 != filenameOut); assert(0 != filenameDB); assert(0 != filenameDBExt); assert(0 != cacheSize); assert(0 != squashLimit); assert(0 != elevMin); extern char* optarg; int nparsed = 1; *vs = 0.0; *filenameIn = ""; *filenameOut = ""; *filenameDB = ""; *filenameDBExt = ""; int c = EOF; while ( (c = getopt(argc, argv, "c:d:e:hi:o:s:v:z:") ) != EOF) { switch (c) { // switch case 'c' : // process -c option *cacheSize = atoi(optarg); nparsed += 2; break; case 'd' : // process -d option *filenameDB = optarg; nparsed += 2; break; case 'e' : // process -e option *filenameDBExt = optarg; nparsed += 2; break; case 'h' : // process -h option nparsed += 1; usage(); exit(0); break; case 'i' : // process -i option *filenameIn = optarg; nparsed += 2; break; case 'o' : // process -o option *filenameOut = optarg; nparsed += 2; break; case 's': // process -s option *squashLimit = atof(optarg); nparsed += 2; break; case 'v': // process -v option *vs = atof(optarg); nparsed += 2; break; case 'z': // process -z option *elevMin = atof(optarg); nparsed += 2; break; default : usage(); exit(1); } // switch } // while if (nparsed != argc || 0 == *vs || 0 == filenameIn->length() || 0 == filenameOut->length() || 0 == filenameDB->length()) { usage(); exit(1); } // if } // parseArgs // ---------------------------------------------------------------------- int initialize(cencalvm::query::VMQuery* query, const char* filenameDB, const char* filenameDBExt, const int cacheSize, const double squashLimit, const bool squashOn) { // initialize assert(0 != query); // Get handle to error handler cencalvm::storage::ErrorHandler* errHandler = query->errorHandler(); if (0 == errHandler) { std::cerr << "Could not get handle to error handler.\n"; return 1; } // if // Set database filename query->filename(filenameDB); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if // Set cache size query->cacheSize(cacheSize); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if // Set extended database filename if given if ("" != filenameDBExt) { query->filenameExt(filenameDBExt); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if // Set cache size query->cacheSizeExt(cacheSize); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if } // if // Turn on squashing if requested if (squashOn) { query->squash(true, squashLimit); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if } // if // Open database for querying query->open(); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if // Set query type to maximum resolution query->queryType(cencalvm::query::VMQuery::MAXRES); return 0; } // initialize // ---------------------------------------------------------------------- double queryElev(cencalvm::query::VMQuery* query, const double lon, const double lat) { // queryElev assert(0 != query); // Get handle to error handler cencalvm::storage::ErrorHandler* errHandler = query->errorHandler(); if (0 == errHandler) { std::cerr << "Could not get handle to error handler.\n"; return 1; } // if const int numVals = 1; const char* elevName[] = { "Elevation" }; query->queryVals(elevName, numVals); if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); throw std::runtime_error("Could not get elevation."); } // if double* vals = (numVals > 0) ? new double[numVals] : 0; assert(0 != vals); // Query for elevation at location query->query(&vals, numVals, lon, lat, -5.0e+3); double elev = vals[0]; // Correct elevation for stair-stepping grid const char* valNames[] = { "Vs" }; query->queryVals(valNames, numVals); const int niters = 10; const double dx = -12.5; for (int iter=0; iter < niters; ++iter) { const double elevQ = elev + iter*dx; query->query(&vals, numVals, lon, lat, elevQ); const double vs = vals[0]; if (vs > 0.0) { elev = elevQ; break; } // if } // for delete[] vals; vals = 0; return elev; } // queryElev // ---------------------------------------------------------------------- double searchVs(cencalvm::query::VMQuery* query, const double vsTarget, const double lon, const double lat, const double elevLimitUpper, const double elevLimitLower) { // searchVs assert(0 != query); const int niters = int(1 + ceil(log( (elevLimitUpper - elevLimitLower) / 25.0) / log(2.0))); const int numVals = 1; double* vals = (numVals > 0) ? new double[numVals] : 0; assert(0 != vals); double elevUpper = elevLimitUpper; double elevLower = elevLimitLower; double elevVs = elevLower; // Set values to be returned in queries const char* valNames[] = { "Vs" }; query->queryVals(valNames, numVals); for (int iter=0; iter < niters; ++iter) { query->query(&vals, numVals, lon, lat, elevUpper); const double vsU = vals[0]; query->query(&vals, numVals, lon, lat, elevLower); const double vsL = vals[0]; const double elevMiddle = 0.5 * (elevUpper + elevLower); query->query(&vals, numVals, lon, lat, elevMiddle); const double vsM = vals[0]; if (vsTarget > vsU && vsTarget <= vsM) { elevLower = elevMiddle; elevVs = elevLower; } else if (vsTarget > vsM && vsTarget <= vsL) { elevUpper = elevMiddle; elevVs = elevLower; } else if (vsTarget <= vsU) { elevVs = elevUpper; break; } else if (vsL < 0.0) { elevVs = 1.0e+6; break; } else { std::cerr << "Invalid search range!\n" << "Target vs: " << vsTarget << "\n" << "Location: (" << lon << ", " << lat << ")\n" << "Upper Vs(z=" << elevUpper << "): " << vsU << "\n" << "Lower Vs(z=" << elevLower << "): " << vsL << "\n" << "Middle Vs(z=" << elevMiddle << "): " << vsM << std::endl; exit(1); } // else } // for return elevVs; } // searchVs // ---------------------------------------------------------------------- // main int main(int argc, char* argv[]) { // main double vsTarget = 0.0; std::string filenameIn = ""; std::string filenameOut = ""; std::string filenameDB = ""; std::string filenameDBExt = ""; double queryRes = 0.0; int cacheSize = 128; const double squashDefault = 1.0e+06; double squashLimit = squashDefault; double elevMin = -45.0e+03; // Parse command line arguments parseArgs(&vsTarget, &filenameIn, &filenameOut, &filenameDB, &filenameDBExt, &cacheSize, &squashLimit, &elevMin, argc, argv); // Create query cencalvm::query::VMQuery query; const bool squashOn = squashLimit != squashDefault; initialize(&query, filenameDB.c_str(), filenameDBExt.c_str(), cacheSize, squashLimit, squashOn); // Open input file to read locations std::ifstream fileIn(filenameIn.c_str()); if (!fileIn.is_open()) { std::cerr << "Could not open file '" << filenameIn << "' to read query locations.\n"; return 1; } // if // Open output file to accept data std::ofstream fileOut(filenameOut.c_str()); if (!fileOut.is_open()) { std::cerr << "Could not open file '" << filenameOut << "' to receive query data.\n"; return 1; } // if const int numVals = 1; // Vs // Create array to hold values returned in queries double* vals = (numVals > 0) ? new double[numVals] : 0; // Read location from input file double lon = 0.0; double lat = 0.0; fileIn >> lon >> lat; // Get handle to error handler cencalvm::storage::ErrorHandler* errHandler = query.errorHandler(); if (0 == errHandler) { std::cerr << "Could not get handle to error handler.\n"; return 1; } // if // Continue operating on locations until end of file, reading fails, // or writing fails while (!fileIn.eof() && fileIn.good() && fileOut.good()) { const double elevTopo = queryElev(&query, lon, lat); double elevUpper = (squashOn) ? 0.0 : elevTopo; double elevLower = (squashOn) ? -elevTopo+elevMin : elevMin; const double elevVs = searchVs(&query, vsTarget, lon, lat, elevUpper, elevLower); // If query generated a warning or error, dump message to std::cerr if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); // If query generated an error, then bail out, otherwise reset status if (cencalvm::storage::ErrorHandler::ERROR == errHandler->status()) return 1; errHandler->resetStatus(); } // if const double distIsosurf = (elevVs != 1.0e+6) ? elevTopo - elevVs : -999.0; // Write values returned by query to output file fileOut << std::resetiosflags(std::ios::scientific) << std::setiosflags(std::ios::fixed) << std::setprecision(5) << std::setw(10) << lon << std::setw(9) << lat << std::setprecision(1) << std::setw(9) << distIsosurf << "\n"; // Read in next location from input file fileIn >> lon >> lat; } // while // Close database query.close(); // Close input and output files fileIn.close(); fileOut.close(); // If an error was generated, write error message and bail out if (cencalvm::storage::ErrorHandler::OK != errHandler->status()) { std::cerr << errHandler->message(); return 1; } // if return 0; } // main // End of file
12,394
4,260
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: UnityEngine.Rect #include "UnityEngine/Rect.hpp" // Including type: UnityEngine.Color #include "UnityEngine/Color.hpp" // Including type: UnityEngine.Vector4 #include "UnityEngine/Vector4.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Texture class Texture; // Forward declaring type: Material class Material; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Size: 0xB8 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Internal_DrawTextureArguments // [TokenAttribute] Offset: FFFFFFFF // [VisibleToOtherModulesAttribute] Offset: FFFFFFFF struct Internal_DrawTextureArguments/*, public System::ValueType*/ { public: // public UnityEngine.Rect screenRect // Size: 0x10 // Offset: 0x0 UnityEngine::Rect screenRect; // Field size check static_assert(sizeof(UnityEngine::Rect) == 0x10); // public UnityEngine.Rect sourceRect // Size: 0x10 // Offset: 0x10 UnityEngine::Rect sourceRect; // Field size check static_assert(sizeof(UnityEngine::Rect) == 0x10); // public System.Int32 leftBorder // Size: 0x4 // Offset: 0x20 int leftBorder; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 rightBorder // Size: 0x4 // Offset: 0x24 int rightBorder; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 topBorder // Size: 0x4 // Offset: 0x28 int topBorder; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 bottomBorder // Size: 0x4 // Offset: 0x2C int bottomBorder; // Field size check static_assert(sizeof(int) == 0x4); // public UnityEngine.Color leftBorderColor // Size: 0x10 // Offset: 0x30 UnityEngine::Color leftBorderColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // public UnityEngine.Color rightBorderColor // Size: 0x10 // Offset: 0x40 UnityEngine::Color rightBorderColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // public UnityEngine.Color topBorderColor // Size: 0x10 // Offset: 0x50 UnityEngine::Color topBorderColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // public UnityEngine.Color bottomBorderColor // Size: 0x10 // Offset: 0x60 UnityEngine::Color bottomBorderColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // public UnityEngine.Color color // Size: 0x10 // Offset: 0x70 UnityEngine::Color color; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // public UnityEngine.Vector4 borderWidths // Size: 0x10 // Offset: 0x80 UnityEngine::Vector4 borderWidths; // Field size check static_assert(sizeof(UnityEngine::Vector4) == 0x10); // public UnityEngine.Vector4 cornerRadiuses // Size: 0x10 // Offset: 0x90 UnityEngine::Vector4 cornerRadiuses; // Field size check static_assert(sizeof(UnityEngine::Vector4) == 0x10); // public System.Boolean smoothCorners // Size: 0x1 // Offset: 0xA0 bool smoothCorners; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: smoothCorners and: pass char __padding13[0x3] = {}; // public System.Int32 pass // Size: 0x4 // Offset: 0xA4 int pass; // Field size check static_assert(sizeof(int) == 0x4); // public UnityEngine.Texture texture // Size: 0x8 // Offset: 0xA8 UnityEngine::Texture* texture; // Field size check static_assert(sizeof(UnityEngine::Texture*) == 0x8); // public UnityEngine.Material mat // Size: 0x8 // Offset: 0xB0 UnityEngine::Material* mat; // Field size check static_assert(sizeof(UnityEngine::Material*) == 0x8); // Creating value type constructor for type: Internal_DrawTextureArguments constexpr Internal_DrawTextureArguments(UnityEngine::Rect screenRect_ = {}, UnityEngine::Rect sourceRect_ = {}, int leftBorder_ = {}, int rightBorder_ = {}, int topBorder_ = {}, int bottomBorder_ = {}, UnityEngine::Color leftBorderColor_ = {}, UnityEngine::Color rightBorderColor_ = {}, UnityEngine::Color topBorderColor_ = {}, UnityEngine::Color bottomBorderColor_ = {}, UnityEngine::Color color_ = {}, UnityEngine::Vector4 borderWidths_ = {}, UnityEngine::Vector4 cornerRadiuses_ = {}, bool smoothCorners_ = {}, int pass_ = {}, UnityEngine::Texture* texture_ = {}, UnityEngine::Material* mat_ = {}) noexcept : screenRect{screenRect_}, sourceRect{sourceRect_}, leftBorder{leftBorder_}, rightBorder{rightBorder_}, topBorder{topBorder_}, bottomBorder{bottomBorder_}, leftBorderColor{leftBorderColor_}, rightBorderColor{rightBorderColor_}, topBorderColor{topBorderColor_}, bottomBorderColor{bottomBorderColor_}, color{color_}, borderWidths{borderWidths_}, cornerRadiuses{cornerRadiuses_}, smoothCorners{smoothCorners_}, pass{pass_}, texture{texture_}, mat{mat_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Get instance field reference: public UnityEngine.Rect screenRect UnityEngine::Rect& dyn_screenRect(); // Get instance field reference: public UnityEngine.Rect sourceRect UnityEngine::Rect& dyn_sourceRect(); // Get instance field reference: public System.Int32 leftBorder int& dyn_leftBorder(); // Get instance field reference: public System.Int32 rightBorder int& dyn_rightBorder(); // Get instance field reference: public System.Int32 topBorder int& dyn_topBorder(); // Get instance field reference: public System.Int32 bottomBorder int& dyn_bottomBorder(); // Get instance field reference: public UnityEngine.Color leftBorderColor UnityEngine::Color& dyn_leftBorderColor(); // Get instance field reference: public UnityEngine.Color rightBorderColor UnityEngine::Color& dyn_rightBorderColor(); // Get instance field reference: public UnityEngine.Color topBorderColor UnityEngine::Color& dyn_topBorderColor(); // Get instance field reference: public UnityEngine.Color bottomBorderColor UnityEngine::Color& dyn_bottomBorderColor(); // Get instance field reference: public UnityEngine.Color color UnityEngine::Color& dyn_color(); // Get instance field reference: public UnityEngine.Vector4 borderWidths UnityEngine::Vector4& dyn_borderWidths(); // Get instance field reference: public UnityEngine.Vector4 cornerRadiuses UnityEngine::Vector4& dyn_cornerRadiuses(); // Get instance field reference: public System.Boolean smoothCorners bool& dyn_smoothCorners(); // Get instance field reference: public System.Int32 pass int& dyn_pass(); // Get instance field reference: public UnityEngine.Texture texture UnityEngine::Texture*& dyn_texture(); // Get instance field reference: public UnityEngine.Material mat UnityEngine::Material*& dyn_mat(); }; // UnityEngine.Internal_DrawTextureArguments #pragma pack(pop) static check_size<sizeof(Internal_DrawTextureArguments), 176 + sizeof(UnityEngine::Material*)> __UnityEngine_Internal_DrawTextureArgumentsSizeCheck; static_assert(sizeof(Internal_DrawTextureArguments) == 0xB8); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Internal_DrawTextureArguments, "UnityEngine", "Internal_DrawTextureArguments"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
8,393
2,610
// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -x c++ -emit-llvm < %s \ // RUN: 2>&1 | \ // RUN: FileCheck %s // RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -x c++ -emit-llvm < %s \ // RUN: 2>&1 | \ // RUN: FileCheck %s class test { int a; public: test(int c) { a = c; } ~test() { a = 0; } }; __attribute__((init_priority(2000))) test t(1); // CHECK: fatal error: error in backend: 'init_priority' attribute is not yet supported on AIX
472
206
// Copyright (c) 2018-2018 Josh Blum // SPDX-License-Identifier: BSL-1.0 #pragma once #include "SoapyRemoteConfig.hpp" #include <string> #include <vector> struct SoapyIfAddr { SoapyIfAddr(void); int ethno; //! The ethernet index int ipVer; //! The ip protocol: 4 or 6 bool isUp; //! Is this link active? bool isLoopback; //! Is this a loopback interface? bool isMulticast; //! Does this interface support multicast? std::string name; //! The interface name: ex eth0 std::string addr; //! The ip address as a string }; //! Get a list of IF addrs SOAPY_REMOTE_API std::vector<SoapyIfAddr> listSoapyIfAddrs(void);
646
238
#include "System.Private.CoreLib.h" namespace CoreLib { namespace System { namespace Diagnostics { namespace _ = ::CoreLib::System::Diagnostics; // Method : System.Diagnostics.StackTrace.GetStackFramesInternal(System.Diagnostics.StackFrameHelper, int, bool, System.Exception) void StackTrace::GetStackFramesInternal(_::StackFrameHelper* sfh, int32_t iSkip, bool fNeedFileInfo, ::CoreLib::System::Exception* e) { throw 3221274624U; } }}} namespace CoreLib { namespace System { namespace Diagnostics { namespace _ = ::CoreLib::System::Diagnostics; }}}
587
178
#include <minijson.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static bool Validate(const char* fileName); static bool Validate(const char* fileName) { FILE* f = fopen(fileName, "r"); if (!f) { fprintf(stderr, "ERROR: Failed to open file %s for reading\n", fileName); fflush(stderr); return false; } fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); if (size <= 0) { fprintf(stderr, "ERROR: Empty file %s\n", fileName); fflush(stderr); fclose(f); return false; } if (size > 1024 * 1024 * 20) { fprintf(stderr, "ERROR: File too large: %s\n", fileName); fflush(stderr); fclose(f); return false; } char* data = (char*)malloc(size + 1); if (fread(data, 1, size, f) != (size_t)size) { fprintf(stderr, "ERROR: Failed to read %d bytes from file %s\n", (int)size, fileName); fflush(stderr); fclose(f); free(data); return false; } fclose(f); f = NULL; try { minijson::CParser parser; minijson::CEntity* entity = parser.Parse(data); delete entity; } catch (const minijson::CParseErrorException& ex) { if (ex.Line() > 0) { fprintf(stderr, "ERROR: Parse error in file %s at or after line %d column %d (position %d in file):\n----------\n%s----------\nException: %s\n", fileName, ex.Line(), ex.Column(), ex.Position(), ex.Surrounding().c_str(), ex.Message().c_str()); } else { fprintf(stderr, "ERROR: Parse error in file %s at or after position %d, exception: %s\n", fileName, (int)ex.Position(), ex.Message().c_str()); } fflush(stderr); free(data); return false; } catch (const minijson::CException& ex) { fprintf(stderr, "ERROR: Failed to parse file %s, exception: %s\n", fileName, ex.Message().c_str()); fflush(stderr); free(data); return false; } free(data); fprintf(stdout, "SUCCESSFULLY parsed %s\n", fileName); fflush(stdout); return true; } int main(int argc, char** argv) { bool ok = true; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { fprintf(stdout, "Usage: %s <files>\n", argv[0]); fprintf(stdout, " This tool will attempt to parse all specified JSON files and report any parse errors\n"); fflush(stdout); return 0; } } for (int i = 1; i < argc; i++) { if (!Validate(argv[i])) { ok = false; } } if (ok) { return 0; } return 1; }
2,794
988
//-------------------------------------------------------------------------------------- // pch.cpp // // Include the standard header and generate the precompiled header. // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #pragma warning(disable : 4996) #include "pch.h"
423
98
#include "quipper_lib.h" #include "compat/test.h" namespace { TEST(QuipperLibTest, ValidOldPerfCommandLine) { int argc = 6; const char* argv[] = {"quipper", "10", "perf", "record", "-e", "cycles"}; std::vector<string> perf_args; int perf_duration = 0; EXPECT_TRUE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args)); EXPECT_EQ(10, perf_duration); for (int i = 0; i < perf_args.size(); ++i) { EXPECT_EQ(argv[i + 2], perf_args[i]); } } TEST(QuipperLibTest, InValidOldPerfCommandLine) { int argc = 6; const char* argv[] = { "quipper", "--duration", "10", "--perf_path", "perf", "--output_file", "file", "-- record -e cycles"}; std::vector<string> perf_args; int perf_duration = 0; EXPECT_FALSE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args)); } } // namespace
841
352
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_compiler.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/types.pb.h" namespace tensorflow { namespace { class ConstOp : public XlaOpKernel { public: explicit ConstOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { const TensorProto* proto = nullptr; OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto)); proto_ = *proto; OP_REQUIRES( ctx, ctx->output_type(0) == proto_.dtype(), errors::InvalidArgument("Type mismatch between value (", DataTypeString(proto_.dtype()), ") and dtype (", DataTypeString(ctx->output_type(0)), ")")); OP_REQUIRES_OK(ctx, TensorShape::IsValidShape(proto_.tensor_shape())); } void Compile(XlaOpKernelContext* ctx) override { TensorShape shape(proto_.tensor_shape()); xla::XlaBuilder* b = ctx->builder(); // To avoid blowups for large constants filled with the same value, // recognize that case and emit a scalar broadcast instead. if (shape.num_elements() > 1) { switch (proto_.dtype()) { case DT_BOOL: if (proto_.bool_val_size() == 1) { ctx->SetOutput( 0, xla::Broadcast(xla::ConstantR0<bool>(b, proto_.bool_val(0)), shape.dim_sizes())); return; } break; case DT_FLOAT: if (proto_.float_val_size() == 1) { ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<float>( b, proto_.float_val(0)), shape.dim_sizes())); return; } break; case DT_DOUBLE: if (proto_.double_val_size() == 1) { ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<double>( b, proto_.double_val(0)), shape.dim_sizes())); return; } break; case DT_COMPLEX64: if (proto_.scomplex_val_size() == 2) { ctx->SetOutput( 0, xla::Broadcast(xla::ConstantR0<xla::complex64>( b, xla::complex64(proto_.scomplex_val(0), proto_.scomplex_val(1))), shape.dim_sizes())); return; } break; case DT_COMPLEX128: if (proto_.scomplex_val_size() == 2) { ctx->SetOutput( 0, xla::Broadcast(xla::ConstantR0<xla::complex128>( b, xla::complex128(proto_.dcomplex_val(0), proto_.dcomplex_val(1))), shape.dim_sizes())); return; } break; case DT_INT32: if (proto_.int_val_size() == 1) { ctx->SetOutput( 0, xla::Broadcast(xla::ConstantR0<int32>(b, proto_.int_val(0)), shape.dim_sizes())); return; } break; case DT_INT64: if (proto_.int64_val_size() == 1) { ctx->SetOutput(0, xla::Broadcast(xla::ConstantR0<int64>( b, proto_.int64_val(0)), shape.dim_sizes())); return; } break; default: break; } } // General case Tensor tensor(proto_.dtype()); OP_REQUIRES(ctx, tensor.FromProto(cpu_allocator(), proto_), errors::InvalidArgument("Cannot parse tensor from proto: ", proto_.DebugString())); ctx->SetConstantOutput(0, tensor); } private: TensorProto proto_; TF_DISALLOW_COPY_AND_ASSIGN(ConstOp); }; // XLA_* devices also register a "real" Const operator so we suppress the // dummy operator using CompilationOnly(). REGISTER_XLA_OP(Name("Const").CompilationOnly(), ConstOp); } // namespace } // namespace tensorflow
5,295
1,587
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // // This file is part of Bytecoin. // // Bytecoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>. #include "CryptoNoteCore/Transactions/TransactionUtils.h" #include <unordered_set> #include <numeric> #include <iterator> #include <exception> #include <algorithm> #include <Xi/Exceptions.hpp> #include <crypto/crypto.h> #include "CryptoNoteCore/Account.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/Transactions/TransactionExtra.h" using namespace Crypto; namespace CryptoNote { bool checkInputsKeyimagesDiff(const CryptoNote::TransactionPrefix& tx) { std::unordered_set<Crypto::KeyImage> ki; for (const auto& in : tx.inputs) { if (auto keyInput = std::get_if<KeyInput>(&in)) { if (!ki.insert(keyInput->keyImage).second) return false; } } return true; } // TransactionInput helper functions size_t getRequiredSignaturesCount(const TransactionInput& in) { if (auto keyInput = std::get_if<KeyInput>(&in)) { return keyInput->outputIndices.size(); } return 0; } uint64_t getTransactionInputAmount(const TransactionInput& in) { if (auto keyInput = std::get_if<KeyInput>(&in)) { return keyInput->amount; } else { return 0; } } uint64_t getTransactionInputAmount(const Transaction& transaction) { return std::accumulate(transaction.inputs.begin(), transaction.inputs.end(), 0ULL, [](uint64_t acc, const auto& input) { return acc + getTransactionInputAmount(input); }); } uint64_t getTransactionOutputAmount(const TransactionOutput& out) { if (const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(out))) { return amountOutput->amount; } else { return 0ULL; } } uint64_t getTransactionOutputAmount(const Transaction& transaction) { return std::accumulate(transaction.outputs.begin(), transaction.outputs.end(), 0ULL, [](uint64_t acc, const auto& out) { return acc + getTransactionOutputAmount(out); }); } boost::optional<KeyImage> getTransactionInputKeyImage(const TransactionInput& input) { if (auto keyInput = std::get_if<KeyInput>(&input)) { return boost::optional<KeyImage>{keyInput->keyImage}; } else { return boost::optional<KeyImage>{}; } } std::vector<KeyImage> getTransactionKeyImages(const Transaction& transaction) { std::vector<KeyImage> reval{}; reval.reserve(transaction.inputs.size()); for (const auto& input : transaction.inputs) { auto keyImage = getTransactionInputKeyImage(input); if (keyImage) { reval.push_back(*keyImage); } } return reval; } std::vector<PublicKey> getTransactionOutputKeys(const Transaction& transaction) { std::vector<PublicKey> keys; keys.reserve(transaction.outputs.size()); for (const auto& output : transaction.outputs) { const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(output)); if (amountOutput == nullptr) { continue; } const auto keyTarget = std::get_if<KeyOutput>(std::addressof(amountOutput->target)); if (keyTarget == nullptr) { continue; } keys.emplace_back(keyTarget->key); } return keys; } TransactionTypes::InputType getTransactionInputType(const TransactionInput& in) { if (std::holds_alternative<KeyInput>(in)) { return TransactionTypes::InputType::Key; } if (std::holds_alternative<BaseInput>(in)) { return TransactionTypes::InputType::Generating; } return TransactionTypes::InputType::Invalid; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.inputs.size() <= index) { throw std::runtime_error("Transaction input index out of range"); } return transaction.inputs[index]; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::InputType type) { const auto& input = getInputChecked(transaction, index); if (getTransactionInputType(input) != type) { throw std::runtime_error("Unexpected transaction input type"); } return input; } // TransactionOutput helper functions TransactionTypes::OutputType getTransactionOutputType(const TransactionOutput& out) { if (std::holds_alternative<TransactionAmountOutput>(out)) { return TransactionTypes::OutputType::Amount; } return TransactionTypes::OutputType::Invalid; } TransactionTypes::OutputTargetType getTransactionOutputTargetType(const TransactionOutputTarget& out) { if (std::holds_alternative<KeyOutput>(out)) { return TransactionTypes::OutputTargetType::Key; } return TransactionTypes::OutputTargetType::Invalid; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.outputs.size() <= index) { throw std::runtime_error("Transaction output index out of range"); } return transaction.outputs[index]; } const TransactionOutputTarget& getOutputTargetChecked(const TransactionOutput& out) { if (!std::holds_alternative<TransactionAmountOutput>(out)) { throw std::runtime_error{"Unexpected transaction output type"}; } return std::get<TransactionAmountOutput>(out).target; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::OutputType outType, TransactionTypes::OutputTargetType type) { const auto& output = getOutputChecked(transaction, index); const auto outputType = getTransactionOutputType(output); if (outputType != outType) { throw std::runtime_error{"Unexpected transaction output type"}; } const auto& target = getOutputTargetChecked(output); if (getTransactionOutputTargetType(target) != type) { throw std::runtime_error("Unexpected transaction output target type"); } return output; } bool isOutToKey(const Crypto::PublicKey& spendPublicKey, const Crypto::PublicKey& outKey, const Crypto::KeyDerivation& derivation, size_t keyIndex) { Crypto::PublicKey pk; derive_public_key(derivation, keyIndex, spendPublicKey, pk); return pk == outKey; } bool findOutputsToAccount(const CryptoNote::TransactionPrefix& transaction, const AccountPublicAddress& addr, const SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount) { using namespace Xi; AccountKeys keys; keys.address = addr; // only view secret key is used, spend key is not needed keys.viewSecretKey = viewSecretKey; ::Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(transaction.extra); amount = 0; size_t keyIndex = 0; uint32_t outputIndex = 0; ::Crypto::KeyDerivation derivation; generate_key_derivation(txPubKey, keys.viewSecretKey, derivation); for (const TransactionOutput& o : transaction.outputs) { exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<TransactionAmountOutput>(o)); const auto& amountOutput = std::get<TransactionAmountOutput>(o); exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<KeyOutput>(amountOutput.target)); const auto& keyOutput = std::get<KeyOutput>(amountOutput.target); if (is_out_to_acc(keys, keyOutput, derivation, keyIndex)) { out.push_back(outputIndex); amount += amountOutput.amount; } ++keyIndex; ++outputIndex; } return true; } std::vector<uint32_t> getTransactionInputIndices(const KeyInput& input) { std::vector<uint32_t> indices{}; if (input.outputIndices.empty()) return indices; indices.resize(input.outputIndices.size()); indices[0] = input.outputIndices[0]; for (size_t i = 1; i < input.outputIndices.size(); ++i) { indices[i] = indices[i - 1] + input.outputIndices[i]; } return indices; } } // namespace CryptoNote
8,561
2,585
#include <iostream> using namespace std; class hello { public: int var; hello() { } hello(int a) : var(a) { } hello operator+(hello &obj) { hello res; res.var = this->var+obj.var; return res; } }; main() { hello obj1(12), obj2(55); hello res = obj1+obj2; cout<<res.var<<endl; }
337
158
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/medialive/model/ListOfferingsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::MediaLive::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListOfferingsResult::ListOfferingsResult() { } ListOfferingsResult::ListOfferingsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListOfferingsResult& ListOfferingsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } if(jsonValue.ValueExists("offerings")) { Array<JsonView> offeringsJsonList = jsonValue.GetArray("offerings"); for(unsigned offeringsIndex = 0; offeringsIndex < offeringsJsonList.GetLength(); ++offeringsIndex) { m_offerings.push_back(offeringsJsonList[offeringsIndex].AsObject()); } } return *this; }
1,258
437
#include <shogun/base/init.h> #include <shogun/features/RandomFourierDotFeatures.h> #include <shogun/kernel/GaussianKernel.h> #include <shogun/kernel/normalizer/SqrtDiagKernelNormalizer.h> #include <shogun/classifier/svm/LibLinear.h> #include <shogun/classifier/svm/SVMOcas.h> #include <shogun/classifier/svm/LibSVM.h> #include <shogun/labels/BinaryLabels.h> #include <shogun/evaluation/PRCEvaluation.h> #include <shogun/lib/Time.h> #include <stdio.h> #include <ctime> using namespace shogun; /** Code that compares the times needed to train * a linear svm using the RandomFourierDotFeatures class * vs a non-linear svm using the Gaussian Kernel. */ int main(int argv, char** argc) { init_shogun_with_defaults(); int32_t dims[] = {10, 100, 1000}; int32_t vecs[] = {10000, 100000, 1000000}; CTime* timer = new CTime(false); float64_t epsilon = 0.001; float64_t lin_C = 0.1; float64_t non_lin_C = 0.1; CPRCEvaluation* evaluator = new CPRCEvaluation(); CSqrtDiagKernelNormalizer* normalizer = new CSqrtDiagKernelNormalizer(true); SG_REF(normalizer); for (index_t d=0; d<4; d++) { int32_t num_dim = dims[d]; SG_SPRINT("Starting experiment for number of dimensions = %d\n", num_dim); for (index_t v=0; v<3; v++) { int32_t num_vecs = vecs[v]; SG_SPRINT(" Using %d examples\n", num_vecs); SGMatrix<float64_t> mat(num_dim, num_vecs); SGVector<float64_t> labs(num_vecs); for (index_t i=0; i<num_vecs; i++) { for (index_t j=0; j<num_dim; j++) { if ((i+j)%2==0) { labs[i] = -1; mat(j,i) = CMath::random(0,1) + 0.5; } else { labs[i] = 1; mat(j,i) = CMath::random(0,1) - 0.5; } } } SGVector<float64_t> params(1); params[0] = 8; SG_SPRINT(" Using kernel_width = %f\n", params[0]); CDenseFeatures<float64_t>* dense_feats = new CDenseFeatures<float64_t>(mat); SG_REF(dense_feats); CBinaryLabels* labels = new CBinaryLabels(labs); SG_REF(labels); /** LibLinear SVM using RandomFourierDotFeatures */ int32_t D[] = {50, 100, 300, 1000}; for (index_t d=0; d<4; d++) { CRandomFourierDotFeatures* r_feats = new CRandomFourierDotFeatures( dense_feats, D[d], KernelName::GAUSSIAN, params); //CLibLinear* lin_svm = new CLibLinear(C, r_feats, labels); CSVMOcas* lin_svm = new CSVMOcas(lin_C, r_feats, labels); lin_svm->set_epsilon(epsilon); clock_t t = clock(); timer->start(); lin_svm->train(); t = clock() - t; timer->stop(); SG_SPRINT("\tSVMOcas using RFDotFeatures(D=%d) finished training. Took %fs (or %fs), ", D[d], timer->time_diff_sec(), (float64_t) t /CLOCKS_PER_SEC); t = clock(); timer->start(); CBinaryLabels* predicted = CLabelsFactory::to_binary(lin_svm->apply()); timer->stop(); t = clock() - t; float64_t auPRC = evaluator->evaluate(predicted, labels); SG_SPRINT("SVMOcas auPRC=%f (Applying took %fs (%fs)\n", auPRC, timer->time_diff_sec(), (float64_t) t / CLOCKS_PER_SEC); SG_UNREF(lin_svm); SG_UNREF(predicted); } /** End of LibLinear code */ /** LibSVM using Gaussian Kernel */ CGaussianKernel* kernel = new CGaussianKernel(dense_feats, dense_feats, params[0]); //kernel->set_normalizer(normalizer); CLibSVM* svm = new CLibSVM(non_lin_C, kernel, labels); svm->set_epsilon(epsilon); clock_t t = clock(); timer->start(); svm->train(); t = clock() - t; timer->stop(); SG_SPRINT("\tLibSVM using GaussianKernel finished training. Took %fs (or %fs), ", timer->time_diff_sec(), (float64_t) t /CLOCKS_PER_SEC); t = clock(); timer->start(); CBinaryLabels* predicted = CLabelsFactory::to_binary(svm->apply()); timer->stop(); t = clock() - t; float64_t auPRC = evaluator->evaluate(predicted, labels); SG_SPRINT("LibSVM auPRC=%f (Applying took %fs (%fs)\n", auPRC, timer->time_diff_sec(), (float64_t) t / CLOCKS_PER_SEC); SG_UNREF(svm); SG_UNREF(predicted); /** End of LibSVM code */ SG_UNREF(labels); SG_UNREF(dense_feats); } } SG_UNREF(timer); SG_UNREF(evaluator); SG_UNREF(normalizer); exit_shogun(); }
4,135
2,001