Algorithm to Organize Array - arrays

Here's the problem:
I have an array that has information about users. Each entry is separated by a blank field in the array.
For this example let's say the data fields are ID, first, last, phone, and email. However, if a user doesn't have a value for a particular field, then it is omitted entirely.
So here is what the array looks like
users[0] = 45049345
users[1] = Bob
users[2] = Smith
users[3] = 789-456-1230
users[4] = bob#gmail.com
users[5] =
users[6] = 63515987
users[7] = Joe
users[6] = Schmoe
users[8] = joe#gmail.com
users[9] =
I want to loop this array and store the data for each user in a database, however I have no clue how to verify that I am storing the right information in the place because there is no pattern in the array. Since Joe doesn't have a phone number, his email is would be stored as his phone number. This would result in ever subsequent entry to be off by 1 index.
Any ideas on how to go about this?
P.S. I am using node.js
EDIT: here is an example of the actual data
021870143-14
lastName
firstName
U
5/16/1988
11/6/2008
A
11/6/2008 6:0:2
NF
245
MAIN ST.
101
NEW YORK
NY
10002
11/4/2008
34
SD1
MUNC1J-036
MAG1-1
LEG77
SENT34
CONG5
CNTY
34-1
10/27/2008 19:59:53
NF

Here's pseudo code because I don't know javascript. I'm basing this off the fact that I think Javascript has dictionaries/associative arrays/hash tables etc.
new_user = {}
for i from 0 to arr.length
if arr[i] = null/Omitted field/nil/None/whatever
database.add_entry(new_user) // Add finished user table to database
new_user = {} // Start new dictionary
else
field = arr[i]
if field contains '#'
new_user.email = field
else if field contains '-'
new_user.phone_number = field
else if is_a_number(field)
new_user.id = field
else if new_user has first_name
new_user.last_name = field
else
new_user.first_name = field

Use tokenization ..
example:
users[0] = "45049345,Bob,Smith,789-456-1230,bob#gmail.com";
users[1] = "63515987,Joe,Schmoe,-,joe#gmail.com";
Process:
for (user in users)
{
for (detail in user)
{
document.write (detail + "<br>");
}
}

Related

Csv file to a Lua table and access the lines as new table or function()

Currently my code have simple tables containing the data needed for each object like this:
infantry = {class = "army", type = "human", power = 2}
cavalry = {class = "panzer", type = "motorized", power = 12}
battleship = {class = "navy", type = "motorized", power = 256}
I use the tables names as identifiers in various functions to have their values processed one by one as a function that is simply called to have access to the values.
Now I want to have this data stored in a spreadsheet (csv file) instead that looks something like this:
Name class type power
Infantry army human 2
Cavalry panzer motorized 12
Battleship navy motorized 256
The spreadsheet will not have more than 50 lines and I want to be able to increase columns in the future.
Tried a couple approaches from similar situation I found here but due to lacking skills I failed to access any values from the nested table. I think this is because I don't fully understand how the tables structure are after reading each line from the csv file to the table and therefore fail to print any values at all.
If there is a way to get the name,class,type,power from the table and use that line just as my old simple tables, I would appreciate having a educational example presented. Another approach could be to declare new tables from the csv that behaves exactly like my old simple tables, line by line from the csv file. I don't know if this is doable.
Using Lua 5.1
You can read the csv file in as a string . i will use a multi line string here to represent the csv.
gmatch with pattern [^\n]+ will return each row of the csv.
gmatch with pattern [^,]+ will return the value of each column from our given row.
if more rows or columns are added or if the columns are moved around we will still reliably convert then information as long as the first row has the header information.
The only column that can not move is the first one the Name column if that is moved it will change the key used to store the row in to the table.
Using gmatch and 2 patterns, [^,]+ and [^\n]+, you can separate the string into each row and column of the csv. Comments in the following code:
local csv = [[
Name,class,type,power
Infantry,army,human,2
Cavalry,panzer,motorized,12
Battleship,navy,motorized,256
]]
local items = {} -- Store our values here
local headers = {} --
local first = true
for line in csv:gmatch("[^\n]+") do
if first then -- this is to handle the first line and capture our headers.
local count = 1
for header in line:gmatch("[^,]+") do
headers[count] = header
count = count + 1
end
first = false -- set first to false to switch off the header block
else
local name
local i = 2 -- We start at 2 because we wont be increment for the header
for field in line:gmatch("[^,]+") do
name = name or field -- check if we know the name of our row
if items[name] then -- if the name is already in the items table then this is a field
items[name][headers[i]] = field -- assign our value at the header in the table with the given name.
i = i + 1
else -- if the name is not in the table we create a new index for it
items[name] = {}
end
end
end
end
Here is how you can load a csv using the I/O library:
-- Example of how to load the csv.
path = "some\\path\\to\\file.csv"
local f = assert(io.open(path))
local csv = f:read("*all")
f:close()
Alternative you can use io.lines(path) which would take the place of csv:gmatch("[^\n]+") in the for loop sections as well.
Here is an example of using the resulting table:
-- print table out
print("items = {")
for name, item in pairs(items) do
print(" " .. name .. " = { ")
for field, value in pairs(item) do
print(" " .. field .. " = ".. value .. ",")
end
print(" },")
end
print("}")
The output:
items = {
Infantry = {
type = human,
class = army,
power = 2,
},
Battleship = {
type = motorized,
class = navy,
power = 256,
},
Cavalry = {
type = motorized,
class = panzer,
power = 12,
},
}

