Gemfire Region Size [closed] - gemfire

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to find size of a region in my Gemfire cache. I have checked the java api of Region. The size method returns only the entry count. I'm sure there must be some way to calculate region size in terms of how much memory it is taking, because Gemfire Pulse data view it shows Memory Usage for each region. Can anyone please help on this?

If you're after the total heap, in gfsh, do a garbage collect and it will tell you exactly how much memory your distributed system is taking in the "After GC" column. As follows:
gfsh> connect
gfsh> gc
Member ID/Name | HeapSize (MB) Before GC | HeapSize(MB) After GC | Time Taken for GC in ms
------------------------------------- | ----------------------- | --------------------- | -----------------------
192.168.0.10(server1:40981)<v1>:52393 | 1698 | 120 | 14
192.168.0.10(server2:43759)<v2>:9599 | 2250 | 78 | 15
To get the size of a partitioned region, run the following in a function on all the nodes:
Region<?,?> primaryDataSet = PartitionRegionHelper.getLocalData(region);
regionSize = primaryDataSet.size();
For a replicated region, run the following code on one of the nodes (all code not shown for space). You have to loop through all or a sampling of entries to get the size of an average record and multiply it by the # entries. Not calculating the size of each row upon insert is by design since it would slow insert time:
/**
* Sizes numEntries of a replicated or local region, or all the entries if
* numEntries is 0.
*
* #param numberOfSamples
* Number of entries to size. If the value is 0, all the entries are
* sized.
*/
private Map<String, Long> sizeReplicatedOrLocalRegion(Region<?,?> region, long numberOfSamples) {
regionTypeInd = 1L;
Set<?> entries = region.entrySet();
regionSize = entries.size();
if (numberOfSamples == 0) {
numberOfSamples = entries.size();
} else if (numberOfSamples > regionSize) {
numberOfSamples = regionSize;
}
int count = 0;
for (Iterator<?> i = entries.iterator(); i.hasNext();) {
if (count == numberOfSamples) {
break;
}
LocalRegion.NonTXEntry entry = (LocalRegion.NonTXEntry) i.next();
RegionEntry re = entry.getRegionEntry();
dumpSizes(entry, re);
count++;
}
dumpTotalAndAverageSizes(numberOfSamples);
Map<String, Long> results = packageResults(numberOfSamples);
clearTotals();
return results;
}
private void dumpSizes(Region.Entry<?,?> entry, RegionEntry re) {
int deserializedRegionEntrySizeBefore = ReflectionObjectSizer.getInstance().sizeof(re);
int serializedValueSize = calculateSerializedValueSize(entry, re);
int deserializedKeySize = ReflectionObjectSizer.getInstance().sizeof(entry.getKey());
Object value = entry.getValue();
int deserializedValueSize;
if (value instanceof PdxInstance) {
Object actualObj = ((PdxInstance) value).getObject();
deserializedValueSize = sizeObject(actualObj);
} else {
deserializedValueSize = sizeObject(value);
}
int deserializedRegionEntrySizeAfter = ReflectionObjectSizer.getInstance().sizeof(re);
this.totalDeserializedRegionEntrySizeBefore += deserializedRegionEntrySizeBefore;
this.totalDeserializedKeySize += deserializedKeySize;
this.totalDeserializedValueSize += deserializedValueSize;
this.totalSerializedValueSize += serializedValueSize;
this.totalDeserializedRegionEntrySizeAfter += deserializedRegionEntrySizeAfter;
log("RegionEntry (key = " + re.getKey() + ") size: " + deserializedRegionEntrySizeBefore + " (serialized), "
+ deserializedRegionEntrySizeAfter + " (deserialized). Key size: " + deserializedKeySize
+ ". Value size: " + serializedValueSize + " (serialized), " + deserializedValueSize
+ "(deserialized).");
String histStats = "";
try {
histStats = histObject(re);
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log("Hist Stats=" + histStats);
}
private int calculateSerializedValueSize(Region.Entry<?,?> entry, RegionEntry re) {
Object valueInVm = re.getValue(null);
int serializedValueSize = 0;
if (valueInVm instanceof CachedDeserializable) {
// Value is a wrapper
Object cdValue = ((CachedDeserializable) valueInVm).getValue();
if (cdValue instanceof byte[]) {
// The wrapper wraps a serialized domain object
serializedValueSize = ((byte[]) cdValue).length;
} else {
// The wrapper wraps a deserialized domain object
serializedValueSize = ReflectionObjectSizer.getInstance().sizeof(cdValue);
}
} else {
// Value is a domain object
serializedValueSize = ReflectionObjectSizer.getInstance().sizeof(valueInVm);
}
return serializedValueSize;
}
private Map<String, Long> packageResults(long totalSamples) {
Map<String, Long> results = new HashMap<>();
results.put("Average RegionEntry size (serialized)", avgDeserializedRegionEntrySizeBefore);
results.put("Average RegionEntry size (deserialized)", avgDeserializedRegionEntrySizeAfter);
results.put("Average Key size", avgDeserializedKeySize);
results.put("Average Value size (serialized)", avgSerializedValueSize);
results.put("Average Value size (deserialized)", avgDeserializedValueSize);
results.put("Total RegionEntry size (serialized)", this.totalDeserializedRegionEntrySizeBefore);
results.put("Total RegionEntry size (deserialized)", this.totalDeserializedRegionEntrySizeAfter);
results.put("Total Key size", this.totalDeserializedKeySize);
results.put("Total Value size (serialized)", this.totalSerializedValueSize);
results.put("Total Value size (deserialized)", this.totalDeserializedValueSize);
results.put("_Region Type indicator", regionTypeInd);
results.put("_Total Sampled Entries", (long) totalSamples);
results.put("_Total Entries", (long) regionSize);
return results;
}

Go and login to pulse and navigate to following url
http://XX.XXX.XXX.XX:7070/pulse/regionDetail.html?regionFullPath=/your-region-name

Related

how to increase the size limit of a mutable list in kotlin?

I was attempting to solve the multiset question (https://codeforces.com/contest/1354/problem/D) on codeforces using Fenwick Tree Data structure. I passed the sample test cases but got the memory limit error after submitting, the testcase is mentioned below.
(Basically the testcase is:
1000000 1000000
1.............1 //10^6 times
-1...........-1 //10^6 times).
I tried similar testcase in my IDE and got the below mentioned error.
(Similar to above, the testcase I provided is:
1000000 1
1.............1 //10^6 times
-1
)
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 524289 out of bounds for length 524289
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:426)
at MultisetKt.main(multiset.kt:47)
at MultisetKt.main(multiset.kt)
Here is my code:
private fun readInt() = readLine()!!.split(" ").map { it.toInt() }
fun main() {
var (n, q) = readInt()
var list = readInt() //modify the list to store it from index 1
var finalList = listOf(0) + list
val query = readInt()
var bit = MutableList(n+1){0}
fun update(i:Int, value:Int) {
var index = i
while(index < n){
bit.set (index , bit[index] + value)
index += (index and -index)
}
}
fun rangefunc(i:Int): Int {
var su = 0
var index = i
while(index > 0){
su += bit[index]
index -= (index and -index)
}
return su
}
fun find(x:Int):Int {
var l = 1
var r = n
var ans = n
var mid = 0
while (l <= r) {
mid = (l + r) / 2
if (rangefunc(mid) >= x) {
ans = mid
r = mid - 1
} else {
l = mid + 1
}
}
return ans
}
for (i in 1..n) {
update(finalList[i], 1)
}
for (j in 0..q - 1) {
if (query[j] > 0) {
update(query[j], 1)
} else {
update(find(-query[j]), -1)
}
}
if(rangefunc(n) == 0){
println(0)
}else{
println(find(1))
}
}
I believe this is because the BITlist is not able to store 10^6 elements but not sure. Please let me know what changes should I make in my code also any additional advice on how to deal with such cases in the future.
Thank you in advance :)
An ArrayList can store over 2 billion items (2 * 10^9). That is not your issue. ArrayIndexOutOfBoundsException is for trying to access an index of an ArrayList that is less than zero or greater than or equal to its size. In other words, an index that it doesn't yet contain.
There's more code there than I have time to debug. But I would start at the line that the stack trace points to and see how it's possible for you to attempt to call bit[index] with an index that equals the size of the ArrayList.
To answer your literal question, you can use LinkedList explicitly as your type of MutableList to avoid the size restriction, but it is heavier and it is slower when accessing elements by index.

Cannot add row without complete selection of batch/serial numbers

ERROR: (-4014) Cannot add row without complete selection of batch/serial numbers.
The default function of DI API SaveDraftToDocument() is working fine on MS SQL Database but not SAP HANA.
I am posting the Delivery document with Serial Numbers.
SAPbobsCOM.Documents oDrafts;
oDrafts = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);
oDrafts.GetByKey(Convert.ToInt32(EditText27.Value));
var count = oDrafts.Lines.Count;
var linenum = oDrafts.Lines.LineNum;
//Validation
#region
var RsRecordCount = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQryRecordCount = String.Format("Select * from \"SANTEXDBADDON\".\"#TEMPITEMDETAILS\" where \"U_DraftNo\" = '{0}'", EditText27.Value);
RsRecordCount.DoQuery(sQryRecordCount);
#endregion
if (count == RsRecordCount.RecordCount)
{
//LINES
string ItemCode = "", WhsCode = ""; double Quantity = 0; int index = 0;
for (int i = 0; i < oDrafts.Lines.Count; i++)
{
oDrafts.Lines.SetCurrentLine(index);
ItemCode = oDrafts.Lines.ItemCode;
//SERIAL NUMBERS
var RsSerial = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
string table = "\"#TEMPSERIALS\"";
var sQrySerial = String.Format(
"Select \"U_ItemCode\" , \"U_DistNumber\" from \"SANTEXDBADDON\".\"#TEMPSERIALS\" where " +
"\"U_DraftNo\" = '{0}' and \"U_ItemCode\" = '{1}'", EditText27.Value, ItemCode);
RsSerial.DoQuery(sQrySerial);
int serialindex = 1, lineindex = 0;
#region
if (RsSerial.RecordCount > 0)
{
while (!RsSerial.EoF)
{
//OSRN SERIALS
var RsSerialOSRN = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
var sQrySerialOSRN = String.Format(
"Select * from OSRN where \"DistNumber\" = '{0}' and \"ItemCode\" = '{1}'"
, RsSerial.Fields.Item("U_DistNumber").Value.ToString(), ItemCode);
RsSerialOSRN.DoQuery(sQrySerialOSRN);
oDrafts.Lines.SerialNumbers.SetCurrentLine(0);
oDrafts.Lines.SerialNumbers.BaseLineNumber = oDrafts.Lines.LineNum;
oDrafts.Lines.SerialNumbers.SystemSerialNumber =
Convert.ToInt32(RsSerialOSRN.Fields.Item("SysNumber").Value.ToString());
oDrafts.Lines.SerialNumbers.ManufacturerSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.InternalSerialNumber =
RsSerialOSRN.Fields.Item("DistNumber").Value.ToString();
oDrafts.Lines.SerialNumbers.Quantity = 1;
if (RsSerial.RecordCount != serialindex)
{
Application.SBO_Application.StatusBar.SetText("INTERNAL NO " + oDrafts.Lines.SerialNumbers.InternalSerialNumber, SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
oDrafts.Lines.SerialNumbers.Add();
serialindex++;
lineindex++;
}
RsSerial.MoveNext();
}
}
#endregion
index++;
}
var status = oDrafts.SaveDraftToDocument();
if (status == 0)
{
oDrafts.Remove();
Application.SBO_Application.StatusBar.SetText("Delivery Posted Successfully !", SAPbouiCOM.BoMessageTime.bmt_Long, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
}
else
{
int code = 0; string message = "";
oCompany.GetLastError(out code, out message);
Application.SBO_Application.SetStatusBarMessage(message, SAPbouiCOM.BoMessageTime.bmt_Medium, true);
}
}`
The error you have posted explains the problem. You are trying to deliver products but have not included all of the serial/batch numbers.
I don't think there's enough information to be sure where this problem happens, but here are some pointers:
You are reading the serial numbers from a custom table. Are the values you are reading valid? For example, could another user have added them to a different order? Could the values be for a different product?
Are you specifying the correct quantity of serial numbers? Is it possible that the item quantity on the line is more than the number of serial numbers you are adding?
Believe the error message until you can prove it's wrong. It doesn't seem like this is a HANA issue (we use HANA extensively) it's a logical problem with the data you are providing.
You may want to capture more debugging information to help you if you can't easily identify where the problem is.

Size of Serialized data is not reducing using flatbuffer

I have written following fbs file
namespace testing;
table polygon {
x : double;
y : double;
}
table layer {
layer_name : string;
polygons : [polygon];
}
root_type layer;
My plan is to serialize approx 5 Million coordinates and dump it into one file. Problem is what I see is the number of bytes is increased compared to what I was expecting. I am expecting it should be arounf (5M* 16) bytes. But the size what I am getting is 140000032 bytes
Here is the java code which I am using for dumping serialize data into a file.
FlatBufferBuilder fbb = new FlatBufferBuilder(0);
String s = "Product1";
int str = fbb.createString("layer1");
int size = 1 * 5 * 1000000;
int[] offset = new int[size];
int cur = 0;
for (double i = 0; i < size; i++) {
fbb.startTable(2);
polygon.addX(fbb, i);
polygon.addY(fbb, i);
offset[cur++] = polygon.endpolygon(fbb);
}
int arrayoffset = layer.createPolygonsVector(fbb, offset);
layer.startlayer(fbb);
layer.addLayerName(fbb, str);
layer.addPolygons(fbb, arrayoffset);
int bla = layer.endlayer(fbb);
fbb.finish(bla);
ByteBuffer bf = fbb.dataBuffer().duplicate();
File myfile = new File("/tmp/test.dat");
try {
FileChannel channel = new FileOutputStream(myfile).getChannel();
channel.write(bf);
channel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please let me know if I am doing something wrong here
change table polygon into struct polygon. table is extensible and has some fixed overhead per element, and also is referred to by the vector over an offset. A struct is not extensible (which seems fine for an xy pair), and has to be serialized inline (see example in the tutorial), and will give you the size you expect.

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

Asking the user to enter in numbers, getting min/max/and average

Hi guys I'm have a real hard time for some reason trying to get this code worked out. My guide lines are:
Create a new Scanner object and save it into a variable name of your choice
Declare an integer variable for the current user’s input and initialize it to something that is NOT 0 (we will call it intInput in these instructions – the name is arbitrary, though)
Create a while loop, with the condition being that intInput is not equal to 0
Inside of this loop, call the nextInt() method of your Scanner object and store the value into intInput
I'm not getting any errors but its not working the way I thought it would.
and here is my code:
import java.util.Scanner;
// class name matches the file name
public class Lab5
{
// we must have a main method to run the program
`enter code here`public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
int userInput = 1;
int minVal = Integer.MIN_VALUE;
int maxVal = Integer.MAX_VALUE;
double average = 0;
int holdNum = 0;
double numSum = 0;
System.out.print ("Please enter numbers and to finish the program your last number should be 0: ");
numSum += userInput;
holdNum++;
while (userInput != 0)
{
userInput = scan.nextInt();
}
if (maxVal > Integer.MAX_VALUE)
{
maxVal = userInput;
}
if (minVal < Integer.MIN_VALUE)
{
minVal = userInput;
}
average = ( numSum ) / ( holdNum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + maxVal );
System.out.println( "Minimum = " + minVal );
}
}
You are adding the user input in the sum and incrementing the number of user inputs only when the input is less than the minimum. I would guess you'll want to do it for all inputs instead.