How to call run nodejs file from PHP and get values? - php

I have a laravel PHP 2 functions. In the first function, I simply create a game and generate a hash for it:
$token = bin2hex(random_bytes(64));
Game::query()->create([
'hash' => $token,
]);
and then i create new record from Game model laravel.
In second function, I need to somehow call a nodejs file, where numbers are simply generated, and the resulting numbers are passed to PHP for saving in the database. My simply second function:
public function setStatus(Request $r)
{
$status = $r->get('status');
$game = $this->getGameInController();
$game->update([
'status' => $status
]);
if ($status === 1) {
$game->update([
AND HERE I WANT TO RECEIVED INFORMATION FROM NODEJS FILE
]);
return $multiplier;
}
}
Then i has test.js file, where i want to pass the hash value from the table:
// You need to edit this value
var gameHash = 'HASH FROM LARAVEL GAME MODEL';
/*
Below this line is the formula which we use to calculate the result
*/
var crypto = require('crypto');
const INSTANT_CRASH_PERCENTAGE = 6.66;
var crashPointFromHash = function (serverSeed) {
var hash = crypto.createHmac('sha256', serverSeed).digest('hex');
// Use the most significant 52-bit from the hash to calculate the crash point
var h = parseInt(hash.slice(0, 52 / 4), 16);
var e = Math.pow(2, 52);
const result = (100 * e - h) / (e - h);
// INSTANT_CRASH_PERCENTAGE of 6.66 will result in modifier of 0.934 = 6.66% house edge with a lowest crashpoint of 1.00x
const houseEdgeModifier = 1 - INSTANT_CRASH_PERCENTAGE / 100;
const endResult = Math.max(100, result * houseEdgeModifier);
return Math.floor(endResult);
};
console.log(`Hash: ${gameHash}\n\nGame crashed at ${(crashPointFromHash(gameHash) / 100).toFixed(2)}x`);
And than i want save in database the value, from {(crashPointFromHash(gameHash) / 100).toFixed(2)}
How i can make it?
I hope for your help!

Related

How to convert php function to kotlin android?

I have a project I'm working on that uses an API for it request, but in order to preform them I need to generate the token first.
Before the API was update everything was working, after the update I don't know how to adjust my code to make it work again.
This was the code that worked before the update (Android | Kotlin):
fun hmacHash(str: String, secret: String): String {
val sha256HMAC = Mac.getInstance("HmacSHA256")
val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256")
sha256HMAC.init(secretKey)
return convertToHex(sha256HMAC.doFinal(str.toByteArray()))
}
fun convertToHex(data: ByteArray): String {
val buf = StringBuilder()
for (b in data) {
var halfbyte = (b.toInt() shr 4) and (0x0F.toByte()).toInt()
var two_halfs = 0
do {
buf.append(if (halfbyte in 0..9) ('0'.toInt() + halfbyte).toChar() else ('a'.toInt() + (halfbyte - 10)).toChar())
halfbyte = (b and 0x0F).toInt()
} while (two_halfs++ < 1)
}
return buf.toString()
}
Which was equivalent to this PHP code:
hash_hmac('sha256', $string, $privateKey);
But now after the update the php code looks like this:
hash_hmac('sha256', $string, hex2bin($privateKey));
And I don't know how to adjust my code to make it work with this new change.
From what I can deduce, the PHP code made that change because $privateKey went from being plain text to being hex-encoded. So hex2bin was needed to change it back to plain text (hex2bin changes hex-encoded text to plain text; a confusingly named function if you ask me).
Since your secret is plain text, you don't need to change anything to match. But there are other ways to improve your code. For example, converting a byte array to a hex-encoded string is much easier than that.
fun hmacHash(str: String, secret: String): String {
val sha256HMAC = Mac.getInstance("HmacSHA256")
val bytes = secret.toByteArray()
val secretKey = SecretKeySpec(bytes, "HmacSHA256")
sha256HMAC.init(secretKey)
return convertToHex(sha256HMAC.doFinal(str.toByteArray()))
}
fun convertToHex(data: ByteArray): String =
data.joinToString("") { "%02x".format(it) }

