How to split hours in Time Range in C#? - time

start time 13:00
End time 17:00
get all hours and put to array
output arrHrs = {"13","14","15","16","17"}

You have to try something like that
DateTime startTime = Convert.ToDateTime("01-01-2013 20:00");
DateTime endTime = Convert.ToDateTime("01-02-2013 02:00");
List<DateTime> list = new List<DateTime>();
list = Listhours(startTime, endTime);
Need to create a function like
private List<DateTime> Listhours(DateTime starttm, DateTime endtm)
{
var Listhour = new List<DateTime>();
DateTime startt = Convert.ToDateTime(starttm.ToString("MM/dd/yyyy HH:00:00"));
DateTime endd = Convert.ToDateTime(endtm.ToString("MM/dd/yyyy HH:00:00"));
for (double dblDate = startt.ToOADate();
dblDate <= endd.ToOADate();
dblDate += (1.0 / 24.0))
{
Listhour.Add(DateTime.FromOADate(dblDate));
}
return Listhour;
}
Hope it works.

var startTime = 13, endTime = 17;
var arrHrs = new List<int>();
while(startTime <= endTime)
{
arrHrs.Add(startTime++);
}
OR in an easier way
var startTime = 13, endTime = 17;
var arrHrs = Enumerable.Range(startTime, endTime);

Related

Copy/Original printing in Netsuite

I am trying to print original first time and copy after the first time printing. I have created a custom field that stored the timestamp of first time printing. So, the template will check first time the field is empty so "original" is printed and the timestamp will stored to the field. Then, when the template is printed after the first time it will check the field, find that there is a content (The timestamp) so it will print copy on the printed template. everything is work fine, buttt when trying to access the advance template of the applied transaction (like: Bill or any) it show an error like below the code!!! What is the issue?
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/render','N/record'], function(render,record) {
function beforeLoad(context) {
var UserEventType = context.UserEventType;
var contextType = context.type;
var newRecord = context.newRecord;
var newRecordID= context.newRecord.id;
var currentDate = sysDate(); // returns the date
var currentTime = timestamp(); // returns the time stamp in HH:MM:SS
var currentDateAndTime = currentDate + ' ' + currentTime;
if (contextType == UserEventType.PRINT) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = newRecord.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: newRecordID , type: newRecord.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();
}
}
}
function sysDate() {
var date = new Date();
var tdate = date.getDate();
var month = date.getMonth() + 1; // jan = 0
var year = date.getFullYear();
return currentDate = month + '/' + tdate + '/' + year;
}
function timestamp() {
var str = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridian = "";
if (hours > 12) {
meridian += "pm";
} else {
meridian += "am";
}
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
str += hours + ":" + minutes + ":" + seconds + " ";
return str + meridian;
}
return {
beforeLoad: beforeLoad,
};
});
The Error: Error during loading transaction for advanced printing Caused by: com.netsuite.suitescript.exception.NLServerSideScriptException: {"type":"error.SuiteScriptError","name":"SSS_MISSING_REQD_ARGUMENT","message":"load: Missing a required argument: id","stack":["createError(N/error)","beforeLoad(/SuiteScripts/Copy_Original.js:23)","createError(N/error)"],"cause":{"name":"SSS_MISSING_REQD_ARGUMENT","message":"load: Missing a required argument: id"},"id":"","notifyOff":false,"userFacing":true}
At first glance the base problem is that you are not passing a record ID to the record.load method.
A breakdown of the error:
What is the Error: "SSS_MISSING_REQD_ARGUMENT" (you are missing an argument that it needs in order to execute)
Where: "beforeLoad(/SuiteScripts/Copy_Original.js:23)" (the beforeLoad event in your suitescript Copy_Original, on line 23.)
What argument are you missing: "load: Missing a required argument: id" (after the : it tells you id)
I would change the names of your variables so they are different from the netsuite names. particularly newRecord, this will eliminate confusion and the possibility of you referencing a netsuite enum when you are trying to use your variable. (I believe that is what is happening here as I am able to get this to work on my record when using the following.)
function beforeLoad(context) {
var UserEventType = context.UserEventType;
var contextType = context.type;
var recObj= context.newRecord;
var recId= recObj.id;
var currentDate = sysDate(); // returns the date
var currentTime = timestamp(); // returns the time stamp in HH:MM:SS
var currentDateAndTime = currentDate + ' ' + currentTime;
if (contextType == UserEventType.PRINT) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = recObj.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: recId, type: recObj.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();
}
It is worked now, check the sol. :
I should add && recId --->(context.newRecord.id)
if (contextType == UserEventType.PRINT && recId) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = recObj.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: recId, type: recObj.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();

Is there a way to speed up this for loop in Google Script?

