Use of a string to get information in an associative array - actionscript-2

I've got a function that takes two strings as arguments, and I want to use these arguments to get the data held in associative arrays.
var myVar:Object = {};
myVar.value = 10;
function getStuff(v:String, vl:String){
//...
}
In this case, v = "myVar" and vl = "value".
How do I translate vinto the variable name 'myVar' and v1 into 'value' so that I can access the data?

Sorry if this won't work, for I can only test AS3 here, but please try this:
function getStuff(v:String, vl:String){
return eval(v + "." + vl);
}
eventually
function getStuff(v:String, vl:String){
return eval("_gobal." + v + "." + vl);
}

Related

Unable to Pass Two Parameters as Argument to Javascript Function

I am trying to use karate.call to invoke function of a JS file receiving two arguments (String, Array of String). However the array of string would not be passed on to the JS file.
The JS file contains:
function(query, fragments) {
// Here lies some code
// One of them includes fragments.length;
}
And I call the JS function on another JS file in this way:
//var query = 'Some string';
//var fragments = ['fragment1', 'fragment2'];
var clean = karate.call('../helper/helper.js', [query, fragments]);
I am able to pass query which is a string. But I was unable to pass the array of string. The error says:
TypeError: Cannot read property "length" from undefined
It seems the array of string did not get passed to the JS function. Any help will be greatly appreciated. Thanks!
You can read you function first and invoke is just like any other js function
var myFun = karate.read('../helper/helper.js');
var funCall = myFun(query, fragments);
or
var myCall = karate.read('../helper/helper.js')(query, fragments);
this should work.
.call takes parameters as comma separated values , you need to use .apply if you want to pass values as an array.
var clean = karate.call('../helper/helper.js', query, fragments);
will work...
The answers here are missing an important clarification:
I often do single arg functions like:
* def concatParams =
"""
function(s) {
return "urldt=" + todaysDate + "&caseid=" + s.caseid
}
"""
And I will call that like so:
* def params = call concatParams {caseid: '3433344'}
But, when I want to do 2 params, I will define a function like so:
* def concatParams =
"""
function(d,s) {
return "urldt=" + d.date + "&caseid=" + s.caseid
}
"""
And unintuitively, neither of these will work:
* def params = call concatParams {date: '01/01/2020', caseid: '3433344'}
* def params = call concatParams '01/01/2020' '3433344'
To get it to work, instead I call it like this:
* def params = concatParams('01/01/2020', '3433344')
Documentation does not clarify this.
var clean = karate.call('../helper/helper.js', query, fragments);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
call method accepts comma separated params and apply accept array so you need to replace call into apply. your code looks like
function karate(query, fragments) {
// Here lies some code
// One of them includes fragments.length;
}
var clean = karate.apply('../helper/helper.js', [query, fragments]);

Kotlin: how to swap character in String

I would like to swap a string from "abcde" to "bcdea". So I wrote my code as below in Kotlin
var prevResult = "abcde"
var tmp = prevResult[0]
for (i in 0..prevResult.length - 2) {
prevResult[i] = prevResult[i+1] // Error on preveResult[i]
}
prevResult[prevResult.length-1] = tmp // Error on preveResult[prevResult.lengt-1]
It errors out as stated above comment line. What did I do wrong? How could I fix this and get what I want?
Strings in Kotlin just like in Java are immutable, so there is no string.set(index, value) (which is what string[index] = value is equivalent to).
To build a string from pieces you could use a StringBuilder, construct a CharSequence and use joinToString, operate on a plain array (char[]) or do result = result + nextCharacter (creates a new String each time -- this is the most expensive way).
Here's how you could do this with StringBuilder:
var prevResult = "abcde"
var tmp = prevResult[0]
var builder = StringBuilder()
for (i in 0..prevResult.length - 2) {
builder.append(prevResult[i+1])
}
builder.append(tmp) // Don't really need tmp, use prevResult[0] instead.
var result = builder.toString()
However, a much simpler way to achieve your goal ("bcdea" from "abcde") is to just "move" one character:
var result = prevResult.substring(1) + prevResult[0]
or using the Sequence methods:
var result = prevResult.drop(1) + prevResult.take(1)
You can use drop(1) and first() (or take(1)) to do it in one line:
val str = "abcde"
val r1 = str.drop(1) + str.first()
val r2 = str.drop(1) + str.take(1)
As to your code, Kotlin String is immutable and you cannot modify its characters. To achieve what you want, you can convert a String to CharArray, modify it and then make a new String of it:
val r1 = str.toCharArray().let {
for (i in 0..it.lastIndex - 1)
it[i] = it[i+1]
it[it.lastIndex] = str[0] // str is unchanged
String(it)
}
(let is used for conciseness to avoid creating more variables)
Also, you can write a more general version of this operation as an extension function for String:
fun String.rotate(n: Int) = drop(n % length) + take(n % length)
Usage:
val str = "abcde"
val r1 = str.rotate(1)
Simpler solution: Just use toMutableList() to create a MutableList of Char and then join it all together with joinToString.
Example:
Given a String input, we want to exchange characters at positions posA and posB:
val chars = input.toMutableList()
val temp = chars[posA]
chars[posA] = chars[posB]
chars[posB] = temp
return chars.joinToString(separator = "")
Since Strings are immutable, you will have to copy the source string into an array, make changes to the array, then create a new string from the modified array. Look into:
getChars() to copy the string chars into an array.
Perform your algorithm on that array, making changes to it as needed.
Convert the modified array back into a String with String(char[]).

