Modify Existing Google Calendar Events - javascript

Below is the script I created to modify existing calendar events. My goal is to change the description to have it change from a Register button to Registration Closed. The script works in that it will add guests, however it will not update the description to the new description when the max number of registrants has been exceeded. I did not include the part of the script that details the calProperties.
function modifyEvents() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Events");
var sheetR = ss.getSheetByName("Registration");
var headerRows = 1;
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
for (var i = 1; i in data; ++i) {
if (i << headerRows) {
var row = data[i];
var room = row[5];
var description = row[6];
var agegroup = row[7];
var registration = row[8];
var max = row[10];
var calname = row[14];
var eventId = row[15];
var registrants = row[17];
var calendarName = sheet.getRange(headerRows + i, 15).getValue();
var calendarId = calProperties.getProperty(calendarName);
var cal = CalendarApp.getCalendarById(calendarId);
var id = sheet.getRange(headerRows + i, 16).getValue();
var event = cal.getEventSeriesById(id);
var email = sheetR.getRange(headerRows + i, 8).getValue();
row[10] = sheet.getRange(headerRows + i, 11).getValue();
row[17] = sheet.getRange(headerRows + i, 18).getValue();
if (registration === 'Y' && registrants >> max) {//7.1 line 25
var description1 = (description + '\n' + '\n' + room + '\n' + '\nEvent Type: ' + calname + '\n' + '\nAge Group: ' + agegroup)
var descriptionHTML = '\n <div id="registration_button" ><a style="text-align:right;color:white!important;text-decoration:bold;background-color:rgb(209,72,54);background-image:-webkit-linear-gradient(top,rgb(221,75,57),rgb(209,72,54));color:#ffffff;border:1px solid rgba(0,0,0,0);border-radius:2px;display:inline-block;font-size:12px;font-weight:bold;height:27px;line-height:27px;padding:0px 20px 0px 20px;text-align:center;text-transform:uppercase;white-space:nowrap;text-decoration:none;color:white" target="_blank">Registration Closed</a>';
var descriptionRegistration = (description1 + '\n' + '\n' + descriptionHTML);
event.setDescription(descriptionRegistration);
}
}
}
}

replace (i << headerRows)
with (i < headerRows)
and replace registration === 'Y' && registrants >> max
with registration === 'Y' && registrants > max
there is a difference between > and >= which are greater than , greater than or equal to and :
>> << which are bitwise operands left and right which you clearly did not want
<< left shift Shifts a in binary representation b (< 32) bits to the left, shifting in zeroes from the right.
>> Sign-propagating right shift Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
What you want are > Greater Than "The greater than operator returns true if the left operand is greater than the right operand."
or
< Less Than "The less than operator returns true if the left operand is less than the right operand."

Related

How do I apply the conversion from charCodeAt to C # here?