I have a for loop which is working on my google sheet but it takes around 5 minutes to filter through the 2100 rows of data. I have read about using filters and getting rid of the for loop all together but I'm fairly new to coding in Google Script and haven't been able to get my head around the syntax for this. Any advice greatly appreciated.
Code below:
function Inspect() {a
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
for (var i = 2; i <= lastRow; i++) {
var cell = srcSheet.getRange("A" + i);
var val = cell.getValue();
if (val == true) {
var srcRange = srcSheet.getRange("B" + i + ":I" + i);
var clrRange = srcSheet.getRange("A" + i);
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":H" + (tarRow+1));
var now = new Date();
var timeRange = tarSheet.getRange("I"+(tarRow+1));
timeRange.setValue(now);
srcRange.copyTo(tarRange);
clrRange.clear();
//tarRange.activate();
timeRange.offset(0, 1).activate();
}
}
};
Yes, to speed-up you will need to get all the values first and apply your logic to the obtained 2D-arrays instead of cells, at the end you will use setValues to update your sheet. I would go for something like this:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var srcLastRow = srcSheet.getLastRow();
var tarLastRow = tarSheet.getLastRow();
var srcArray = srcSheet.getRange(1,1,srcLastRow,9).getValues();//(A1:I(lastrow))
var tarArray = tarSheet.getRange(1,1,tarLastRow,9).getValues();//(A1:I(lastrow))
for (var i = 1; i < srcArray.length; i++) {
var val = srcArray[i][0];
if (val == true) {
var copyValues = srcArray[i].slice(1);//Get all elements from the row excluding first column (srcSheet.getRange("B" + i + ":I" + i);)
var now = new Date();
copyValues[8]=now;//set the time on column 9 (array starts at position 0!)
var tarNewLine = copyValues;
tarArray.push(tarNewLine);
//clear values on source (except column A):
for(var j=1;j<srcArray[i].length;j++){
srcArray[i][j]="";
}
}
}
tarSheet.clear();
tarSheet.getRange(1, 1,tarArray.length,tarArray[0].length).setValues(tarArray);
srcSheet.clear();
srcSheet.getRange(1, 1,srcArray.length,srcArray[0].length).setValues(srcArray);
};
You cannot get around a loop, but you should reduce the number of calls to the SpreadsheetApp to a minimum, see Apps Script Best Practices
It is not the for loop, but those calls that make your code slow. Instead, work with arrays as much as you can. Loops become of a problem if they are nested - this is also something you should avoid.
Sample how to perform most calls to SpreadsheetApp outside of the loop and work with arrays:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
var Acolumn = srcSheet.getRange("A2:A" + lastRow);
var Avalues = Acolumn.getValues();
var srcRange = srcSheet.getRange("B2:I" + lastRow);
var srcValues = srcRange.getValues();
var array = [];
var now = new Date();
for (var i = 0; i < lastRow-1; i++) {
var val = Avalues[i][0];
if (val == true) {
srcValues[i].push(now);
array.push(srcValues[i]);
var clrRange = Acolumn.getCell(i+1, 1);
clrRange.clear();
}
}
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
if(array.length!=0){
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":I" + (tarRow + array.length));
tarRange.setValues(array);
}
};

Nifi:Automatizied nifi