Php Recursive Function Infinite loop Error

I am having a php recursive function to calculate nearest sale price. but i don't know why its run infinite time and throw error of maximum execution.
Its look like below:
function getamazonsaleper($portal)
{
$cp = floatval($this->input->post('cp')); //user provided inputs
$sp = floatval($this->input->post('sp')); //user provided input
$gst = floatval($this->input->post('gst')); //user provided input
$rfsp = floatval($this->input->post('rfsp')); //user provided input
$mcp = (int)($this->input->post('mcp')); //user provided input
$weight = floatval($this->input->post('weight')); //user provided input
$output = $this->getsalepercent($cp,$sp,$gst,$rfsp,$mcp,$weight,$portal);
return $output;
}
function getsalepercent($cp,$sp,$gst,$rfsp,$mcp,$weight,$portal) //recursive funtion
{
$spcost = ((($sp/100)*$cp));
$gstamount= (($spcost/(100+$gst))*$gst);
$rfspamount= ($spcost*($rfsp/100));
$mcpamount= ($cp*($mcp/100));
$fixedfee=$this->getfixedfee($portal,$spcost);
$weightfee=$this->getweightprice($portal,$weight);
$totalcost=$fixedfee+$weightfee+$rfspamount;
$gstinput=($totalcost*(18/100));
$remittances = $spcost-$totalcost-$gstinput;
$actualprofit= $remittances-$cp-$gstamount+$gstinput;
$actualprofitpercent = ($actualprofit/$cp)*100;
if( $actualprofitpercent >= $mcp)
{
return $sp;
}elseif($actualprofitpercent < $mcp)
{
$newsp = (int)($sp+10) ;
$this->getsalepercent($cp,$newsp,$gst,$rfsp,$mcp,$weight,$portal);
}
}
Can anybody tell me how can resolve this issue? Thanks in advance.
Edited :
Perameters
$cp=100;
$sp=200;
$mcp=20;
$weight=0.5;
$gst=28;
$rfsp=6.5;
First a couple of side notes:
- the way you use $gstinput it cancels itself out when you calculate $actualprofit (it's -$gstinput in $remittances which gets added to +$gstinput).
- $mcpamount seems to go completely unused in the code... I thought for a second you might vahe simply confused vars when doing the comparison, but of course for $cp = 100 it makes no difference.
Even so when I made a few calculations using the example values you gave for $sp = 200 (and growing by 10), I got:
Value of $actualprofit, which for $cp = 100 is also the value of $actualprofitpercent...
for $sp = 200:
43.25 - $fixedfee - $weightfee
for $sp = 210:
50.4125 - $fixedfee - $weightfee
for $sp = 220:
57.575 - $fixedfee - $weightfee
so for each $sp = $sp + 10 recursion the value of $actualprofitpercent (without taking into account $fixedfee and $weightfee) seems to grow by 7.1625.
The value of $weightfee should stay the same, but the value of $fixedfee depends on the value of $sp... Could it be that at each recursion getfixedfee() returns a value which grows faster than 7.1625?

How to send array in http get request

private void timer1_Tick(object sender, System.EventArgs e)
{
int iIdx;
int[] iData;
bool[] bData;
if (m_bRegister) // Read registers (4X references)
{
// read register (4X) data from slave
if (adamTCP.Modbus().ReadHoldingRegs(m_iStart, m_iLength, out iData))
{
m_iCount++; // increment the reading counter
txtStatus.Text = "Read registers " + m_iCount.ToString() + " times...";
// update ListView
label1.Text = HttpGet("http://127.0.0.1/misc/api1.php?value0=" + iData[0].ToString());
label2.Text = HttpGet("http://127.0.0.1/misc/api1.php?value1=" + iData[1].ToString());
label3.Text = HttpGet("http://127.0.0.1/misc/api1.php?value2=" + iData[2].ToString());
label4.Text = HttpGet("http://127.0.0.1/misc/api1.php?value3=" + iData[3].ToString());
label5.Text = HttpGet("http://127.0.0.1/misc/api1.php?value4=" + iData[4].ToString());
for (iIdx = 0; iIdx < m_iLength; iIdx++)
{
listViewModbusCur.Items[iIdx].SubItems[2].Text = iData[iIdx].ToString(); // show value in decimal
listViewModbusCur.Items[iIdx].SubItems[3].Text = iData[iIdx].ToString("X04"); // show value in hexdecimal
}
How do i send array using httpget method? The code on top show that i'm sending data one by one. I need to send it in array and retrieve it back in api,php so that i could insert it into database in one row. currently, it's 1 data for 1 row.
Here is a example to convert array to json in PHP
$arr=array(
"varl1"=>1,
"varl2"=>"example",
"varl3"=>3,
);
$json_arr=json_encode($arr);
Now you can send $json_arr
and then you can decode it using json_decode()
you should passing 'value0' become just one querystring, ex : value[]
so the url will become
http://127.0.0.1/misc/api1.php?value[]="+ iData[0].ToString()"&value[]="+ iData[1].ToString() and etc what you want to send it "
or you should use http_build_query to the param array data
the code you show is php ??
the api maybe php but the code style more like .NET c#
correct me if im wrong.
//Update Response
string[] param = new string[(how many your counter param)];
param [0] = "test0";
param [1] = "test1";
param [2] = "test2";
in my example i give you 3
string sParams = JsonConvert.SerializeObject(param) ;
HttpGet("http://127.0.0.1/misc/api1.php?value=" + sParams);

Using R, how to reference variable variables (or variables variable) a la PHP [revisited]

In a previous Using R, how to reference variable variables (or variables variable) a la PHP[post]
I asked a question about something in R analagous to PHP $$ function:
Using R stats, I want to access a variable variable scenario similar to PHP double-dollar-sign technique: http://php.net/manual/en/language.variables.variable.php
Specifically, I am looking for a function in R that is equivalent to $$ in PHP.
The get( response works for strings (characters).
lapply is a way to loop over lists
Or I can loop over and get the values ...
for(name in names(vars))
{
val = vars[[name]];
I still haven't had the $$ function in R answered, although the lapply solved what I needed in the moment.
`$$` <- function
that allows any variable type to be evaluated. That is still the question.
UPDATES
> mlist = list('four'="score", 'seven'="years");
> str = 'mlist$four'
> mlist
$four
[1] "score"
$seven
[1] "years"
> str
[1] "mlist$four"
> get(str)
Error in get(str) : object 'mlist$four' not found
> mlist$four
[1] "score"
Or how about attributes for an object such as mobj#index
UPDATES #2
So let's put specific context on the need. I was hacking the texreg package to build a custom latex output of 24 models of regression for a research paper. I am using plm fixed effects, and the default output of texreg uses dcolumns to center, which I don't like (I prefer r#{}l, so I wanted to write my own template. The purpose for me, to code this, is for me to write extensible code that I can use again and again. I can rebuild my 24 tables across 4 pages in seconds, so if the data change, or if I want to tweak the function, I immediately have a nice answer. The power of abstraction.
As I hacked this, I wanted to get more than the number of observations, but also the number of groups, which can be any user defined index. In my case it is "country" (wait for it, hence, the need for variable variables).
If I do a lookup of the structure, what I want is right there: model$model#index$country which would be nice to simply call as $$('model$model#index$country'); where I can easily build the string using paste. Nope, this is my workaround.
getIndexCount = function(model,key="country")
{
myA = attr(summary(model)$model,"index");
for(i in 1:length(colnames(myA)))
{
if(colnames(myA)[i] == key) {idx = i; break;}
}
if(!is.na(idx))
{
length(unique(myA[,idx]));
} else {
FALSE;
}
}
UPDATES #3
Using R, on the command line, I can type in a string and it gets evaluated. Why can't that internal function be directly accessed, and the element captured that then gets printed to the screen?
There is no equivalent function in R. get() works for all types, not just strings.
Here is what I came up with, after chatting with the R-bug group, and getting some ideas from them. KUDOS!
`$$` <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
`$$`(nstr);
}
}
Below are some example use cases, where I can directly access what the str(obj) is providing... Extending the utility of the '$' operator by also allowing '#' for attributes.
model = list("four" = "score", "seven"="years");
str = 'model$four';
result = `$$`(str);
print(result);
matrix = matrix(rnorm(1000), ncol=25);
str='matrix[1:5,8:10]';
result = `$$`(str);
print(result);
## Annette Dobson (1990) "An Introduction to Generalized Linear Models".
## Page 9: Plant Weight Data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14);
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69);
group <- gl(2, 10, 20, labels = c("Ctl","Trt"));
weight <- c(ctl, trt);
lm.D9 <- lm(weight ~ group);
lm.D90 <- lm(weight ~ group - 1); # omitting intercept
myA = anova(lm.D9); myA; str(myA);
str = 'myA#heading';
result = `$$`(str);
print(result);
myS = summary(lm.D90); myS; str(myS);
str = 'myS$terms#factors';
result = `$$`(str);
print(result);
str = 'myS$terms#factors#dimnames';
result = `$$`(str);
print(result);
str = 'myS$terms#dataClasses#names';
result = `$$`(str);
print(result);
After realizing the back-tick can be a bit tedious, I chose to update the function, calling it access
access <- function(str)
{
E = unlist( strsplit(as.character(str),"[#]") );
k = length(E);
if(k==1)
{
eval(parse(text=str));
} else {
# k = 2
nstr = paste("attributes(",E[1],")",sep="");
nstr = paste(nstr,'$',E[2],sep="");
if(k>2) {
for(i in 3:k)
{
nstr = paste("attributes(",nstr,")",sep="");
nstr = paste(nstr,'$',E[i],sep="");
}
}
access(nstr);
}
}

How to port get_browser() from PHP to ColdFusion?

browscap.ini that get_browser() depends on is found at http://browsers.garykeith.com/downloads
Does anyone know how to port the seemingly simple get_browser() to CFML?
Thanks!
Solved!
This is based on http://forums.adobe.com/thread/620512, and optimized for performance with improved correctness.
It is still quite slow (~1s) because working with ini file with ColdFusion means every getProfileString() is a disk I/O! Might be faster with SSD. :)
function get_browser(user_agent=CGI.HTTP_USER_AGENT, browscap_ini=expandPath("./browscap.ini"))
{
var result = {};
// Read wildcard patterns from the INI file
var browscap_list = getProfileSections(browscap_ini);
// Seed some variables
var browser_champion_pattern = "*";
// Loop through the patterns to find the best match (relative to length of name pattern)
for (var browser_name_pattern in browscap_list)
{
if (len(browser_name_pattern) >= len(browser_champion_pattern))
{
// Massage the wildcard into useable regex
var browser_name_regex = replaceList(browser_name_pattern, ".,*,?,(,),[,]", "\.,.*,.,\(,\),\[,\]");
if (left(browser_name_pattern, 1) != "*")
browser_name_regex = "^" & browser_name_regex;
if (right(browser_name_pattern, 1) != "*")
browser_name_regex &= "$";
// Test the resulting regex against the user agent
if (reFindNoCase(browser_name_regex, user_agent))
browser_champion_pattern = browser_name_pattern;
}
}
// Set the winning regex patterns
var browser_name_pattern = browser_champion_pattern;
// Fetch the winning info
var keynames = listToArray(browscap_list[browser_champion_pattern]);
for (var keyname in keynames)
result[keyname] = getProfileString(browscap_ini, browser_champion_pattern, keyname);
// Fetch the rest of the info from parents
while (structKeyExists(result, "parent"))
{
var parent = result.parent;
structDelete(result, "parent");
var keynames = listToArray(browscap_list[parent]);
for (var keyname in keynames)
if (!structKeyExists(result, keyname))
result[keyname] = getProfileString(browscap_ini, parent, keyname);
}
return result;
}

Categories