Prestashop - how to set custom tax for products of one manufacturer?

My prestashop site has different manufacturers and I want to set 20% TAX/VAT for products of one manufacturer and don't effect the rest of manufacturers. Which way and how could I do it? Let's say the manufacturer identified by it's id - manufacturer_id = 1.
UPDATE ps_product_shop ps
LEFT JOIN
ps_product p ON ps.id_product = p.id_product
SET
ps.id_tax_rules_group = XXX
WHERE
p.id_manufacturer = 1;
replace XXX with actual tax rules id.
You need to repeat this update query for ps_product table to have consistent data.
must be online file upload on your website and call
require_once('config/defines.inc.php');
$id_tax_rules = XXXX; // ID TAX RULES GROUP
$id_manufacturer = 1; // ID MANUFACTURER
Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'product_shop SET id_tax_rules_group = '.$id_tax_rules.' WHERE id_manufacturer = '.$id_manufacturer);
Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'product SET id_tax_rules_group = '.$id_tax_rules.' WHERE id_manufacturer = '.$id_manufacturer);
?>
Regards

How to avoid inserting duplicate contacts(using email check) in salesforce using apex batch?

I am trying to insert new contacts and leads in salesforce using external api call in apex batch. I am running once in a day and inserting 500 contacts or leads in salesfoce.
But my batch file is inserting duplicate contacts with same email address. I want to skip contact or lead records to insert when same email id already exists with another record.
If I check email address using query for each record then the SOQL query limit will be a problem.
How I can avoid duplicate insert in contacts or lead in salesforce.
Thanks in Advance
Rajendra J.
Apex code:
request.setMethod('GET');
request.setTimeout(120000);
request.setEndpoint('http://api.nurturehq.com/contacts/many?nurture_id='+last_insert_id+'&limit=10&auth_token='+obj_authentication.nurture_authentication_key__c);
request.setHeader('X-Api-Version', '2.0');
request.setHeader('X-Access-Id', 'APP_ID3MVG9A2kN3Bn17hvx6UytrOeZp67_J835ecdoZ5eJmyC_BQS227UFPVb5KgNJW7YpVd9oTA6sCJ19msqZQ9sY');
request.setHeader('X-Access-Secret', 'SECRET_KEY4317178691269588217');
JSONParser parser = JSON.createParser(response.getBody());
// system.debug('jsondataaaa'+parser);
NurtureSingleton__c nurSingle = [SELECT nurture_last_insert_contact_id__c FROM NurtureSingleton__c limit 1];
List listContacts = new List();
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.START_OBJECT){
Contacts cnts = (Contacts)parser.readValueAs(Contacts.class);
first_name=cnts.first_name;
last_name=cnts.last_name;
if(String.isEmpty(first_name)) {
first_name='-';
}
if(String.isEmpty(last_name)) {
last_name='-';
}
listContacts.add(new Contact(FirstName = first_name , LastName = last_name,Email=cnts.email,Title=cnts.title,Birthdate=cnts.birthdate,Phone=cnts.phone,
MobilePhone=cnts.mobile,Fax=cnts.fax,Description=cnts.description,LeadSource=cnts.lead_source,MailingCity=cnts.city,MailingState=cnts.state,
MailingPostalCode = cnts.zip, MailingCountry = cnts.country,Department=cnts.department,Salutation=cnts.Salutation,
MailingStreet=cnts.address,Nurture_contact_id__c=cnts.id,AccountId=cnts.salesforce_account_id));
nurSingle.nurture_last_insert_contact_id__c = cnts.id;
//insert listContacts;
}
}
}
}
insert listContacts;
you stated that
"But my batch file is inserting duplicate contacts with same email address."
Question here is , is it a duplicate or just the same email address?
You will need to compare the whole record or at least first name , last name email and phone
Enterprise businesses will have point of contact emails, meaning that Mr smith Mrs Yong and other can and will have an email like support#... or Info#..... and customer-care#..
So a simple validation on Email can't work if you have already one person in the list but another lead comes up.
Imaging a hospital that got AandE#xyzhospital.com , now you are selling health / hygiene products and selling direct to doctors, you are already selling to 2 doctors there and a 3rd ( a new lead joins) but you can only reach them under AandE#xyzhospital.com , the new lead would not be created as you only compare the email address

