I'm trying to modify a simple little AE script which shows the day of the week in source text. I need it to show tomorrow and the next day - which I can do by using +1 and +2 - but without a condition it breaks. I'm guessing it's along the lines of; if d>6 then d=0? Can't quite get the code right, some help would be much appreciated!
d = new Date(Date(0));
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
weekday[d.getDay()]
[EDIT: Terribly sorry, #ndix, but previous code (deleted) is totally flawed. The negatives will NOT work.
Use the code below]
timeDirectionIndex = 0;//initial for today or future
daysToAdd = -15;//you can make this zero or any positive or negative integer
d = new Date(Date(0));
var weekday=new Array(7);
if (daysToAdd < 0) {timeDirectionIndex = 1;}
//if time is reversed, uses second column
weekday[0]=["Sunday","Saturday"][timeDirectionIndex];
weekday[1]=["Monday","Friday"][timeDirectionIndex];
weekday[2]=["Tuesday","Thursday"][timeDirectionIndex];
weekday[3]=["Wednesday","Wednesday"][timeDirectionIndex];
weekday[4]=["Thursday","Tuesday"][timeDirectionIndex];
weekday[5]=["Friday","Monday"][timeDirectionIndex];
weekday[6]=["Saturday","Sunday"][timeDirectionIndex];
//Math.abs makes it always positive; we rely on order of array now
if (daysToAdd < 0) {
wd=weekday[ ( Math.abs(daysToAdd) + 3 + ( 3 - d.getDay()) )%7 ];
} else {
wd=weekday[ (Math.abs(daysToAdd) + ( d.getDay() ) )%7 ];
}
alert(wd);
[PREVIOUS CODE DID NOT WORK]
Related
I want to make coding about the final score display. If someone has done 10 multiple choice questions and he clicks on the final score button, then his final score will appear along with the description. The score will be made in a range according to the category, namely 1-59 = Under Average, 60-79 = Average, and 80-100 = Above Average.
I've tried coding it but I found error 1176 on line 7 and 11.
Can you help me fix it?
finalscorebutton.addEventListener(MouseEvent.CLICK, finalscore);
function finalscore(event:MouseEvent):void
{
multiplechoicefinalscore.text = sumofscores;
var finalscore:String = finalscore.toString;
finalscore = multiplechoicefinalscore..text;
if(finalscore.toString < 60){
description.text =
"UNDER AVERAGE.";
}
else if(finalscore.toString >= 60 && finalscore.toString <=79){
description.text =
"AVERAGE.";
}
else{
description.text =
"ABOVE AVERAGE.";
}
}
There are multiple syntax and logic errors.
Something.toString is a reference to a method, you probably mean Something.toString() which calls the said method and returns a text representation of whatever Something is.
You don't need a text representation because you want to compare numbers, you need a numeric representation (which is either int, uint or Number).
There are 2 dots in multiplechoicefinalscore..text, what does it even mean?
There is function finalscore and then you define var finalscore, defining things with the same names is a bad idea in general.
You should keep your script formatted properly, otherwise reading it and understanding would be a pain.
So, I assume you have the user's result is in sumofscores. I'm not sure if the script below will actually work as is, but at least it is logically and syntactically correct:
finalscorebutton.addEventListener(MouseEvent.CLICK, onFinal);
function onFinal(e:MouseEvent):void
{
// Ok, let's keep this one, I think you are putting
// the score result into some kind of TextField.
multiplechoicefinalscore.text = sumofscores;
// Get a definitely numeric representation of the score.
var aScore:int = int(sumofscores);
// In terms of logic, putting the complicated condition case
// under the "else" statement will simplify the program.
if (aScore < 60)
{
description.text = "UNDER AVERAGE.";
}
else if (aScore > 79)
{
description.text = "ABOVE AVERAGE.";
}
else
{
description.text = "AVERAGE.";
}
}
Some background on what is going on:
We are processing addresses into standardized forms, this is the code to take addresses scored by how many components found and then rescore them using a levenshtein algorithm across similar post codes
The scores are how many components were found in that address divided by the number missed, to return a ratio
The input data, scoreDict, is a dictionary containing arrays of arrays. The first set of arrays is the scores, so there are 12 arrays because there are 12 scores in this file (it adjusts by file). There are then however many addresses fit that score in their own separate arrays stored in that. Don't ask me why I'm doing it that way, my brain is dead
The code correctly goes through each score array and each one is properly filled with the unique elements that make it up. It is not short by any amount, nothing is duplicated, I have checked
When we hit the score that is -1 (this goes to any address where it doesn't fit in some rule so we can't use its post code to find components so no components are found) the loop specifically ONLY DOES EVERY OTHER ADDRESS IN THIS SCORE ARRAY
It doesn't do this to any other score array, I have checked
I have tried changing the number to something else like 99, same issue except one LESS address got rescored, and the rest stayed at the original failing score of 99
I am going insane, can anyone find where in this loop something may be going wrong to cause it to only do every other line. The index counter of line and sc come through in the correct order and do not skip over. I have checked
I am sorry this is not professional, I have been at this one loop for 5 hours
Rescore: function Rescore(scoreDict) {
let tempInc = 0;
//Loop through all scores stored in scoreDict
for (var line in scoreDict) {
let addUpdate = "";
//Loop through each line stored by score
for (var sc in scoreDict[line.toString()]) {
console.log(scoreDict[line.toString()].length);
let possCodes = new Array();
const curLine = scoreDict[line.toString()][sc];
console.log(sc);
const curScore = curLine[1].split(',')[curLine[1].split(',').length-1];
switch (true) {
case curScore == -1:
let postCode = (new RegExp('([A-PR-UWYZ][A-HK-Y]?[0-9][A-Z0-9]?[ ]?[0-9][ABD-HJLNP-UW-Z]{2})', 'i')).exec(curLine[1].replace(/\\n/g, ','));
let areaCode;
//if (curLine.split(',')[curLine.split(',').length-2].includes("REFERENCE")) {
if ((postCode = (new RegExp('(([A-Z][A-Z]?[0-9][A-Z0-9]?(?=[ ]?[0-9][A-Z]{2}))|[0-9]{5})', 'i').exec(postCode))) !== null) {
for (const code in Object.keys(addProper)) {
leven.LoadWords(postCode[0], Object.keys(addProper)[code]);
if (leven.distance < 2) {
//Weight will have adjustment algorithms based on other factors
let weight = 1;
//Add all codes that are close to the same to a temp array
possCodes.push(postCode.input.replace(postCode[0], Object.keys(addProper)[code]).split(',')[0] + "(|W|)" + (leven.distance/weight));
}
}
let highScore = 0;
let candidates = new Array();
//Use the component script from cityprocess to rescore
for (var i=0;i<possCodes.length;i++) {
postValid.add([curLine[1].split(',').slice(0,curLine[1].split(',').length-2) + '(|S|)' + possCodes[i].split("(|W|)")[0]]);
if (postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1] > highScore) {
candidates = new Array();
highScore = postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1];
candidates.push(postValid.addChunk[0]);
} else if (postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1] == highScore) {
candidates.push(postValid.addChunk[0]);
}
}
score.Rescore(curLine, sc, candidates[0]);
}
//} else if (curLine.split(',')[curLine.split(',').length-2].contains("AREA")) {
// leven.LoadWords();
//}
break;
case curScore > 0:
//console.log("That's a pretty good score mate");
break;
}
//console.log(line + ": " + scoreDict[line].length);
}
}
console.log(tempInc)
score.ScoreWrite(score.scoreDict);
}
The issue was that I was calling the loop on the array I was editing, so as each element got removed from the array (rescored and moved into a separate array) it got shorter by that element, resulting in an issue that when the first element was rescored and removed, and then we moved onto the second index which was now the third element, because everything shifted up by 1 index
I fixed it by having it simply enter an empty array for each removed element, so everything kept its index and the array kept its length, and then clear the empty values at a later time in the code
Sorry if the text is confusing, I don't speak English.
My problem is:
1. I have the number of pages that was printed.
2. The duration of printing (start time and finish)
3. I want to plot a chart by hour whith the number of pages per hour
Example:
900 pages
1:30 hous
I want this Array of hour: [600, 300]
I think this is more a mathematical problem, but I don't had a good idea to do this. The are a lot of data and i need to do a algorithm fast and optimized.
Obs: I am more interested in the logic, not in the programming language.
Ok, not sure that works for everything but I think is a good start.
I have made the assumption that your duration is in minutes or else I believe you can transform it to minutes.
function something(pages,totalDutation){
// pages = 900
// totalDutation = 90
var printsPerMinute = pages / totalDutation //get the prints per minute!
var printsPerHour = Math.floor(printsPerMinute * 60) //calculate the prints made in one hour
var countOfHours = parseInt(totalDutation / 60) //divide the total duration by 60 to get the count of hours
var remainingPrints = (totalDutation % 60) * printsPerMinute //add the extra prints that didn't complete a whole hour.
var result = Array(countOfHours).fill(printsPerHour) //create an array and fill it.
if(remainingPrints) result.push(remainingPrints)
return result
}
Take a look at the NodeJS example below to get an idea of how it can be done.
Might need a bit of fine-tuning, though.
Calculate the number of prints per hour
Make as many iterations as hours taken
Do (total prints - prints per hour) as long as a > b,
otherwise return the remaining total prints
const getPagesPerHour = function (totalPrints, totalTime) {
const printsPerHour = (totalPrints / totalTime) * 60;
return Array.apply(null, { length: Math.ceil(totalPrints/printsPerHour) }).map(function (val, key) {
if (totalPrints > printsPerHour) {
totalPrints = (totalPrints - printsPerHour);
return printsPerHour;
} else {
return totalPrints;
}
});
}
console.log(getPagesPerHour(900, 90)); // [600, 300]
Basically I have a method that will take any set of numbers with a selected value and reorder them ascending keeping track of the new selected value.
So {21, 2, 9, 13} selectedVal = 9 becomes { 1, 2, 3, 4 } selectedVal = 2
What I need to do now is be able to swap 2 numbers and keep the order intact. If I want to swap 2 with 4 I need 3->2 and 4->3 but also the other way around like swapping 3 with 1 so 1->2 and 2->3.
I'm sure there is a proven algorithm for this and I will probably create my own for fun tomorrow but I'd like the fastest solution to use in my actual application.
The name of the algorithm or any useful links would be appreciated. I am using C# 4.0 if that matters at all.
EDIT - I came up with my own solution that I believe works on paper but I'd still like a reply if someone knows a better solution.
Assuming ordered list always starts at 1 which it does in my case...
if (newpos < currpos)
for (int i = newpos-1; i < currpos-1; i++)
{
array[i] += 1;
array[currpos-1] = newpos;
}
else if (newpos > currpos)
for (int i = newpos-1; i >= currpos-1; i--)
{
array[i] -= 1;
array[currpos-1] = newpos;
}
else // do nothing since they are trying to swap to the same place
Let me explain.
I have to do some fuzzy matching for a company, so ATM I use a levenshtein distance calculator, and then calculate the percentage of similarity between the two terms. If the terms are more than 80% similar, Fuzzymatch returns "TRUE".
My problem is that I'm on an internship, and leaving soon. The people who will continue doing this do not know how to use excel with macros, and want me to implement what I did as best I can.
So my question is : however inefficient the function may be, is there ANY way to make a standard function in Excel that will calculate what I did before, without resorting to macros ?
Thanks.
If you came about this googling something like
levenshtein distance google sheets
I threw this together, with the code comment from milot-midia on this gist (https://gist.github.com/andrei-m/982927 - code under MIT license)
From Sheets in the header menu, Tools -> Script Editor
Name the project
The name of the function (not the project) will let you use the func
Paste the following code
function Levenshtein(a, b) {
if(a.length == 0) return b.length;
if(b.length == 0) return a.length;
// swap to save some memory O(min(a,b)) instead of O(a)
if(a.length > b.length) {
var tmp = a;
a = b;
b = tmp;
}
var row = [];
// init the row
for(var i = 0; i <= a.length; i++){
row[i] = i;
}
// fill in the rest
for(var i = 1; i <= b.length; i++){
var prev = i;
for(var j = 1; j <= a.length; j++){
var val;
if(b.charAt(i-1) == a.charAt(j-1)){
val = row[j-1]; // match
} else {
val = Math.min(row[j-1] + 1, // substitution
prev + 1, // insertion
row[j] + 1); // deletion
}
row[j - 1] = prev;
prev = val;
}
row[a.length] = prev;
}
return row[a.length];
}
You should be able to run it from a spreadsheet with
=Levenshtein(cell_1,cell_2)
While it can't be done in a single formula for any reasonably-sized strings, you can use formulas alone to compute the Levenshtein Distance between strings using a worksheet.
Here is an example that can handle strings up to 15 characters, it could be easily expanded for more:
https://docs.google.com/spreadsheet/ccc?key=0AkZy12yffb5YdFNybkNJaE5hTG9VYkNpdW5ZOWowSFE&usp=sharing
This isn't practical for anything other than ad-hoc comparisons, but it does do a decent job of showing how the algorithm works.
looking at the previous answers to calculating Levenshtein distance, I think it would be impossible to create it as a formula.
Take a look at the code here
Actually, I think I just found a workaround. I was adding it in the wrong part of the code...
Adding this line
} else if(b.charAt(i-1)==a.charAt(j) && b.charAt(i)==a.charAt(j-1)){
val = row[j-1]-0.33; //transposition
so it now reads
if(b.charAt(i-1) == a.charAt(j-1)){
val = row[j-1]; // match
} else if(b.charAt(i-1)==a.charAt(j) && b.charAt(i)==a.charAt(j-1)){
val = row[j-1]-0.33; //transposition
} else {
val = Math.min(row[j-1] + 1, // substitution
prev + 1, // insertion
row[j] + 1); // deletion
}
Seems to fix the problem. Now 'biulding' is 92% accurate and 'bilding' is 88%. (whereas with the original formula 'biulding' was only 75%... despite being closer to the correct spelling of building)