Why can't this code run, is it a bug in Kotlin? - kotlin

I write a piece of code, then compile it with no errors. but when I run, it throws an exception (java.lang.NoClassDefFoundError: TesKt$test$1$1).
Is this a language bug?
private fun test(block:()->Unit) = arrayOf(1).map {
object {
fun print() {
println("Hello print")
block()
}
}
}
fun main(args: Array<String>) {
val array = test{println("Hello main")}
array[0].print()
}

I'm going to conclude that it's a bug in the Kotlin compiler. I played a lot with this code and looked into the compiled bytecode. It seems the compiler is losing some information about the anonymous class which is defined by object.
If we add a type to that object, then it works fine:
interface Printable {
fun print()
}
private fun test(block:()->Unit): List<Printable> {
return arrayOf(1).map {
object: Printable {
override fun print() {
println("Hello print")
block()
}
}
}
}
fun main(args: Array<String>) {
val array = test{println("Hello main")}
array[0].print()
}
As you can see, I only defined a simple Printable interface and annotated the anonymous class with this interface.
Let's call your code: version A, and this code of mine: Version B.
I compiled code A and then decompiled it to Java. Here's the result:
import TestKt.test.1.1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import kotlin.Metadata;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
#Metadata(
mv = {1, 1, 15},
bv = {1, 0, 3},
k = 2,
d1 = {"\u0000#\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u0011\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010 \n\u0002\b\u0002\n\u0002\u0018\u0002*\u0001\b\u001a\u0019\u0010\u0000\u001a\u00020\u00012\f\u0010\u0002\u001a\b\u0012\u0004\u0012\u00020\u00040\u0003¢\u0006\u0002\u0010\u0005\u001a\u001c\u0010\u0006\u001a\b\u0012\u0004\u0012\u00020\b0\u00072\f\u0010\t\u001a\b\u0012\u0004\u0012\u00020\u00010\nH\u0002"},
d2 = {"main", "", "args", "", "", "([Ljava/lang/String;)V", "test", "", "TestKt$test$1$1", "block", "Lkotlin/Function0;"}
)
public final class TestKt {
/*#19:*/private static final List<1> test(Function0<Unit> block) {
Object[] $this$map$iv = new Integer[]{1};
int $i$f$map = false;
Collection destination$iv$iv = (Collection)(new ArrayList($this$map$iv.length));
int $i$f$mapTo = false;
Integer[] var6 = $this$map$iv;
int var7 = $this$map$iv.length;
for(int var8 = 0; var8 < var7; ++var8) {
Object item$iv$iv = var6[var8];
int it = ((Number)item$iv$iv).intValue();
int var11 = false;
/*#31:*/ TestKt.test..inlined.map.lambda.1 var13 = new TestKt.test..inlined.map.lambda.1(block);
destination$iv$iv.add(var13);
}
return (List)destination$iv$iv;
}
public static final void main(#NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
List array = test((Function0)TestKt.main.array.1.INSTANCE);
/*#41:*/((1)array.get(0)).print();
}
}
And this is the result of the same process for code B:
import TestKt.test..inlined.map.lambda.1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import kotlin.Metadata;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
#Metadata(
mv = {1, 1, 15},
bv = {1, 0, 3},
k = 2,
d1 = {"\u0000\"\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u0011\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010 \n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\u001a\u0019\u0010\u0000\u001a\u00020\u00012\f\u0010\u0002\u001a\b\u0012\u0004\u0012\u00020\u00040\u0003¢\u0006\u0002\u0010\u0005\u001a\u001c\u0010\u0006\u001a\b\u0012\u0004\u0012\u00020\b0\u00072\f\u0010\t\u001a\b\u0012\u0004\u0012\u00020\u00010\nH\u0002"},
d2 = {"main", "", "args", "", "", "([Ljava/lang/String;)V", "test", "", "LPrintable;", "block", "Lkotlin/Function0;"}
)
public final class TestKt {
/*#19:*/private static final List<Printable> test(Function0<Unit> block) {
Object[] $this$map$iv = new Integer[]{1};
int $i$f$map = false;
Collection destination$iv$iv = (Collection)(new ArrayList($this$map$iv.length));
int $i$f$mapTo = false;
Integer[] var6 = $this$map$iv;
int var7 = $this$map$iv.length;
for(int var8 = 0; var8 < var7; ++var8) {
Object item$iv$iv = var6[var8];
int it = ((Number)item$iv$iv).intValue();
int var11 = false;
/*#31:*/ 1 var13 = new 1(block);
destination$iv$iv.add(var13);
}
return (List)destination$iv$iv;
}
public static final void main(#NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
List array = test((Function0)TestKt.main.array.1.INSTANCE);
/*#41:*/((Printable)array.get(0)).print();
}
}
As you can see, the only differences are in the first line, as well as line numbers 19, 31 and 41 (commented like #19: and so on).
In code A a type (strangely) with the name of 1 is expected. But this type 1, which is packaged as TestKt.test.1.1, is not found and so you got your error (NoClassDefFoundError: TesKt$test$1$1).
Inn code B, however, a more clear type of Printable is expected and found.
If the compiler had compiled the very first line of code A just like code B (import TestKt.test..inlined.map.lambda.1; instead of import TestKt.test.1.1;) then your code would have worked.

Related

TFlite model slow/no inference

I am trying to get an opencv pipeline working on a REV control hub for FTC with tensorflow. I have a trained TFLite model and I am processing it and retrieving the confidences. It works well on an android device as an android app, but it doesn't seem to work with the REV control hub. You may see that I have a variable named here2, this always evaluates to false unless it is before model.process, showing that the model doesn't get processed. Any idea why this is?
package org.firstinspires.ftc.teamcode.vision;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.ml.ModelUnquant;
import org.opencv.core.Mat;
import org.openftc.easyopencv.OpenCvPipeline;
import org.opencv.android.Utils;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class CircularTagDetectionPipeline extends OpenCvPipeline {
Telemetry telemetry;
public boolean done = false;
public int pos = -1;
public boolean here1 = false;
public boolean here2 = false;
public CircularTagDetectionPipeline(Telemetry telemetry){
this.telemetry = telemetry;
}
#Override
public Mat processFrame(Mat input) {
Bitmap bmp = Bitmap.createBitmap(input.width(), input.height(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(input, bmp);
pos = classifyImage(bmp);
done = true;
return input;
}
public int classifyImage(Bitmap image){
try {
image = Bitmap.createScaledBitmap(image, 224, 224, false);
//image.setWidth(224);
//image.setHeight(224);
ModelUnquant model = ModelUnquant.newInstance(FtcRobotControllerActivity.contextFTC);
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*imageWidth*imageHeight*3);
byteBuffer.order(ByteOrder.nativeOrder());
int[] intValues = new int[imageWidth*imageHeight];
image.getPixels(intValues, 0, imageWidth,0, 0, imageWidth, imageHeight);
int pixel = 0;
for(int i = 0; i < imageWidth; i++){
for(int j = 0; j < imageHeight; j++){
int val = intValues[pixel++];
byteBuffer.putFloat(((val >> 16)&0xFF)*(1.f/255.f));
byteBuffer.putFloat(((val >> 8)&0xFF)*(1.f/255.f));
byteBuffer.putFloat((val & 0xFF)*(1.f/255.f));
}
telemetry.addLine(i+"");
}
here1 = true;
inputFeature0.loadBuffer(byteBuffer);
ModelUnquant.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
here2 = true;
float[] confidences = outputFeature0.getFloatArray();
int maxPos = 0;
float maxConfidence = 0;
for(int i = 0; i < confidences.length; i++){
if(confidences[i] > maxConfidence){
maxConfidence = confidences[i];
maxPos = i;
}
}
String[] classes = {"1", "2", "3"};
int posReturn = Integer.parseInt(classes[maxPos]);
model.close();
return posReturn;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
}
I am expecting the robot to go to execute the desired trajectory based on the confidences, but confidences never get processed. I tried on an android app and it worked, just not on the control hub.

Comparing to array list through there given index but its returning null exception at file initialization

package adc;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
class Result {
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<=n;j++){
if(ar.get(i)==ar.get(j)){
count++;
}
}
}
return(count);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); ' BufferedWriter(newFileWriter(System.getenv("F:\\")));'
int n = Integer.parseInt(bufferedReader.readLine().trim());
String[] arTemp = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> ar = new ArrayList<>();
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arTemp[i]);
ar.add(arItem);
}
int result = Result.sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Working of code
here inputs are n("number of integer arraylist have")=9
and ar input of arraylist [10, 20, 20, 10, 10, 30, 50, 10, 20]
** In this ar arraylist we have to find the even pair of number and return the number of pair .**
In this example the output is 3.