Drupal custom file type for invoice

I have a content type 'invoice'
I want to add a field invoice_number for example: ABC2012001
ABC: prefix,
2012: changes Every year,
001 : nr of invoice (reset every year)
THE field is autoincrement.
How can I do this? Is it possible without programming or do I have to use THE hook functions?
You could do this with a custom module using the node_presave hook. The users only enter the prefix value into the 'invoice_number' field. Before the node is saved to the database your hook does the following:
if the node is of type 'invoice' and has not yet been saved 'nid == 0'
gets the current year
gets the current number of invoices for this year (either from a stored variable or a database query)
alters the field value and appends the year/number
So something along the lines of this:
<?php
function mymodule_node_presave($node){
if (($node->type == 'invoice') && ($node->nid == 0)) { //node has not been saved
//get the current year
$this_year = date('Y');
if ($count = variable_get('invoice_count_'.$this_year,0)){
//have the invoice number
}else{
//get the number of invoices created this year from DB
$count_query = "SELECT COUNT(DISTINCT nid)) FROM {node} WHERE type = :type AND FROM_UNIXTIME(created,'%Y') = :year";
$count = db_query($count_query,array(':type'=>'invoice',':year'=>$this_year))->fetchField();
}
$invoice_count = $count;
//append number with 0's?
$invoice_count = str_repeat('0',(3-strlen($invoice_count))).$invoice_count;
//alter the field value and append the year.number
$node->field_invoice_number['und'][0]['value'].=$this_year.$invoice_count;
//save the increment
variable_set('invoice_count_'.$this_year,($count+1));
}
}

How to allocate an ID

I want to get user ID 5005 for myself. I read that with GAE you can allocate an ID and set it but I don't fully understand the documentation.
The code is
handmade_key = db.Key.from_path('MyModel', 1)
first_batch = db.allocate_ids(handmade_key, 10)
first_range = range(first_batch[0], first_batch[1] + 1)
my_id = first_range.pop(0)
new_key = db.Key.from_path('MyModel', my_id)
new_instance = MyModel(key=new_key)
new_instance.put()
assert new_instance.key().id() == my_id
But where do I put that I want 5005 as the user ID? The model is the user model from webapp2.
You can allocate specific ids range using allocate_id_range, and then you should be able to construct the Key manually using Key.from_path by supplying your own id, and assign it to your new Model instance using the key argument.

Resources