So I've already found posts on this topic, but that didn't really help me. On the one hand, I have tried something like this, for example, but it is not quite right in my case**(C#)**.
string temp;
foreach (var a in chaine)
temp = ( Convert.ToUInt16(a).ToString("X4"));
for (j = 0; j < intlenght; j+= 1)
{
arrayData[j + 1] = temp;
}
Why I think it doesn't really work is that my starting form looked a little different than the examples and I'm not really familiar with JavaScript. My starting shape looks like this**(javaScript)**:
for (j = 0; j < intlenght; j+= 1)
{
arrayData[j + 1] = x.charCodeAt(j) - 32;
}
the x in this case it is actually
var x = document.getElementById ("textIn"). value;
but in my method I have a string return value instead of the X
so how can i correctly get the
arrayData [j + 1] = x.charCodeAt (j) - 32;
translate in c #. In the end I need this in my method for Code128 encoder
EDIT for better Understanding:
So I have a TextBlock in my window, but there is a text in it in a barcode 128 font. However, this barcode cannot yet be read. So what I want to do is add the additional characters of the barcode so that at the end you can scan this barcode with a scanning program. To do that I come across this Stack Overflow answer: https://stackoverflow.com/a/60363928/17667316
However, the problem was with the question that the code is in JavaScript and not in C #. Since I've only found solutions where it works with libaries and nuggets (which I want to work around) I tried to convert this javaScript code into C #. I come across lines like this(javaScript):
arrayData[j + 1] = x.charCodeAt(j) - 32;
I didn't find a solution to this as I did this Javascript code:
var buttonGen = document.getElementById("btnGen");
buttonGen.onclick = function () {
var x = document.getElementById("textIn").value;
var i, j, intWeight, intLength, intWtProd = 0, arrayData = [], fs;
var arraySubst = [ "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê" ];
/*
* Checksum Calculation for Code 128 B
*/
intLength = x.length;
arrayData[0] = 104; // Assume Code 128B, Will revise to support A, C and switching.
intWtProd = 104;
for (j = 0; j < intLength; j += 1) {
arrayData[j + 1] = x.charCodeAt(j) - 32; // Have to convert to Code 128 encoding
intWeight = j + 1; // to generate the checksum
intWtProd += intWeight * arrayData[j + 1]; // Just a weighted sum
}
arrayData[j + 1] = intWtProd % 103; // Modulo 103 on weighted sum
arrayData[j + 2] = 106; // Code 128 Stop character
chr = parseInt(arrayData[j + 1], 10); // Gotta convert from character to a number
if (chr > 94) {
chrString = arraySubst[chr - 95];
} else {
chrString = String.fromCharCode(chr + 32);
}
// Change the font-size style to match the drop down
fs = document.getElementsByTagName("option")[document.getElementById("selList").selectedIndex].value;
document.getElementById("test").style.fontSize = fs + 'px';
document.getElementById("check").innerHTML =
'Checksum = ' + chr + ' or character ' + // Make It Visual
chrString + ', for text = "' + x + '"';
document.getElementById("test").innerHTML =
'Ì' + // Start Code B
x + // The originally typed string
chrString + // The generated checksum
'Î'; // Stop Code
}
Can convert into a working C # code.

Not properly referencing cells

I am coding a phone number formatter for a large database. Everything is working, but there is an inconsistent printing of blank cells. Most of the cells are read through and are properly formatted, but there are some that show blank outputs in the wrong cells.
I have tried fixing this by resetting the cleanNumber variable to a blank string but this just posed another issue on line 33 with indexOf().
function myFunction() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // connects sheet to code
var startRow = 18;
var endRow = 41;
for (var i = startRow; i <= endRow; i++) { // i = currnet row | row to end at | add 1 to count each time
var workingCell = activeSheet.getRange(i, 2).getValue();
Logger.log("Original number: " + workingCell)
//If blank, move to next row
exit: if (workingCell.length == 0.0) {
var blank = "";
activeSheet.getRange(i, 3).setValue(blank);
Logger.log("This row is blank")
//break exit;
}
// cleanNumber if it isn't formatted already
else if (isNaN(workingCell)) { // runs if active cell is not a preformatted number
var cleanNumber = workingCell.replace(/\D/g, ''); // removes all non-numeric values
activeSheet.getRange(i, 3).setValue(cleanNumber);
Logger.log("Extra char's removed: " + cleanNumber)
}
// runs if active cell is already preformatted
else {
activeSheet.getRange(i, 3).setValue(workingCell);
Logger.log("No need for formatting: " + workingCell)
}
// If cleanNumber has a country code(+1), remove it
if ((cleanNumber.indexOf("1")) == 0) {
cleanNumber = cleanNumber.substring(1); //removes first character = "1"
activeSheet.getRange(i, 3).setValue(cleanNumber);
Logger.log("Country code removed: " + cleanNumber);
}
// If number is longer than 10 characters, create an extension variable - with entire number, remove 10 characters from front
if (cleanNumber.length > 10.0) {
var extension = cleanNumber.substring(10, 15);
var phoneNumber = cleanNumber.substring(0, 10);
var formatted = phoneNumber.slice(0, 3) + "-" + phoneNumber.slice(3, 6) + "-" + phoneNumber.slice(6, 15);
var finalPhoneNumber = formatted + " ext. " + extension;
activeSheet.getRange(i, 3).setValue(finalPhoneNumber);
Logger.log("This number is in its final ext. format: " + finalPhoneNumber);
}
//if number doesnt have an extension, put it into final format
else if (cleanNumber.length = 10.0) {
var frontFinal = cleanNumber.substring(0, 3);
var midFinal = cleanNumber.substring(3, 6);
var endFinal = cleanNumber.substring(6, 10);
var finalNumber = frontFinal + "-" + midFinal + "-" + endFinal;
activeSheet.getRange(i, 3).setValue(finalNumber);
Logger.log("This number is in its final format: " + finalNumber);
}
//if number is less than 10 numbers
else {
Logger.log("This number is shorter than 10 numbers" + cleanNumber);
}
cleanNumber = " ";
}
}
The pre-formatted numbers are on the left and the output is in the right column.
Here is some sample data, please consider that the issue seems to be stemming from blank rows.
Unformatted
1999-111-1111
1+2222-222222
4444444444 ext. 223
9738094395
9172609107
866.786.6682
973 330 2212
(631)563-4000 ext. 234
I look forward to solving this issue, thank you for the help :)
You can do it with ARRAYFORMULA or you may use the RegExp in your script.
=ArrayFormula(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(TO_TEXT(A2:A),"\D",),"^(?:1)?(\d{3})(\d{3})(\d{4})(\d{0,5}).*$","$1-$2-$3 ext. $4")," ext\. $",))
You are recommended to use batch operations
const values = [
['1999-111-1111'],
['1+2222-222222'],
['4444444444 ext. 223'],
[9738094395],
[9172609107],
['866.786.6682'],
['973 330 2212'],
['(631)563-4000 ext. 234'],
['973-809-4395'],
['']
];
const results = [];
for (const value of values) {
const cleanNumber = value[0].toString().replace(/\D/g, '');
const m = cleanNumber.match(/^(?:1)?(\d{3})(\d{3})(\d{4})(\d{0,5}).*$/);
if (m) {
let finalNumber = `${m[1]}-${m[2]}-${m[3]}`;
if (m[4]) { finalNumber += ` ext. ${m[4]}`; }
results.push([finalNumber]);
}
else {
results.push(value);
}
}
console.log(results.flat());

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

