I have 3 arrays
arr1 = ['Acc2','Acc2', 'Acc3', 'Acc3', 'Acc3', 'Acc4', 'Acc6', 'Acc6', 'Acc6']
arr2 = ['5','', '', '', '', '', '10', ''. '']
arr3 = ['23','24', '25', '26', '27', '28', '30', '31', '32']
So arr1 contains the account name, arr2 contains the corresponding tier of the account name in arr1 and arr3 contains the corersponding row number of account names in arr1.
So, the values in arr2 and arr3 correspond to the respective values in arr1.
The tier is entered just at the first entry of the account name, for example, for Acc2 the tier 2 is entered correspondingly in arr2 at its first entry and thus its second entry is empty.
Similarly with Acc6, tier in arr2 is entered as 10 and its other two entries are empty.
Now, the tier in arr2 is not entered for Acc3 and Acc4
I want to loop over the arrays and identify for which Account name there is no entry in arr2 present in google apps script.
The output can be a new dictionary with arr3 as keys and value as error or not for the account name
output_dict = { '23' : 'No error',
'24' : 'No error',
'25' : 'Error',
'26' : 'Error',
'27` : 'Error',
'28' : 'Error',
'30' : 'No error',
'31' : 'No error',
'32' : 'No error'
}
Please guide!
Try this
function newDictionary() {
try {
let arr1 = ['Acc2','Acc2', 'Acc3', 'Acc3', 'Acc3', 'Acc4', 'Acc6', 'Acc6', 'Acc6'];
let arr2 = ['5','', '', '', '', '', '10', '', ''];
let arr3 = ['23','24', '25', '26', '27', '28', '30', '31', '32'];
let current = null;
let error = null;
let dictionary = {};
arr1.forEach( (item,index) => {
if( item !== current ) {
current = item;
error = arr2[index] === "" ? "Error" : "No error";
}
dictionary[arr3[index]] = error;
}
)
console.log(dictionary);
}
catch(err) {
console.log(err);
}
}
7:58:25 AM Notice Execution started
7:58:26 AM Info { '23': 'No error',
'24': 'No error',
'25': 'Error',
'26': 'Error',
'27': 'Error',
'28': 'Error',
'30': 'No error',
'31': 'No error',
'32': 'No error' }
7:58:26 AM Notice Execution completed
Reference
Array.forEach()
Related
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 8 months ago.
Improve this question
I have a data containing test results of multiple tests performed at different locations in a general area. I am struggling to write a script that summarizes the results in the following way in a separate tab using Google AppScript:
Test 1 to 3 are mandatory and if they:
all Pass, summary should record Pass
any Fail, summary should record Fail
any Partial Pass, summary should record Partial Pass
any Missing, summary should record Result Missing
Test 4 is optional and can be ignored
Input:
Output:
Description
The following example script will first determine the unique areas. Then for each area examine the test results by row and determine if any fail. Test_4 results are ignored. And Fail takes precedence over Partial Pass.
I've included the execution log with console.log steps along the way to show how the data is reduced.
Code.gs
function test () {
try {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
let values = sheet.getDataRange().getValues();
values.shift(); // remove the headers
values.forEach( row => row.pop() ); // remove Test_4 results
console.log(values);
// get unique areas
let areas = values.map( row => row[0] );
console.log(areas);
areas = [...new Set(areas)]
console.log(areas);
// find results for each area
let results = areas.map( area => [area,"Pass"]);
console.log(results);
values.forEach( row => { let index = areas.findIndex( area => area === row[0] );
let tests = row.slice(2);
if( tests.indexOf("Fail") >= 0 ) {
results[index][1] = "Fail";
return;
}
else if( tests.indexOf( "Partial Pass") >= 0 ) {
results[index][1] = "Partial Pass";
return;
}
else if( tests.indexOf( "" ) >= 0 ) {
results[index][1] = "Results Missing";
return;
}
}
);
console.log(results);
}
catch(err) {
console.log(err);
}
}
Execution log
3:25:42 PM Notice Execution started
3:25:43 PM Info [ [ 'A', 1, 'Pass', 'Pass', 'Pass' ],
[ 'A', 2, 'Pass', 'Pass', 'Pass' ],
[ 'A', 3, 'Pass', 'Pass', 'Pass' ],
[ 'B', 1, 'Pass', 'Pass', 'Pass' ],
[ 'B', 2, 'Fail', 'Pass', 'Pass' ],
[ 'C', 1, 'Pass', 'Pass', 'Pass' ],
[ 'C', 2, 'Pass', 'Pass', 'Fail' ],
[ 'C', 3, 'Pass', 'Pass', 'Pass' ],
[ 'D', 1, 'Pass', 'Pass', 'Pass' ],
[ 'D', 2, 'Pass', 'Partial Pass', 'Pass' ],
[ 'D', 3, 'Pass', 'Pass', 'Pass' ],
[ 'E', 2, '', 'Pass', 'Pass' ] ]
3:25:43 PM Info [ 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E' ]
3:25:43 PM Info [ 'A', 'B', 'C', 'D', 'E' ]
3:25:43 PM Info [ [ 'A', 'Pass' ],
[ 'B', 'Pass' ],
[ 'C', 'Pass' ],
[ 'D', 'Pass' ],
[ 'E', 'Pass' ] ]
3:25:43 PM Info [ [ 'A', 'Pass' ],
[ 'B', 'Fail' ],
[ 'C', 'Fail' ],
[ 'D', 'Partial Pass' ],
[ 'E', 'Results Missing' ] ]
3:25:44 PM Notice Execution completed
Reference
Sheet.getDataRange()
Array.shift()
Array.forEach()
Array.pop()
Array.map()
Set Object
Array.findIndex()
Array.slice()
Array.indexOf()
Using a custom function,
=RESULTFIXING(A2:A10,C2:E10)
Where Col A contains the area and columns C to E contains the data
Create a function to check for empty string or Partial Pass or Fail. If present, use it, else return Pass
Use Array.reduce with Map to create a unique array based on the previous function
Sample script with live test:
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
const resultFixing = (area, data) => {
const compressor = (arr) => {
const out = arr.find((s) =>
['', 'Fail', 'Partial Pass'].some((crit) => s === crit)
);
if (out === '') return 'Result Missing';
return out || 'Pass';
};
return [
...data
.reduce(
(map, arr, i) =>
map.set(
area[i][0],
map.has(area[i][0]) && map.get(area[i][0]) !== 'Pass'
? map.get(area[i][0])
: compressor(arr)
),
new Map()
)
.entries(),
];
};
console.table(
resultFixing(
[/*A2:A7*/['a'], ['a'], ['b'], ['c'], ['c'], ['d']],
[/*C2:D7*/
['Pass', 'Pass'],
['Pass', 'Fail'],
['Partial Pass', 'Pass'],
['Pass', 'Pass'],
['Pass', ''],
['Pass', 'Pass'],
]
)
);
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
i am having two array object as follows. This to be done in a loop using typescript. The both objects are dinamically generated from sql api and filtered
Array of Object 1
customers = [
{
id = '1',
name = 'John',
engg_id = '6'
},
{
id = '2',
name = 'Max',
engg_id = '5'
},
{
id = '3',
name = 'Rob',
engg_id = '6'
},
{
id = '4',
name = 'Rob',
engg_id = '6'
}
]
Array of Object 1
enggNames = [
{
engg_name = 'Surya'
},
{
engg_name = 'Syed'
},
{
engg_name = 'Surya'
},
{
engg_name = 'Surya'
}
]
the above array of object to get append to the customers array of objects as below.
Required Array of Objects
customers = [
{
id = '1',
name = 'John',
engg_id = '6'
engg_name = 'Surya'
},
{
id = '1',
name = 'John',
engg_id = '6'
engg_name = 'Syed'
},
{
id = '1',
name = 'John',
engg_id = '6'
engg_name = 'Surya'
},
{
id = '1',
name = 'John',
engg_id = '6'
engg_name = 'Surya'
}
]
Iterate your two arrays in the same time and spread values in your results array:
const merge = []
for (let i = 0; i < customers.length; i++) {
merge.push({
...customers[i],
...enggNames[i]
})
}
See this working on Stackblitz.
You can try this.
customers = customers.map( (customer, index) => {
customer.engg_name = enggNames[index].engg_name;
return customer;
});
Hope it helps.
You can use .map() to iterate over your data and use Object.assign() to merge properties form multiple objects.
const arr1 = [
{ id: '1', name: 'John', engg_id: '6' },
{ id: '2', name: 'Max', engg_id: '5' },
{ id: '3', name: 'Rob', engg_id: '6' },
{ id: '4', name: 'Rob', engg_id: '6' }
];
const arr2 = [
{ engg_name: 'Surya' },
{ engg_name: 'Syed' },
{ engg_name: 'Surya' },
{ engg_name: 'Surya' }
];
const merge = (a1, a2) => a1.map((o, i) => Object.assign({}, o, a2[i]));
console.log(merge(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am trying to insert hundreds of rows into a MySQL db at once. There are two types of records, unanswered calls and answered calls. I am putting all records into a list of tuples, and each record is it's own tuple, so that I can use the executemany function. I am getting a TypeError: not all arguments converted during string formatting, and I don't understand why.
answered = []
unanswered = []
insertQuery = """ INSERT INTO cdr (recno, relcause, starttime, answertime, endtime, releasecausetext, releasecausecode, 1streleasedialog,
origtrunk, callingnumber, orighost, callednumber, desthost, origcallid, origremotepayloadip, origremotepayloadport,
origlocalpayloadip, origlocalpayloadport, termtrunk, termsourcenumber, termsourcehost, termdestnumber, termdesthostname,
termcallid, termremotepayloadip, termremotepayloadport, termlocalpayloadip, termlocalpayloadport, duration, postdialdelay,
ringtime, durationms, routetableused, origtidalias, termtidalias, termpddms, reasoncause, mappedcausecode, mappedreasoncause,
reasoncausetext, origmos, termmos) VALUES ('%s'); """
for y in cdrList:
#Check to make sure record does not exist
sqlQuery = "select * from cdr where recno = %d and origcallid = %s;" % (int(y[0]), y[13])
if cursor.execute(sqlQuery):
print("Record exists")
else:
if y[7]=='NA':
unanswered.append((y[0], y[5],extractSqlDate(y[6]), 'null', extractSqlDate(y[8]), y[10], y[11], y[12], y[13], y[15], y[16], y[17], y[18], y[19], y[20], y[21], y[22], y[23], y[32], y[34], y[35], y[36], y[37], y[38], y[39], y[40], y[41], y[42], y[53], y[54], y[55], y[56], y[60], y[66], y[67], y[71], y[78], y[79], y[80], y[81], y[85], y[88]))
else:
answered.append((y[0], y[5],extractSqlDate(y[6]), extractSqlDate(y[7]), extractSqlDate(y[8]), y[10], y[11], y[12], y[13], y[15], y[16], y[17], y[18], y[19], y[20], y[21], y[22], y[23], y[32], y[34], y[35], y[36], y[37], y[38], y[39], y[40], y[41], y[42], y[53], y[54], y[55], y[56], y[60], y[66], y[67], y[71], y[78], y[79], y[80], y[81], y[85], y[88]))
try:
print(answered)
cursor.executemany(insertQuery, answered)
cursor.executemany(insertQuery, unanswered)
db.commit()
print("Record inserted successfully")
except MySQLdb.Error as e:
print(e)
I have confirmed that each element in each tuple in the list is a string:
Successfully connected to database
/PATH/20190610/20190610-0015-1750147245-1750147250.cdr
[('1750147245', '0001', '2019-06-10 00:10:50', '2019-06-10 00:10:59', '2019-06-10 00:11:13', 'Normal BYE', ' 200', 'O', '001102', '+tn', 'ip', '+tn', 'ip', '273418599_83875291#ip', 'ip', '20530', 'ip', '11944', '000020', '+tn', 'ip', 'tn', 'ip', '4121333-0-2851866068#ip', 'ip', '16840', 'ip', '11946', '13', '1', '8', '13450', '50', 'C - Peerless C6933_04 Origin', 'P - Thirdlane 6', '1150', '', '200', '', '', '0', '0')]
I found the problem. The tuple was returning strings, so the insert query was trying to insert values like this: ''value''. I removed the ' around the %s, and, based on #jonrsharpe's comment, added %s for each other value, and it worked.
Am trying to build an multi-row insert query using Knex.js
My post request contains a variable which is formatted in the following format : [{addon_name:'sugar'},{addon_name:'milk'}]
My DB table has only one column namely addon_name
My knex query in my node application goes as follows
knex(`<table_name>`).insert(req.body.`<param_name>`))
expected op
insert into `<tablename>`(`addon_name`) values (sugar), (milk);
but the code dosn't work. Any comments ?
Error Details
{ [Error: insert into `table_name` (`0`, `1`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`, `2`, `20`, `21`, `22`, `23`, `24`, `25`, `26`, `27`, `28`, `29`, `3`, `30`, `31`, `32`, `33`, `34`, `35`, `36`, `37`, `38`, `39`, `4`, `40`, `41`, `5`, `6`, `7`, `8`, `9`) values ('[', '{', 'm', 'e', ':', '\'', 's', 'u', 'g', 'a', 'r', '\'', 'a', '}', ',', '{', 'a', 'd', 'd', 'o', 'n', '_', 'n', 'd', 'a', 'm', 'e', ':', '\'', 'm', 'i', 'l', 'k', '\'', 'd', '}', ']', 'o', 'n', '_', 'n', 'a') - ER_BAD_FIELD_ERROR: Unknown column '0' in 'field list']
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlState: '42S22',
index: 0 }
Though this is an old question, I am replying here just for others who stumble upon this.
Knex now supports multi-row inserts like this:
knex('coords').insert([{x: 20}, {y: 30}, {x: 10, y: 20}])
outputs:
insert into `coords` (`x`, `y`) values (20, DEFAULT), (DEFAULT, 30), (10, 20)
There's also the batchInsert utility will inserts a batch of rows wrapped inside a transaction.
req.body.<param_name> is always a string. Most probably this will work for you:
knex(table_name).insert(JSON.parse(req.body.param_name)));
What you are seeing in your error is Knex treating the string as an array of chars, trying to push it to the table.
In the error, the following:
values ('[', '{', 'm', 'e', ':', '\'', 's', ...
Is actually your string being broken down: [{me:\'s....
Thanks. I changed the structure of my input in post method, to an comma separated string. That way it gets easier to parse the input and model it the way I need.
post method input : "milk,sugar"
code
//Knex accepts multi row insert in the following format [{},{}] => we need to
//model our input that way
var parsedValues = [];
try {
var arr = req.body.addons.split(',');
}catch(err){
return res.send({ "Message": "405" }); // Data not sent in proper format
}
for (var i in arr) {
parsedValues.push({addon_name: arr[i]});
}
console.log(parsedValues);
knex(`<table_name>`).insert(parsedValues).then(function (rows){
console.log(rows);
return res.send({ "Message": "777" }); // Operation Success
}).catch(function (err){
console.log(err)
return res.send({ "Message": "403" }); // PK / FK Violation
});
You can use batch insert
DB.transaction(async (t: Knex.Transaction) => {
return await t
.batchInsert("addon_name", addon_nameRecords)
.returning("id");
});
i am getting errors on my config.php file , it started giving me errors 1 day ago.
So the errors are:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/x/public_html/rx/includes/config.php on line 32
Warning: Cannot modify header information - headers already sent by (output started at /home/x/public_html/rx/includes/config.php:32) in /home/x/public_html/rx/includes/config.php on line 38
My config php file is the next:
<?php
session_start();
include 'connection.php';
include 'functions.php';
$logged_in = 0;
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
$username = sec($_SESSION['username']);
$password = sec($_SESSION['password']);
$udata = get_row("SELECT * FROM playeraccounts WHERE playerName='$username' && playerPassword='$password'");
if(isset($udata['playerID']))
{
$logged_in = 1;
if(isset($_GET['logout']))
{
unset($_SESSION['username']);
unset($_SESSION['password']);
mysql_query("UPDATE playeraccounts SET rpgon=0 WHERE playerName='$username'");
header('location: index.php');
}
}
}
function redirect_not_logged()
{
$username = sec($_SESSION['username']);
$password = sec($_SESSION['password']);
$udata = get_row("SELECT * FROM playeraccounts WHERE playerName='$username' && playerPassword='$password'");
$id = $udata['playerID'];
$q = mysql_query("SELECT * FROM `playeraccounts` WHERE playerID = $id");
while($row = mysql_fetch_array($q))
{
$rpg = $row['rpgon'];
}
if($rpg == 0)
{
header('location: login.php');
}
}
// vars
$member_types = array(
'Civilian',
'Los Santos Police Department',
'F.B.I',
'National Guard',
'Paramedic Department',
'Guvernment',
'The Russian Mafia',
'Grove Street',
'Los Aztecas',
'The Riffa',
'Ballas',
'Los Vagos',
'Hitman Agency',
'School Instructors',
'Taxi Company',
'News Reporters',
'Las Barrancas Taxi Company',
'Las Barrancas Paramedic Department'
);
$shop_types = array(0,
'Bullet',
'Cheetah',
'FCR-900',
'Clear 10FP',
'Golden Account',
'Infernus',
'Change Nick',
'Turismo',
'Clear 1 Warn',
);
$rank = array(
'Civil',
'Rank 1',
'Rank 2',
'Rank 3',
'Rank 4',
'Rank 5',
'Rank 6',
'Leader'
);
$account_types = array(
'No',
'Yes'
);
$status_types = array(
'<font color="#FF0000">Offline</font>',
'<font color="#0DFF00">Online</font>',
'<font color="#FEC300">Sleep</font>'
);
$status1_types = array(
'<font color="#FF0000">•</font>',
'<font color="#0DFF00">•</font>',
'<font color="#0DFF00">•</font>'
);
$ban_type = array(0, 'N', 'I');
$admins56 = array(0, 'Trial Admin', 'Junior Admin', 'General Admin', 'Head Admin', 'Lead Admin', 'Manager');
$helpers56 = array(0, 'Trial Helper', 'Helper', 'Lead Helper');
?>
I can't find what is wrong , also the redirect_not_logged function isn't working anymore , since i get this 2 errors..
playerID is the number of the row wich is situated in playeraccounts.