I have attribute names like startDate:2017-09-07 and endDate:2017-09-16 i want to reitrive data with this parameters and after writing response into the base i want to change this parameter i mean (startDate:2017-09-07 and endDate:2017-09-16 with 2017-09-17 and 2017-09-24) i tried this ecmascript code:
var OutputStreamCallback = Java.type("org.apache.nifi.processor.io.OutputStreamCallback");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
Date.prototype.isValid = function () {
return (Object.prototype.toString.call(this) === "[object Date]")
&& !isNaN(this.getTime());
};
function addDays(date, days) {
var result =new Date(date);
result.setDate(result.getDate() + days);
var dateFormated = result.toISOString().substr(0,10);
return formatDate(dateFormated);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
var startDate = startDate.getValue(),
endDate = endDate.getValue(),
parametr=parameter.getValue(),
count=count.getValue();
var flowFile = session.crete();
var param=8;
var endDate = addDays(end, param*count);
var startDate = formatDate(newStart);
flowFile = session.putAttribute(flowFile, 'startDate', startDate);
flowFile = session.putAttribute(flowFile, 'endDate', endDate);
session.transfer(flowFile, REL_SUCCESS)
but i don't know how can i make my code known when it should increase count in order to change endDate and startTdate manually and replace it with valid startDate and EndDate
is there any service or processor i can use to simplify this task?

Icon calendar generator

Are there any calendar Photoshop/illustrator scripts which can automatically generate a date number similar to this calendar icon image?
I need similar icon with date (1,2,3..31) and name of every month but in .png format. I cannot use html/css3 and jquery to create icon.
Thank you for answers and help
Yes, it's possible. I like a challenge:)
First with the template image open
Second create a folder folder C:\temp\calendar (or change the destination path in the script)
Run the script below and it'll generate dates as defined with sdate & eDate (start & end date) - currently November, 30 to December 01
// Load in background image before running script
// call the source document
var srcDoc = app.activeDocument;
var sDate = new Date("November, 30, 2016 00:00:00");
var eDate = new Date("January, 01, 2017 00:00:00");
var myPath = "c:\\temp\\calendar"
printDate(sDate, eDate, myPath, srcDoc);
//-----------------------------
function printDate(start, end, apath, sauce)
{
if (start == undefined) return;
if (end == undefined) return;
// set long month names
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
str = "";
// main loop here
while(start <= end)
{
// Display the month, day, and year.
// getMonth() returns a 0-based number.
var monthNum = start.getMonth()+1;
var month = monthNames[monthNum-1].toUpperCase();
var day = start.getDate();
var year = start.getFullYear();
// alert(month + " " + day + " " + year);
// num padding
if (monthNum < 10) monthNum = "0" + monthNum;
if (day < 10) day = "0" + day;
var theDate = "cal_" + monthNum + "_" + day + "_" + year;
duplicateIt(theDate);
var day = start.getDate();
str = (day);
var newDate = start.setDate(start.getDate() + 1);
// fontface, size, R,G,B, text, X, Y
// print bigmonth
createText("Arial-BoldMT", 38.0,255, 255, 255, month, 582, 460);
// print big day
createText("Arial-BoldMT", 176.0, 0, 0, 0, day, 582, 1144);
var f = apath + "\\" + theDate + ".png";
// alert(f)
saveAsPNG(f, 10);
// close that saved png
app.activeDocument.close();
// get the original source doc
app.activeDocument = sauce;
// reset start
start = new Date(newDate);
}
}
// function DUPLICATE IT (str)
// --------------------------------------------------------
function duplicateIt(str)
{
// duplicate image into new document
if (arguments.length == 0) str = "temp";
var id428 = charIDToTypeID( "Dplc" );
var desc92 = new ActionDescriptor();
var id429 = charIDToTypeID( "null" );
var ref27 = new ActionReference();
var id430 = charIDToTypeID( "Dcmn" );
var id431 = charIDToTypeID( "Ordn" );
var id432 = charIDToTypeID( "Frst" );
ref27.putEnumerated( id430, id431, id432 );
desc92.putReference( id429, ref27 );
var id433 = charIDToTypeID( "Nm " );
desc92.putString( id433, str ); // name
executeAction( id428, desc92, DialogModes.NO );
}
// function SAVE JPEG(file name & path)
// --------------------------------------------------------
function saveAsPNG(afilePath)
{
// flatten it
activeDocument.flatten();
// save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
// function CREATE TEXT(typeface, size, R, G, B, content, Xpos, Ypos, justify)
// --------------------------------------------------------
function createText(fface, size, colR, colG, colB, content, X, Y)
{
// Add a new layer in the new document
var artLayerRef = app.activeDocument.artLayers.add()
// Specify that the layer is a text layer
artLayerRef.kind = LayerKind.TEXT;
artLayerRef.name = content;
//This section defines the color of the text
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
//Get a reference to the text item so
// that we can add the text and format it a bit
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size;
//pixels from the left, pixels from the top
textItemRef.position = new Array(X, Y)
just = Justification.CENTER;
activeDocument.activeLayer.textItem.justification = just;
}
It's save them as .PNG files named after the date.

UILocalNotification Wrong time zone

When creating a new UILocalNotification and scheduling a notification, the time gets changed due to the timezone. I the date i set gets changed by UiLocalNotifcation to the timezone. which i don't want to happen
public static void RegisterLocalNotification(ServiceModel.Types.ParkingTicket parkingTicket)
{
if (parkingTicket == null || parkingTicket.ExpiringSoon) return;
var startDate = parkingTicket.UtcStart.ToLocalTime();
NSDate nsStartDate = startDate.AddMinutes(parkingTicket.Duration - 10).UtcDateTimeToNSDate();
var notification = new UILocalNotification
{
FireDate = nsStartDate,
TimeZone = null,
AlertAction = Resources.Strings.ExtendTicket,
AlertBody = string.Format
(Resources.Strings.FormattedExpiringMessage,
parkingTicket.TimeLeft.Description(false),
parkingTicket.Address,parkingTicket.Car.RegistrationNumber),
RepeatInterval = 0,
HasAction = true,
UserInfo = GetDictionaryFromParkingTicket(parkingTicket),
SoundName = UILocalNotification.DefaultSoundName,
ApplicationIconBadgeNumber = 1
};
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
}
public static NSDate UtcDateTimeToNSDate(this DateTime utcDateTime)
{
var reference = new DateTime(2001, 1, 1, 0, 0, 0);
return NSDate.FromTimeIntervalSinceReferenceDate((utcDateTime - reference).TotalSeconds);
}
I have tried using TimeZone = NSTimeZone.LocalTimeZone.
You're converting a UTC date to a local date:
var startDate = parkingTicket.UtcStart.ToLocalTime ();
then you're treating the local date as a UTC date, thereby doing the conversion twice:
NSDate nsStartDate = startDate.AddMinutes(parkingTicket.Duration - 10).UtcDateTimeToNSDate();
Just do this instead:
var startDate = parkingTicket.UtcStart;
var nsStartDate = (NSDate) startDate.AddMinutes (parkingTicket.Duration - 10);
The explicit NSDate conversion will do the right thing.

Resources