I need help with getting a list of GPAs over 3.4. I was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).
<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
thegpas = prompt("Enter gpas or XXX to Stop");
if(thegpas != "XXX"){
gpas.push(thegpas);
} else {
break;
}
}
for(var x = 0; x < gpas.length; x++)
{
a = gpas.sort((a,b)=>b-a);
total=total + parseFloat(gpas[x]);
b = total/gpas.length //parseFloat(total)/length;
var max = gpas[0];
var min = gpas[0];
for(var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
}
//need help with this part
//outstandingGPAs=0;
outstandingGPAs = [];
cutoff = 3.4;
if (gpas[x]>cutoff){
outstandingGPAs.push(parseFloat(gpas[x]));
}
out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
// alert(gpas[x]);
}
document.getElementById('out').innerHTML=out;
Current Output:
Best way to output a (not very long) array is the join function.
In your output, you should use:
out = "<whatever you put>" + outstandingGPAs.join();
Check this link for more explanation of the join function.
Since you are already looping over your gpas array you could save those that are over 3.4 while you do that.
You would do that within your existing loop, not afterwards.
const cutoff = 3.4;
let outstandingGPAs = [];
// ...
for (var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
// added to the existing loop
if (gpas[i] > cutoff) {
outstandingGPAs.push(gpas[i]);
}
}
The outer loop should not be there, as you just redo the same operation over and over again.
As you only push at most one value in outstandingGPAs after you have set it to the empty array, that result will be wrong.
There are several other similar issues going on...
Also, getting input with prompt is really not user-friendly. The way to do this, is using an input element, and let the user type all values freely, and go back and correct whenever they want, and when they are happy with it, they can press a button so the code can run on it.
Here is how that looks:
var calcButton = document.getElementById("calc");
var gpasInput = document.getElementById("gpas");
var outDiv = document.getElementById('out');
calcButton.addEventListener("click", function () {
var min = Infinity,
max = -Infinity,
total = 0,
gpas = [],
outstandingGPAs = [];
// Collect the input as an array of strings with number-related characters
var inputStrings = gpasInput.value.match(/-?\d+(\.\d+)?/g);
for (var i = 0; i < inputStrings.length; i++) {
var num = parseFloat(inputStrings[i]);
gpas.push(num);
if (num > 3.4) {
outstandingGPAs.push(num);
}
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
total += num;
}
var average = total / gpas.length;
gpas.sort((a, b) => b - a);
// lets also sort the outstanding GPAs
outstandingGPAs.sort((a, b) => b - a);
outDiv.innerHTML = "Largest to smallest " + gpas.join(", ") + "<br>"
+ "GPAs average: " + average + "<br>"
+ "Max and Min: " + max + ", " + min + "<br>"
+ "Outstanding GPAs (greather than 3.4): " + outstandingGPAs.join(", ");
});
Enter gpas values: <input id="gpas">
<button id="calc">Calculate</button><br>
<div id ="out"></div>
Here:
let theGpas = "";
let gpaArr = [];
while(theGpas != "XXX"){
theGpas = prompt("Enter GPAs. Enter XXX to stop.");
if(theGpas != "XXX"){
gpaArr.push(theGpas);
}
}
gpaArr = gpaArr.sort();
document.write("Largest to Smallest: "+gpaArr.join(",")+"<br/>");
function average(array){
var totalSum = 0;
for(var n in array){
totalSum += array[n];
}
return totalSum/array.length;
}
function moreThanArray(array, comparison){
var returnArr = [];
for(var z in array){
if(array[z]>comparison){
returnArr[returnArr.length] = array[z];
}
}
return returnArr;
}
const averageOf = average(gpaArr);
document.write("GPAs average: "+averageOf+"<br/>");
document.write("Max and Min: "+gpaArr[gpaArr.length-1]+", "+gpaArr[0]);
document.write("<br/>"+"Outstanding GPAs (greater than 3.4): "+moreThanArray(gpaArr, 3.4).join(","));

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Javascript Showing even numbers only

I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.

Categories

Resources