may I know is it possible the shipping fees is calculated by kilometer within a distance from my coordinate location?
For example, i already set a coordinate location that would be my physical store, and my shipping area only can deliver within 20 kilometer from my location.
How am i suppose to let customer can only choose the shipping area within 20 km from my location, and set a shipping fees on it?
Please help. Much appreciated and thank you all.
If you only need rough numbers and don't care if it's 20 or 23 km then you can use post codes.
If you want to you can "fine tune" each post code with street, and if needed with house number.
$UserPostCode = 12345;
$UserStreet = "3-street";
$Postcodes = [
"11111" => [
"A-street" => 12,
"B-street" => 10,
"C-street" => 15,
"Default" => 11
],
"12345" => [
"1-street" => 5,
"2-street" => 6,
"3-street" => 7,
"Default" => 5
]
];
if(isset($PostCodes[$UserPostCode])){
// post code is within your range
if(isset($PostCodes[$UserPostCode][$UserStreet])){
// you have a price set for this street
echo $PostCodes[$UserPostCode][$UserStreet]; //7
}else{
// This is a new street in the postcode unknown to you, give default price
echo $PostCodes[$UserPostCode]["Default"];
}
}else{
// customer lives out of range
echo "Sorry can't deliver to you";
}
As I wrote above you can fine tune the streets to house number 1-50 and 50 and higher if you like with the same logic as above.
Related
I am learning JavaScript for WordPress Websites, but I am only asked for the formula without including HTML or CSS fields, I just need the JS.
I need to create a formula to take a quantity [quantity] multiply it by the base price [base price] and then subtract the [discount] based on the following list they give me.
If you buy:
1 = 4
2 to 10 = 3.4
11 to 50 = 3.0
From 51 to 100 = 2.75
From 101 to 1000 = 2.50
This is the code I have been able to create but it only gives me the price until it reaches 10.
It is an exercise or an example, because I am learning how to create the code... the goal is to make the list above.
(function(){
if([field id="quantity"]<=10)
{
return 4;
}
else if(10>[field id="quantity"] && [field id="quantity"]<=20)
{
return 3.5;
}
else
{
return 0;
}
})() * [field id="quantity"]
Here is an example I made to give you an idea of the structure:
Loan Calculator Form | Monthly Payment:
[field id="amount"]*([field id="annual_interest"]/1200)/(1-(Math.pow(1/(1+([field id="annual_interest"]/1200)),([field id="repayment_period"]*12))))
List of available static mathematical methods I was given to use
Url of this list: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math?retiredLocale=vi#static_methods
I would like you to show me some examples of quantity discounts to learn how to handle the tools involved in performing this equation.
I have a set of text messages. Lets call them m1, m2, ..... The maximum number of message is below 1,000,000. Each message is below 1024 characters in length, and all are in lowercase. Lets also pick an n-gram s1.
I need to find frequency of all possible substring from all of these messages. For example, lets say we have only two messages:
m1 = a cat in a cage
m2 = a bird in a cage
The frequency of some n-gram in these two messages:
'a' = 4
'in a cage' = 2
'a bird' = 1
'a cat' = 1
...
Note that, as in = 2, in a = 2, and a cage = 2 are subsets of in a cage = 2 and have same frequency, they should not be listed. Only take the longest one that have the highest frequency; follow this condition: the longest sn-gram should consist of at most 8 words, with a total character count below 30. If a n-gram exceeds this limit, it can be broken into two or more n-grams and listed separately.
I need to find such n-grams for all of these text messages and sort them by their number of occurrences in descending order.
How to I approach this problem? I need a solution in javascript.
PS: I need help, but do not know to where to ask this. If the question
is not for this site, then where should I post it? please guide this
newbie here.
May be you can approach as follows. I will edit to add explanation as soon as i have some time.
var subSentences = (w,...ws) => ws.length ? ws.reduce((r,s) => (r.push(r[r.length-1] + ` ${s}`), r),[w])
.concat(subSentences(...ws))
: [w],
frequencyMap = sss => sss.reduce((map,ss) => subSentences(...ss.split(/\s+/)).reduce((m,s) => m.set(s, m.get(s) + 1 || 1), map), new Map());
frequencies = frequencyMap(["this is a test string",
"this is another one",
"yet another one is here"]);
console.log(...frequencies.entries()); // logging map object seems not possible hence entries
.as-console-wrapper { max-height : 100% !important
}
I do not have any control over modifying the server endpoint to return a valid JSON.
Endpoint: http://newsrack.in/stories/servelots/iihs_feeds/16.json
sample response data:
`var _nr_metadata = {
site_base_url : "http://newsrack.in",
issue_name : "iihs_feeds",
category_name : "Chikungunya",
listing_url : "/stories/servelots/iihs_feeds/16"
}
var _nr_stories = [
{
title : "Delhi: Changing weather conditions cause 25 per cent rise in dengue cases",
url : "http://indiatoday.intoday.in/story/delhi-changing-weather-conditions-cause-rise-in-dengue-cases/1/1075570.html",
source : "India Today| Must Read",
date : "26.10.2017",
desc : "<a href=\'http://indiatoday.intoday.in/story/delhi-changing-weather-conditions-cause-rise-in-dengue-cases/1/1075570.html?utm_source=rss\'><img src=\'http://media2.intoday.in/indiatoday/images/stories/dengue305_102617022722.jpg\' align=\"left\" hspace=\"2\" height=\"180\" width=\"305\" alt=\"\" border=\"0\"/><\/a>Usually at this time of the year, the virus becomes inactive due to \ntemperature dip. But experts are witnessing the hostile nature of ades \nmosquitoes."
},
{
title : "Waste management bye-laws pending approval of LG: Delhi High Court told",
url : "http://indianexpress.com/article/delhi/waste-management-bye-laws-pending-approval-of-lg-delhi-high-court-told-4906249/",
source : "Delhi – The Indian Express",
date : "25.10.2017",
desc : "<img alt=\"\" border=\"0\" src=\"http://pixel.wp.com/b.gif?host=indianexpress.com&blog=53855017&post=4906249&subd=indianexpressonline&ref=&feed=1\" width=\"1\" height=\"1\" />"
},
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "650 new cases of dengue, 48 of chikungunya",
url : "http://www.thehindu.com/news/cities/Delhi/650-new-cases-of-dengue-48-of-chikungunya/article19908528.ece",
source : "Hindu: Cities",
date : "24.10.2017",
desc : "More than 1,000 dengue cases reported so far this month"
},
'' // Last item -- needed because previous item ends with a comma
]`
as you can see the sample data is not valid JSON, i tried the below function, however ended up with unnecessary space in the keys, which is also a problem.
`
//Step 1
function extractjson(strarg){
var found = [], // an array to collect the strings that are found
rxp = /{([^}]+)}/g,
curMatch;
var parsed=[];
// step 2: regex to add quotes
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;
while( curMatch = rxp.exec( strarg ) ) {
found.push( curMatch[0].replace(objKeysRegex, "$1\"$2\":") );
}
//step 3- parse the found data
for(i=0;i<found.length;i++){
try {
json = JSON.parse(found[i]);
} catch (exception) {
json = null;
}
if (json) {
//the json is ok
parsed.push(JSON.parse(found[i]));
}else{
console.log("badjson");
//the json is not ok
}
}
console.log("input length =", found.length, "output length=", parsed.length);
return parsed;
}
}
`
Here's a fairly naive attempt at parsing...it makes some assumptions about the format of the data (for example it looks for the _nr_ prefix on variable names). I'd recommend splitting the string up into its various var declarations, and then cleaning up each section of data between them before evaluating using JSON.parse.
let parseJSON = (text) => {
let quoteKeysAndParse = (text) => {
//Quote keys in objects
let quoted = text.replace(/([\{\[,]\s*)(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '$1"$3": ');
//Remove the "last item" text
quoted = quoted.replace(/,\s+'' \/\/ Last item[^\]^}]+([\]\}])/g, '$1');
//Remove improperly escaping of apostrophes
quoted = quoted.replace(/([^\\])\\'/g, '$1\'');
//Parse the JSON
return JSON.parse(quoted);
}
//Find var declarations
let declarations = text.match(/var\s+_nr_[^\s]+\s+=\s+/ig), obj = {}, key = null, prevKey = null;
text = ['',text];
//For each variable...
for(let declaration of declarations){
key = declaration.match(/_nr_[^\s]+/)[0];
let currentText = text[1].split(declaration);
text = currentText;
if(prevKey){
//Parse the prior split section
obj[prevKey] = quoteKeysAndParse(text[0]);
}
prevKey = key;
}
//Make sure we process the last section
if(prevKey){
obj[prevKey] = quoteKeysAndParse(text[1]);
}
return obj;
}
fetch('https://cors-anywhere.herokuapp.com/newsrack.in/stories/servelots/iihs_feeds/16.json')
.then(response => response.text())
.then(parseJSON)
.then(data => {
for(let item of data._nr_stories){
let div = document.createElement('div');
div.innerHTML = `<h3>${item.date} - ${item.title} (${item.source})</h3><p>${item.desc}</p>`;
document.body.append(div)
}
});
Here's a working short solution
// ----------------------- DATA -----------------------
let code = `
var _nr_metadata = {
site_base_url : "http://newsrack.in",
issue_name : "iihs_feeds",
category_name : "Chikungunya",
listing_url : "/stories/servelots/iihs_feeds/16"
}
var _nr_stories = [
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "650 new cases of dengue, 48 of chikungunya",
url : "http://www.thehindu.com/news/cities/Delhi/650-new-cases-of-dengue-48-of-chikungunya/article19908528.ece",
source : "Hindu: Cities",
date : "24.10.2017",
desc : "More than 1,000 dengue cases reported so far this month"
},
]
`
// --------------------- / DATA ------------------------
// --------------------- TREATMENT ------------------------
// Add '"' around the property names
code = code.replace(/\n +([a-z_]+) +:/g, '"$1" :').replace(/[\n\r]/g,'');
// To avoid unecessary ',' in "}, ]"
code = code.replace(/\},[ ]*\]/g,'}]');
// Split by var (keeping var name)
code = code.split(/ var(?=[a-z_ ]+= [\[\{])/);
// The result to feed
let result = {} ;
// Treat each var
code.forEach( d => {
d = d.trim();
if (!d) { return }
// Separate var name and var value
// Faster?
let index = d.indexOf('=');
let var_name = d.substr(0, index).trim();
let var_value = d.substr(index+1, d.length).trim();
// Parse the value
try
{
result[var_name] = JSON.parse(var_value);
}
catch(error)
{
console.error(error);
}
})
console.log(result);
I have a list of postcodes in the UK with a region id next to it. Now for delivering products it costs more depending on the region a user lives in.
For example, if a user lives in Birmingham and has a postcode that starts with B, he will get free delivery because that postcode region doesn't have any charge.
Likewise, if a user has a postcode starting with IM , they have to pay more delivery as that postcode region is more.
Sample postcode list:
Postcode | Region
AL | A
BA | A
BB | A
BD | A
B | B
BH | B
LN | D
LS | D
IV1 | E
IV23 | F
From the example above if a user wants to get a delivery and their postcode starts with BA then I want to apply the delivery charge rate of region A.
I'm actually a bit confused as to how I can programmatically do this. At first I thought I would simply do something similar to:
$postcodes = [
'AL'=>'A',
'BA'=>'A',
//And so on ....
];
//get the first 2 letters
$user_input = substr( $user_postcode, 0, 2 );
if(array_key_exists($user_input,$postcodes)){
//Get the region code
$region = $postcodes[$user_input];
// Charge the user with the delivery rate specific to that user, then carry on
}
But problem is that some similar postcodes can be in different regions, so for example, IV1 is region E and IV23 is region F like seen above.
That means I have to match a users post code on either, the 1 , 2 ,3 or 4 characters. That probably doesn't make sense. To elaborate more see below:
//From Birmingham and is in region B
$user1_input = 'B';
//From Bradford and is in region A
$user1_input = 'BD';
//From Inverness and is in region E
$user1_input = 'IV1';
So if the user input is from Birmingham and user input starts with B , how can i tell that apart from a postcode that also starts with B but then has other letters in it which makes it a different postcode.
I'm trying my best to explain, hopefully, this does make sense. If not please ask for more info.
Can anyone please help me with the logic to how I could achieve this? Either in Javascript or PHP , because i can convert the logic afterwards.
If you have what looks like a valid UK postcode, then remove the spaces and just search the array till you find a match:
$lookup = [
'' => 'X', // in case no match is found
'AL'=>'A',
'BA'=>'A',
//And so on ....
];
function get_delivery_for($postcode)
{
global $lookup;
for ($x=5; $x>0 && !$result; $x--) {
$result=$lookup[substr($postcode, 0, $x)];
}
return ($result);
}
Note that the code above is intended for illustration, I would recommend using something more elaborate to avoid it throwing warnings....
$result=isset($lookup[substr($postcode, 0, $x)])
? $lookup[substr($postcode, 0, $x)]
: false;
One option would be to order your postcode/region array by the descending length of the postcode key. This way, the longer (more specific) keys are checked first. Taking your list above, it would become something like this...
$postcodes = array(
"IV23" => "F",
"IV1" => "E",
"LS" => "D",
"LN" => "D",
"BH" => "B",
"BD" => "A",
"BB" => "A",
"BA" => "A",
"AL" => "A",
"B" => "B",
);
After you have that, it's as simple as looping through the array, checking for a match against the provided postcode (starting from the left), and stopping when you find a match.
foreach($postcodes as $code => $region)
{
if($code == substr($user_postcode, 0, strlen($code)))
{
$shippingRegion = $region;
break;
}
}
echo $shippingRegion;
I hope someone can help with this:
I am currently working on a motor dealership website. On this website is a car loan calculator that calculates your monthly repayments. I have successfully created a basic calculator that calculates the correct amount.
The client isn't happy with that. They want a more advanced calculator that calculates the monthly repayments with balloon considerations and a deposit and initiation and admin fees.
I altered the code to reflect that, but now the thing won't work anymore. I can't find any error in my code.
Here's the Javascript that's supposed to do the calculation:
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert from
// an annual rate to a monthly rate. Convert payment period in years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var lessDeposit = document.loandata.deposit.value;
var adminFee = document.loandata.admin.value;
var initiationFee = document.loandata.initiation.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
var balloonPercent = document.loandata.balloon.value / 100;
// Now compute the monthly payment figure, using esoteric math.
var balloonFinal = (principal * balloonPercent);
var totalPrincipal = (principal + initiationFee + balloonfinal - lessDeposit);
var x = Math.pow(1 + interest, payments);
var monthly = (totalPrincipal*x*interest)/(x-1);
// Check that the result is a finite number. If so, display the results
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
document.loandata.payment.value = round(monthly + adminFee);
document.loandata.total.value = round(monthly * payments);
document.loandata.totalinterest.value =
round((monthly * payments) - principal);
}
// Otherwise, the user's input was probably invalid, so don't
// display anything.
else {
document.loandata.payment.value = "";
document.loandata.total.value = "";
document.loandata.totalinterest.value = "";
}
}
// This simple method rounds a number to two decimal places.
function round(x) {
return Math.round(x*100)/100;
}
Also, if possible, there needs to be some validation. Like purchase price, interest rate and payment period are required fields. But the rest are not. So if someone fills in the required fields but not the rest, the calculator still needs to work, but if someone does NOT complete one of the required fields, they need to be prompted to do so.
For those who don't know what a balloon payment is, here's an example;
Purchase Price is R117 000
You decide on a balloon payment of 30%. On the initial purchase price, the 30% amounts to R35 100. This amount is then subtracted from your initial purchase price so that means your purchase is now R81 900. After that comes the deposit, which is subtracted, and the extras and the admin and initiation fees. So the monthly repayments are calculated using this new purchase price of R81 900 + extras - deposit (if any). For interest sake, after your contract ends, you have to pay the balloon amount in full or re-finance the vehicle.
PS: I'm a complete newbie when it comes to JavaScript. So any help would be greatly appreciated.
If the result is nothing, one of these three conditions is likely triggering the else statement:
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
You have a typo in the JS, you need to change balloonfinal to be balloonFinal with a capital F in the var totalPrincipal = line of code.
The principal, lessDeposit, adminFee, initiationFee may also need to be typecast as an integer/float.