LINQ Where clause Multiple conditions

Im trying to get all the data rows that contain a certain set of data.
In my database i have some values, including start and length.
I have an array that contains integers called startTimes and another called endTimes.
I need a where clause that would return the records that have a start value contained in startTimes, OR start+length contained in endTimes.
Is there any way to do this?
Thanks
IQueryable<request> proposedRequest = db.requests.Include(r => r.rooms);
proposedRequest = proposedRequest.Where(r=>r.booked.Equals(1));
proposedRequest = proposedRequest.Where(r=>r.roundID.Equals(roundID))8;
proposedRequest = proposedRequest.Where(r=>r.day.Equals(day));
int[] startTimes;
int[] endTimes;
for(var q=0;q<time;q++){
startTimes[startTimes.Length] = time + q;
endTimes[endTimes.Length] = time + q + 1;
}
proposedRequest = proposedRequest.Where(//what goes in here);
i have an array startTime=[1,3,4] and an array endTime=[2,4,5] lets
say. I need to see if any of those values match my records? I dont
think the above would do the job
To check if you have value in Array of int, Use the Contains Method:
proposedRequest = proposedRequest.Where(s => startTimes.Contains(s.INT_ID)
|| endTimes.Contains(s.INT_ID));
Syntax: ARRAY.Contains(ID_TO_SEARCH)
it returns a boolean:
var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);
will something like this suffice?
var data = collection.Where(
t => startTimes.Contains(t.theTime) ||
endTimes.Contains(t.theTime + theLength));
proposedRequest.Where(pr => startTimesArray.Contains(pr.start) || endTimesArray.Contains(pr.start + pr.length));

DataContext.ExecuteQuery<object> returns object {}

I'm trying to write function for selecting optional columns in linq(columns that may not exist). The problem is in linq like this:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? t.B : -1; //this is optional column
}}
Unfortunately, this won't work because the fragment near Optional will be translated to case statement and error arises that column not exists.
So i decided to "cover" it with function:
using (DataDataContext db = new DataDataContext()){
var collection = from t in table
select new
{
Nonoptional = t.A;
Optional = IsInDB("table","B") ? OptionalColumnValue<int>("table","B","id_table",t.id_table) : -1; //this is optional column
}}
I want this function to be universal. It should work like that" If there is no value or column is nullable and value is null then return default value for type.
I came up with something like this:
//table,column - obvious,id_column - PK column of table, id - id of currently processing record
public static T OptionalColumnValue<T>(string table,string column,string id_columm,int id) T t = default(T);
DataDataContext db = new DataDataContext();
IEnumerable<object> value = db.ExecuteQuery<object>("select " + column + " from " + table + " where " + id_columm + " = " + id.ToString());
List<object> valueList = value.ToList();
if (valueList.Count == 1)//here is the problem
t = (T)valueList.First();
return t;
}
When there is null value db.ExecuteQuery return something like object{}. I'm assuming this is "empty" object,with nothing really in there. I was thinking about checking for "emptiness" of this object( BTW this is not DBull).
When i realised that this is no way either with concrete value in this column(it cannot cast it to return correct type), then I tried db.ExecuteQuery<T>. Then concrete value - OK, null - Exception.
I thought, maybe Nullable<T> as return value. Nop, because string also can be T.
I don't know what to do next. Maybe there's another solution to this problem.

Invalid parameter number: number of bound variables does not match number of tokens PDO insert

function mysql_insert($data_array){
$sql = "insert into `". $this->table_name. '`';
$array_keys = array_keys($data_array);
$array_keys_comma = implode(",\n", preg_replace('/^(.*?)$/', "`$1`", $array_keys));
for($a=0,$b=count($data_array); $a<$b; $a++){ $question_marks .="?,"; }
$array_values = array_values($data_array);
$array_values_comma = implode(",", $array_values);
$sql.= " ($array_keys_comma) ";
$sql.= " values(". substr($question_marks, 0,-1) .")";
$prepare = $this->connDB->prepare($sql);
$insert = $prepare->execute(array($array_values_comma));
}
I want to creat like this universal functions, $data_array-comes from $_POST
This function will work for all form. But i dont know what is my wrong :S
I don't know what is my wrong
That's quite easy to know: number of bound variables does not match number of tokens.
I want to creat like this universal functions, $data_array-comes from $_POST
Here you go: Insert/update helper function using PDO
$array_values_comma is a scalar after you implode() the array. So you always pass an array of one element to your execute() function. You should pass $array_values.
Here's how I'd write this function:
function mysql_insert($data_array){
$columns = array_keys($data_array);
$column_list_delimited = implode(",",
array_map(function ($name) { return "`$name`"; }, $columns));
$question_marks = implode(",", array_fill(1, count($data_array), "?"));
$sql = "insert into `{$this->table_name}` ($column_list_delimited)
values ($question_marks)";
// always check for these functions returning FALSE, which indicates an error
// or alternatively set the PDO attribute to use exceptions
$prepare = $this->connDB->prepare($sql);
if ($prepare === false) {
trigger_error(print_r($this->connDB->errorInfo(),true), E_USER_ERROR);
}
$insert = $prepare->execute(array_values($data_array));
if ($insert === false) {
trigger_error(print_r($prepare->errorInfo(),true), E_USER_ERROR);
}
}
A further improvement would be to do some validation of $this->table_name and the keys of $data_array so you know they match an existing table and its columns.
See my answer to escaping column name with PDO for an example of validating column names.