managed c++ classes crash in create_task

Basically, what is happening is when trying to change a variable of a Managed class (UWP), it crashes. Additionally, it seems to only crash if I try modifying a variable which is created with the app namespace. In other words, if I create a new namspace and managed class, I can modify variables just fine.
void ASynTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
create_task([taskDone, responseItem, rootPage]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
UberSnipAPI->Http->request();
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
});
This does not crash
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
but this one does
all_item->Title = "All";
I am almost positive it has something to do with it being in the apps default namespace and it being accessed outside of the main thread ... At least that's what it seems like as that's really the only difference besides the actual class.
This is what GENERIC_ITEM looks like.
[Windows::UI::Xaml::Data::Bindable]
public ref class GENERIC_ITEM sealed {
private:
Platform::String^ _title = "";
Platform::String^ _description;
Windows::UI::Xaml::Media::ImageSource^ _Image;
event PropertyChangedEventHandler^ _PropertyChanged;
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChangedEventArgs^ pcea = ref new PropertyChangedEventArgs(propertyName);
_PropertyChanged(this, pcea);
}
public:
GENERIC_ITEM() {
};
property Platform::String^ Title {
Platform::String^ get() {
return this->_title;
}
void set(Platform::String^ val) {
this->_title = val;
OnPropertyChanged("Title");
}
}
property Platform::String^ Description {
Platform::String^ get() {
return this->_description;
}
void set(Platform::String^ val) {
this->_description = val;
OnPropertyChanged("Description");
}
}
void SetImage(Platform::String^ path)
{
Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(path);
_Image = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage(uri);
}
};
I know there is no issue with the class because it works perfectly fine if I run this exact same code on the initial thread.
Any suggestions? Thanks! :D
Figured it out after several hours! In case someone else is having this issue, all you must do is use the Dispatcher to run code on the UI that is not available outside of the UI thread.
void loadCats(UberSnip::HELPER::ASYNC_RESPONSE^ responseItem, MainPage^ rootPage) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
}
void ASyncTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
auto dispatch = CoreWindow::GetForCurrentThread()->Dispatcher;
auto op2 = create_async([taskDone, responseItem, rootPage, dispatch] {
return create_task([taskDone, responseItem, rootPage, dispatch]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
try{
UberSnipAPI->Http->request();
}
catch (...) {
printf("Error");
}
int err = UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).find("__api_err");
if (err < 0) {
if (UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).length() < 3) {
return;
}
}
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
dispatch->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]()
{
rootPage->loadCats(responseItem, rootPage);
}));
for (int i = 0; i < 100;) {
}
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
});
});
//rootPage->loadCats(responseItem, rootPage);
}

