Start Java Application using System.Diagnostics.Process - java

$startCount = 5;
$processors = Get-WmiObject -Class Win32_ComputerSystem | select -
ExpandProperty "NumberOfLogicalProcessors";
$perInstance = $processors / $startCount;
$affinityloop = 1;
$affinityvalue = 0;
for($i=1; $i -le $startCount; $i++) {
$affinityvalue = 0;
for($u=1; $u -le $perInstance ; $u++) {
$affinityvalue = $affinityvalue + $affinityloop;
$affinityloop = $affinityloop * 2;
}
$ps = new-object System.Diagnostics.Process;
$ps.StartInfo.Filename = "C:\jdk\bin\java.exe";
$ps.StartInfo.Arguments = " -server -Xms10240m -Xmx10240m -XX:+UseG1GC -cp `".;*`" Worker";
$ps.start();
Write-Host $affinityvalue ;
$ps.ProcessorAffinity = [Convert]::ToString($affinityvalue, 16);
}
I am trying to start a Windows Java application on two different NUMA nodes. Has anyone able to accomplish this with Diagnostics.Process format? This code does work fine, but all applications created are on the same NUMA node and hence only using 50% power.
I tried codes such as $mod = ($i % 2); to help prepare for some way to alternate the NUMA node but unsure how to specify it within the script.
EDIT
Tried to load balance with ProcessorAffinity and I get crashes due to Double unable to convert to IntPtr
EDIT 2
So it looks like Windows Groups the processors past 64 into Groups. Can't seem to find a way to alter that like ProcessAffinity. I guess its just not that common. You can easily do it in Task manager, just need to find a way to do it in Powershell or similar.

Related

vscode coderunner has trouble executing java code

I have the following structure:
java_projects > chapter9
usually i cd to a directory a level above java_projects, and do code java_projects to create a workspace directory from that location. Now, inside chapter 9, i have the folloiwng files:
Tv.java, TestTv.java
Inside TestTv.java i have the following code:
package chapter9;
public class TestTv {
public static void main(String[] args){
Tv tv = new Tv();
tv.turnOn();
tv.setChannel(30);
tv.setVolume(3);
System.out.println("Tv channel is: " + tv.channel);
// testing java date class
java.util.Date date = new java.util.Date();
System.out.println("time elapsed since jan 1, 1970 is: " + date.getTime() + "milliseconds");
System.out.println(date.toString());
}
}
when i run this via code-runner, i get the following error:
TestTv.java:5: error: cannot find symbol
Tv tv = new Tv();
^
symbol: class Tv
location: class TestTv
TestTv.java:5: error: cannot find symbol
Tv tv = new Tv();
^
symbol: class Tv
location: class TestTv
I'm not too sure why this is happening. Upon further investigating, i learned this has to do with compiling the Tv Class first before its being used in java program. Ok, so i looked into my settings.json inside vscode and changed it to:
"java": cd $dir && javac *.java && java $fileName"
This still gives me the same error.
So i cd'd out of the chapter9 directory and tried java chapter9/TestTv.java and it worked!!
How do i tell vscode's executor map to go back one level up and execute it?
Thanks
{
"code-runner.clearPreviousOutput": true,
"code-runner.ignoreSelection": true,
"code-runner.saveAllFilesBeforeRun": true,
"java.autobuild.enabled": true,
"code-runner.fileDirectoryAsCwd": false,
"java.configuration.updateBuildConfiguration": "automatic",
"code-runner.executorMap": {
"java": "cd $dir && javac *.java && java $fileName"
},
"code-runner.runInTerminal": true,
}
Attached is my tvclass
public class Tv {
// instance variables
int channel = 1; // default channel is 1
int volumeLevel = 1;
boolean on = false; // Tv is off
public Tv(){};
public void turnOn(){
on = true;
}
public void turnOff(){
on = false;
}
public void setChannel(int newChannel){
if (on && newChannel >= 1 && newChannel <= 120)
channel = newChannel;
}
public void setVolume(int newVolumeLevel){
if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7){
volumeLevel = newVolumeLevel;
}
}
public void channelUp(){
if (on && channel < 120)
channel++;
}
public void channelDown(){
if (on && channel > 1)
channel--;
}
public void volumeUp(){
if (on && volumeLevel < 7)
volumeLevel++;
}
public void volumeDown(){
if (on && volumeLevel > 1)
volumeLevel--;
}
Im looking for something like this?
"java": cd $dir && javac *.java && java (go back one directory up) $dir[my_folder_name]fileName"
so something like this...
"java": cd $dir && javac *.java && cd .. java chapter9/TestTv.java"
I don't know i can't make it any more clearer. I have a mac OSX, sierra, javaSE11. I don't think it has to do with the operating system. Its more of a compilation issue. going to the vscode's github doesn't help as they don't reply to any thing.
I am also not very familiar with the topic. I did some trial and error and managed it to work with the following:
"code-runner.executorMap": {
"java": "cd $dir && javac *.java && cd .. && java \"$(basename $dir)/$fileNameWithoutExt\""
}
Notable parts/changes:
&& cd .. moves one directory up.
$(basename $dir) returns the most inner directory. chapter9 in your example, but if you change to another directory you don't have to change it.
$fileNameWithoutExt: The base name of the code file being run without its extension, as documented here under Configuration.
I'm less familiar with this topic, but based looking at this syntax in your problem/answer and seeing the "&&" syntax as a series of scripts, it looks like you need one more "&&" in the mix so the "cd .." moves up to the parent directory BEFORE calling the java-interpreter as the last thing.
so:
"java": cd $dir && javac *.java && cd .. && java chapter9.TestTv"
Also I'm less familiar with mac requirements, but I know some systems don't mind "cd.." and some only take "cd .." with the space, so be cautious as you type it in..

Powershell running Java Script to Encrypt Password

We have a number of Lanier MFPs that use the scan-to-folder option to allow people to get their documents, and we are starting to implement more security measures on the AD passwords they use by forcing a password reset.
Unfortunately, the Laniers use a proprietary encryption for the passwords. I've managed to get a functional Java command that will encrypt passwords into this format. The problem I've been encountering is that I then have to get this encoded password into PowerShell to pass it to the scanner.
I can run the Java command through a command line, but can't pass the encrypted password back into PowerShell as a string that the printer will accept (it needs to be in Base64). If I do pass the encoded password back into PowerShell, then run it through PowerShell's Base64 creation process, it is, obviously, changed too much for the scanner to use it.
What I need to determine is whether there's a way for me to take the following command line command, and get it to run in PowerShell, then provide me its output so I can pass this to the printer.
java -cp ./commons-codec-1.10.jar;. cdm.GwpwesCharacterEncoding %pass% "gwpwes002"
The Java command outputs a Base64 string based on the following line:
return new String(Base64.encodeBase64((byte[])encrypt));
As an example, if I pass the text 'Test' into that, I get the string "HVhcmtla25meHVncHQ=="
This is useless to me, though, as I can't then get this back into PowerShell to pass through to the printer, and if I encode it as Base64 with PowerShell, it comes out as "MgBoAHMAWgBtADkAegBjADIAQgBxAGUAMABKAHgAWgBYAGgAbgBiAG0AMAB3AD0A".
Can anyone help?
Revised code after some assistance:
$pass1 = "test"
$path = "c:\Test\printercreds"
$encode = "gwpwes002"
cd $path
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pInfo.FileName = 'java'
$pInfo.Arguments = "-jar .\commons-codec-1.10.jar cdm.GwpwesCharacterEncoding $pass1 $encode"
$pInfo.UseShellExecute = $false
$pInfo.RedirectStandardOutput = $true
$pInfo.RedirectStandardError = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $pInfo
[void]$process.Start()
$passsec = $process.StandardOutput.ReadtoEnd()
$process.WaitforExit()
write-host $passsec
Please try this. Its the encoding for GWPWES002. I found a old java version here.
https://www.dropbox.com/s/3324g84x0l4bnon/GwpwesCharacterEncoding.java?dl=0
There is a weakness in this "encoding". The front part of the encoding is just random padding. the pack part is where the actual string is stored. Running the script on the same string just a few times points out this error.
encodeGwpwes002 -code "a"
generated this hashes
np6eWFieWJ6eWA==
np6eWJ5YWFieWA==
WFienlhYnlieWA==
nlhYnp5Ynp6eWA==
nlieWFieWJ6eWA==
everything up until eWA== is just random padding mean "eWA==" == "a"
same for "aaaaaaaa"
np5YWJ5YnlieWFhYWFhYWFg=
np5Ynp6eWJ6eWFhYWFhYWFg=
nlienp6eWJ6eWFhYWFhYWFg=
WJ5YWJ6enlieWFhYWFhYWFg=
Meaning that
"eWFhYWFhYWFg=" Is "aaaaaaaa".
the password you provided as "test", A example of manipulation would be :
HVhcmtla25meHVncHQ== IS "test" :: 29 88 92 154 217 90 219 153 158 29 89 220 29
HVhcmtla25meFVncHQ== IS "Test" :: 29 88 92 154 217 90 219 153 158 21 89 220 29
Here is the powershell I have translated below
#private static String encodeGwpwes002(String code, int codeSize) {
function encodeGwpwes002([string]$code, [int]$codeSize = 0){
#byte[] protectCode;
[byte]$protectCode | Out-Null
#try {
try{
#protectCode = code.getBytes("UTF-8");
$protectCode = [System.Text.Encoding]::UTF8.GetBytes($code)
#}catch (Throwable e) {
}catch{
#return null;
return $null
#}
}
#int encodeSize = codeSize;
[int]$encodeSize = $codeSize
#if (protectCode.length >= codeSize) {
if(($protectCode.length) -ge $codeSize){
#encodeSize = protectCode.length + 9;
$encodeSize = ($protectCode.length) + 9
#}
}
#byte[] simple = new byte[encodeSize];
[byte[]]$simple = New-Object byte[] $encodeSize
#int diffuseCnt = 0;
[int]$diffuseCnt = 0
#int simpleCnt = 0;
[int]$simpleCnt = 0
#if (protectCode.length < encodeSize - 1) {
if(($protectCode.length) -lt ($encodeSize - 1)){
#for (diffuseCnt = 0; diffuseCnt < encodeSize - 1 - protectCode.length; ++diffuseCnt) {
for($diffuseCnt = 0; $diffuseCnt -lt ($encodeSize - 1 - ($protectCode.length)); $diffuseCnt++){
#simple[diffuseCnt] = (byte)(Math.random() * 25.0 + 97.0);
$simple[$diffuseCnt] = [byte] (Get-Random -Maximum 0.9 -Minimum 0.1) * 25.0 + 97.0
#}
}
#}
}
#simple[diffuseCnt++] = 122;
$simple[$diffuseCnt++] = 122
#for (simpleCnt = diffuseCnt; simpleCnt < protectCode.length + diffuseCnt; ++simpleCnt) {
for($simpleCnt = $diffuseCnt; $simpleCnt -lt ($protectCode.length) + $diffuseCnt; $simpleCnt++){
#simple[simpleCnt] = protectCode[simpleCnt - diffuseCnt];
$simple[$simpleCnt] = $protectCode[$simpleCnt - $diffuseCnt];
#}
}
#byte[] encrypt = new byte[simpleCnt];
[byte[]] $encrypt = New-Object byte[] $simpleCnt
#for (int i = 0; i < simpleCnt; ++i) {
for([int]$i=0; $i -lt $simpleCnt; $i++) {
#byte work = 0;
[byte]$work = 0
#work = (byte)((simple[i] & 192) >>> 6 | (simple[i] & 63) << 2);
$work = [byte](($simple[$i] -band 192) -shr 6 -bor ($simple[$i] -band 63) -shl 2)
#encrypt[i] = (byte)((work & 240) >>> 4 | (work & 15) << 4);
$encrypt[$i] = [byte](($work -band 240) -shr 4 -bor ($work -band 15) -shl 4)
#}
}
#return new String(Base64.encodeBase64((byte[])encrypt));
return [string]([System.Convert]::ToBase64String([byte[]]$encrypt))
#}
}
encodeGwpwes002TEST -code "Test"

Tensorflow in Android: How do i use my linear regression model to predict a value in an android application?

I currently have a ipynb file (ipython notebook) that contains a linear regression code / model(im not entirely sure if it's a model) that I've created earlier.
How do i implement this model in an android application such that if I were to input a value of 'x' in a text box, it'll output in a textview the predicted value of 'y'. Function: Y = mx + b.
I've tried looking at different tutorials, but they were mostly not "step-by-step" guides, which made it really hard to understand, I'm a beginner at coding.
Here's my code for the model:
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
rng = np.random
from numpy import genfromtxt
from sklearn.datasets import load_boston
# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50
n_samples = 222
X = tf.placeholder("float") # create symbolic variables
Y = tf.placeholder("float")
filename_queue = tf.train.string_input_producer(["C://Users//Shiina//battdata.csv"],shuffle=False)
reader = tf.TextLineReader() # skip_header_lines=1 if csv has headers
key, value = reader.read(filename_queue)
# Default values, in case of empty columns. Also specifies the type of the
# decoded result.
record_defaults = [[1.], [1.]]
height, soc= tf.decode_csv(
value, record_defaults=record_defaults)
features = tf.stack([height])
# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
# Construct a linear model
pred_soc = tf.add(tf.multiply(height, W), b) # XW + b <- y = mx + b where W is gradient, b is intercept
# Mean squared error
cost = tf.reduce_sum(tf.pow(pred_soc-soc, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
with tf.Session() as sess:
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
sess.run(init)
# Fit all training data
for epoch in range(training_epochs):
_, cost_value = sess.run([optimizer,cost])
#Display logs per epoch step
if (epoch+1) % display_step == 0:
c = sess.run(cost)
print( "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))
print("Optimization Finished!")
training_cost = sess.run(cost)
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
#Plot data after completing training
train_X = []
train_Y = []
for i in range(n_samples): #Your input data size to loop through once
X, Y = sess.run([height, pred_soc]) # Call pred, to get the prediction with the updated weights
train_X.append(X)
train_Y.append(Y)
#Graphic display
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.ylabel("SoC")
plt.xlabel("Height")
plt.axis([0, 1, 0, 100])
plt.plot(train_X, train_Y, linewidth=2.0)
plt.legend()
plt.show()
coord.request_stop()
coord.join(threads)

How to get actual RAM usage of app in android?

Quite simply, how can I get the amount of memory (in MB) that my android app is currently using? This would need to be done in Java so I can display this information to the user.
I've looked at other stackoverflow posts but none give a simple or accurate answer to this problem.
adb shell dumpsys meminfo packagename
Try to execute this command with Java.
You can use ActivityManager for that purpose.
It's answered in this post.
Try to use this code if a performance is not critical:
Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memInfo);
long res = memInfo.getTotalPrivateDirty();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
res += memInfo.getTotalPrivateClean();
return res * 1024L;
If performance is critical check this answer
1. dumpsys meminfo PKG_NAME
...
App Summary
Pss(KB)
------
Java Heap: 42868 <--
Native Heap: 52268 <--
Code: 23608
Stack: 96
Graphics: 5084
Private Other: 5620
System: 14900
TOTAL: 144444 <-- TOTAL SWAP PSS: 130
2. in java code
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Debug.java#640
// this is the value source of dumpsys meminfo.
Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memInfo);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
String javaMem = memInfo.getMemoryStat("summary.java-heap");
String natiMem = memInfo.getMemoryStat("summary.native-heap");
String totalMem = memInfo.getMemoryStat("summary.total-pss");
//msg2 += "\n" + String.format("%s %s %s", javaMem, natiMem, totalMem);
msg2 += "\n\n"+String.format("java %8s\nnati %8s\ntotal %8s",
formatMB(Integer.parseInt(javaMem)), formatMB(Integer.parseInt(natiMem)), formatMB(Integer.parseInt(totalMem))
);
}
...
String formatMB(double KB){
return String.format("%.1f MB", KB/1024);
}
The other api need lots of calculate,
// you can read them in Debug.java src file.
This is the closest to dumpsys meminfo or android studio monitor.

Autoit Java argument in run command through $chosen variable

I made a combo:
$Combo1 = GUICtrlCreateCombo("Java Memory", 24, 872, 145, 25, $CBS_DROPDOWNLIST)
GUICtrlSetData(-1, "-Xmx1024M|-Xmx2048M|-Xmx3072M|-Xmx4096M")
Then I added something to read it:
$chosen = GUICtrlRead($Combo1)
Then I made a run command and put $chosen in it:
Run ("java -jar spigot-1.6.2-R0.1.jar " & $chosen, "E:\Spill\Alle spill\Minecraft\KnarCraft 2013")
When I don't choose an option in the drop down list, it starts. When I do, it comes a window that disappears instantly, but it shows all valid parameters so therefore something is wrong in the way it reads it. I think it has something to do with the - but I don't know how i should do it. I tried using a - and then the variable, but then it reads it as -$chosen instead of "-" + "choice in $chosen".
First off, the order of your java command line I believe is important, and so the -Xmx option should come after the "java" and before the "-jar" tokens.
Next, I wonder if you're trying to use too much memory. Have you considered testing this with smaller values?
For example:
$Combo1 = GUICtrlCreateCombo("Java Memory", 10, 10, 142, 25, $CBS_DROPDOWNLIST)
GUICtrlSetData(-1, "-Xmx100M|-Xmx200M|-Xmx400M|-Xmx800M|-Xmx1024M|-Xmx2048M|-Xmx3072M|-Xmx4096M")
Then see if any of the smaller numbers work and if the larger numbers break the program.
My test program:
AutoIt program, MyFoo.au3:
#include <ComboConstants.au3>
#include <GUIConstantsEx.au3>
Example()
Func Example()
Local $msg
GUICreate("My GUI combo") ; will create a dialog box that when displayed is centered
$Combo1 = GUICtrlCreateCombo("Java Memory", 10, 10, 142, 25, $CBS_DROPDOWNLIST)
GUICtrlSetData(-1, "-Xmx100M|-Xmx200M|-Xmx400M|-Xmx800M|-Xmx1024M|-Xmx2048M|-Xmx3072M|-Xmx4096M")
GUISetState()
; Run the GUI until the dialog is closed
While 1
$msg = GUIGetMsg()
If $msg = $Combo1 Then
$chosen = GUICtrlRead($Combo1)
$runString1 = "java " & $chosen & " -jar MyFoo.jar"
$runString2 = "java -jar MyFoo.jar " & $chosen
ConsoleWrite($runString1 & #CRLF)
Run($runString1)
EndIf
If $msg = $GUI_EVENT_CLOSE Then ExitLoop
WEnd
EndFunc
Java test program, MyAutoItFoo.java. Of course this was jar'd first:
import javax.swing.JOptionPane;
public class MyAutoItFoo {
public static void main(String[] args) {
long heapSize = Runtime.getRuntime().totalMemory();
long heapMaxSize = Runtime.getRuntime().maxMemory();
String heapString = String.format("Heap Size = %H; Max Heap = %H",
heapSize, heapMaxSize);
System.out.println(heapString);
JOptionPane.showMessageDialog(null, heapString);
}
}

Categories

Resources