i want to know where to put my java code in opendaylight project , load balancing routing

i am new to opendaylight i have installed mininet and connected to the controller successfully. I want to implement dynamic load balancing on the controller i have the java code with me the problem is I donot know where to put it
**
* #file
LbRoutingImplementation.java
*
*
* #brief
Implementation of a routing engine using
* lb_routing. Implementation of lb_routing
come from Jung2 library
*
*/
package org.opendaylight.controller.routing.lb_routing_implementation.internal;
import org.opendaylight.controller.sal.core.Bandwidth;
import org.opendaylight.controller.sal.core.ConstructionException;
import org.opendayli
ght.controller.sal.core.Edge;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.core.Path;
import org.opendaylight.controller.sal.core.Property;
import org.op
endaylight.controller.sal.core.UpdateType;
import org.opendaylight.controller.sal.reader.IReadService;
import org.opendaylight.controller.sal.routing.IListenRoutingUpdates;
import org.opendaylight.controller.sal.routing.IRouting;
import org.opendaylight.co
ntroller.sal.topology.TopoEdgeUpdate;
import org.opendaylight.controller.switchmanager.ISwitchManager;
import org.opendaylight.controller.topologymanager.ITopologyManager;
import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
import org
.opendaylight.controller.statisticsmanager.internal.StatisticsManager;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.
util.EdgeType;
import java.lang.Exception;
import java.lang.IllegalArgumentException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Map;
import java.util.concu
rrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.collections15.Transformer;
public class LbRoutingImp
lementation implements IRouting, ITopologyManagerAware {
private static Logger log = LoggerFactory
.getLogger(LbRoutingImplementation.class);
private ConcurrentMap<Short, Graph<Node, Edge>> topologyBWAware;
private ConcurrentMap<Sho
rt, DijkstraShortestPath<Node, Edge>> sptBWAware;
DijkstraShortestPath<Node, Edge> mtp; // Max Throughput Path
private Set<IListenRoutingUpdates> routingAware;
private ISwitchManager switchManager;
30
private ITopologyManager topologyManager;
private IReadService readService;
private static final long DEFAULT_LINK_SPEED = Bandwidth.BW1Gbps;
private StatisticsManager statMgr;
private Timer lbRoutingTimer;
private TimerTask lbRoutingTimerTask;
public void setListenR
outingUpdates(IListenRoutingUpdates i) {
if (this.routingAware == null) {
this.routingAware = new HashSet<IListenRoutingUpdates>();
}
if (this.routingAware != null) {
log.debug("Adding routingAware listener:
{}", i);
this.routingAware.add(i);
}
}
public void unsetListenRoutingUpdates(IListenRoutingUpdates i) {
if (this.routingAware == null) {
return;
}
log.debug("Removing routingAware listener");
this.routingAware.remove(i);
if (this.routingAware.isEmpty()) {
// We don't have any listener lets dereference
this.routingAware = null;
}
}
#Override
public synchronized void initMaxThroughput(
final Map<Edge, Number> EdgeWeightMap) {
if (mtp != null) {
log.error("Max Throughput Dijkstra is already enabled!");
return;
}
Transformer<Edge, ? extends Number> mtTransformer = null;
i
f (EdgeWeightMap == null) {
mtTransformer = new Transformer<Edge, Double>() {
public Double transform(Edge e) {
if (switchManager == null) {
log.error("switchManager is null");
return (double)
-
1;
}
NodeConnector srcNC = e.getTailNodeConnector();
NodeConnector dstNC = e.getHeadNodeConnector();
if ((srcNC == null) || (dstNC == null)) {
log.error("srcNC:{} or dstNC:{} is null", srcNC, dstNC);
return (double)
-
1;
}
Bandwidth bwSrc = (Bandwidth) switchManager
.getNodeConnecto
rProp(srcNC,
Bandwidth.BandwidthPropName);
Bandwidth bwDst = (Bandwidth) switchManager
.getNodeConnectorProp(dstNC,
Bandwidth.BandwidthP
ropName);
34
// If the src and dst vertex don't have incoming or
// outgoing links we can get ride of them
if (topo.containsVertex(src.getNode())
&& topo.inDegree(src.getNode()) == 0
&
& topo.outDegree(src.getNode()) == 0) {
log.debug("Removing vertex {}", src);
topo.removeVertex(src.getNode());
}
if (topo.containsVertex(dst.getNode())
&& top
o.inDegree(dst.getNode()) == 0
&& topo.outDegree(dst.getNode()) == 0) {
log.debug("Removing vertex {}", dst);
topo.removeVertex(dst.getNode());
}
}
spt.
reset();
if (bw.equals(baseBW)) {
clearMaxThroughput();
}
} else {
log.error("Cannot find topology for BW {} this is unexpected!", bw);
}
return edgePresentInGraph;
}
priv
ate boolean edgeUpdate(Edge e, UpdateType type, Set<Property> props) {
String srcType = null;
String dstType = null;
if (e == null || type == null) {
log.error("Edge or Update type are null!");
return false;
} else {
srcType = e.getTailNodeConnector().getType();
dstType = e.getHeadNodeConnector().getType();
if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
log.debug("Skip updates f
or {}", e);
return false;
}
if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) {
log.debug("Skip updates for {}", e);
return false;
}
}
Ban
dwidth bw = new Bandwidth(0);
boolean newEdge = false;
if (props != null)
props.remove(bw);
if (log.isDebugEnabled()) {
log.debug("edgeUpdate: {} bw: {}", e, bw.getValue());
}
35
Short baseBW = S
hort.valueOf((short) 0);
boolean add = (type == UpdateType.ADDED) ? true : false;
// Update base topo
newEdge = !updateTopo(e, baseBW, add);
if (newEdge == true) {
if (bw.getValue() != baseBW) {
/
/ Update BW topo
updateTopo(e, (short) bw.getValue(), add);
}
}
return newEdge;
}
#Override
public void edgeUpdate(List<TopoEdgeUpdate> topoedgeupdateList) {
boolean callListeners = false;
for (int i = 0; i < topoedgeupdateList.size(); i++) {
Edge e = topoedgeupdateList.get(i).getEdge();
Set<Property> p = topoedgeupdateList.get(i).getProperty();
UpdateType type = topoedgeupdateList.get(i).getUpdateTy
pe();
if ((edgeUpdate(e, type, p)) && (!callListeners)) {
callListeners = true;
}
}
if ((callListeners) && (this.routingAware != null)) {
/*Map<Edge, Number> edgeWeightMap = new
Map<Edge,
Number >();
Bandwidth bw = new Bandwidth(0);
Graph<Node, Edge> topo = this.topologyBWAware.get(bw);
Collection<Edge> edges = topo.getEdges();
Iterator<Edge> iterEdge;
Number i;
for(it
erEdge = edges.iterator(), i = 0;iterEdge.hasNext();){
Edge e = iterEdge.next();
edgeWeightMap.put(e,i);
i = i.intValue()+1;
}*/
clearMaxThroughput();
mtp =
null;
initMaxThroughput(null);
for (IListenRoutingUpdates ra : this.routingAware) {
try {
ra.recalculateDone();
} catch (Exception ex) {
log.error("
Exception on routingAware listener call", ex);
}
}
}
}
private void updateEdgeUtilization() {
log.debug("UpdateEdgeUtilization called");
clearMaxThroughput();
mtp = null;
init
MaxThroughput(null);
}
/**
* Function called by the dependency manager when all the required
36
* dependencies are satisfied
*
*/
#SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
log.debug("Rout
ing init() is called");
this.topologyBWAware = (ConcurrentMap<Short, Graph<Node, Edge>>) new ConcurrentHashMap();
this.sptBWAware = (ConcurrentMap<Short, DijkstraShortestPath<Node, Edge>>) new ConcurrentHashMap();
// Now create the
default topology, which doesn't consider the
// BW, also create the corresponding Dijkstra calculation
Graph<Node, Edge> g = new SparseMultigraph();
Short sZero = Short.valueOf((short) 0);
this.topologyBWAware.put(sZero, g);
this.sptBWAware.put(sZero, new DijkstraShortestPath(g));
// Topologies for other BW will be added on a needed base
this.statMgr = new StatisticsManager();
this.lbRoutingTimer = new Timer();
this.lbRoutingTimerTask =
new TimerTask() {
#Override
public void run() {
updateEdgeUtilization();
}
};
}
/**
* Function called by the dependency manager when at least one dependency
* become unsati
sfied or when the component is shutting down because for
* example bundle is being stopped.
*
*/
void destroy() {
log.debug("Routing destroy() is called");
}
/**
* Function called by dependency manager after "init
()" is called and after
* the services provided by the class are registered in the service registry
*
*/
void start() {
log.debug("Routing start() is called");
// build the routing database from the topology if it exists
.
Map<Edge, Set<Property>> edges = topologyManager.getEdges();
if (edges.isEmpty()) {
return;
}
List<TopoEdgeUpdate> topoedgeupdateList = new ArrayList<TopoEdgeUpdate>();
log.debug("Creating routing datab
ase from the topology");
for (Iterator<Map.Entry<Edge, Set<Property>>> i = edges.entrySet()
.iterator(); i.hasNext();) {
Map.Entry<Edge, Set<Property>> entry = i.next();
Edge e = entry.getKey();
Set<Property> props = entry.getValue();
TopoEdgeUpdate topoedgeupdate = new TopoEdgeUpdate(e, props,
UpdateType.ADDED);
topoedgeupdateList.add(topoedgeupdate);
37
}
edgeUpdate(topoedgeupdateL
ist);
// StatsTimer is set to 10s
lbRoutingTimer.scheduleAtFixedRate(lbRoutingTimerTask, 0, 10000);
}
/**
* Function called by the dependency manager before the services exported by
* the component are unregistered,
this will be followed by a "destroy ()"
* calls
*
*/
public void stop() {
log.debug("Routing stop() is called");
}
#Override
public void edgeOverUtilized(Edge edge) {
// TODO Auto
-
generated method stub
}
#Override
public void edgeUtilBackToNormal(Edge edge) {
// TODO Auto
-
generated method stub
}
public void setSwitchManager(ISwitchManager switchManager) {
this.switchManager = switchManager;
}
public void unsetS
witchManager(ISwitchManager switchManager) {
if (this.switchManager == switchManager) {
this.switchManager = null;
}
}
public void setReadService(IReadService readService) {
this.readService = readService;
}
public void unsetReadService(IReadService readService) {
if (this.readService == readService) {
this.readService = null;
}
}
public void setTopologyManager(ITopologyManager tm) {
this.topologyManager = tm;
}
public void unsetTopologyManager(ITopologyManager tm) {
if (this.topologyManager == tm) {
this.topologyManager = null;
}
}
}

Iterate on a range of iterable

I have interface that returns a iterable object.
I need to iterate on the first 1000 items of it.
What is the best way to combine iterating using Iterator and stop after a certain count is reached.
Thanks
I'd use a loop that iterates and have a counter variable incremented; then break out of the loop when the counter reaches 1000.
What is your language?
C#:
using System.Linq;
//...
foreach (var item in iface.GetIterable().Take(1000))
{
//...
}
Python:
import itertools
#...
for item in itertools.islice(iface.get_iterable(), 1000):
#...
Make a standard loop that iterates over your collection, but check to see if the index has progress past the target index.
You may want to extract a seperate counter from the main loop index for your specific application.
int stopIndex = 1000;
for (int index = 0; index <= theInterface.Count; index++)
{
// check to see if we're at/past the stopIndex
if (index >= stopIndex)
break;
// we're still within the conditions, so do something with your interface
myObjectType localObject = (MyObjectType)theInterface.IndexOf(index);
}
Here's a test-driven (Java) wrapper around any existing iterator that should do the trick.
package com.playground;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
public class LimitedIterableTest extends TestCase {
private static class LimitedIterator<T> implements Iterator<T> {
private final Iterator<T> original;
private final int limit;
private int index = 0;
public LimitedIterator(Iterator<T> iterator, int limit) {
this.original = iterator;
this.limit = limit;
}
public boolean hasNext() {
return index < limit && original.hasNext();
}
public T next() {
index++;
return original.next();
}
public void remove() {
original.remove();
}
}
private static class LimitedIterable<T> implements Iterable<T> {
private final int limit;
private final Iterable<T> original;
public LimitedIterable(Iterable<T> iterable, int limit) {
this.original = iterable;
this.limit = limit;
}
public Iterator<T> iterator() {
return new LimitedIterator<T>(original.iterator(), limit);
}
}
final Integer[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
final List<Integer> list = Arrays.asList(array);
public void testCount() throws Exception {
assertEquals(10, count(list));
}
public void testLimitedIterable() throws Exception {
Iterable<Integer> limited = new LimitedIterable<Integer>(list, 5);
assertEquals(5, count(limited));
limited = new LimitedIterable<Integer>(list, 50);
assertEquals(10, count(limited));
}
private static <T> int count(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
return count(iterator);
}
private static <T> int count(Iterator<T> iterator) {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
}