How to create a Bank Calendar with 30 days each month - calendar

For calculating annuity loan with german I need a calendar where every month has exactly 30 days. Every year has 360 days. There are no leap years.
The interest is allways calculated on a basis of 30 day (That's the german interest method)
I'm using Java 8. What possibilities do I have with the new java.time API to accomplish my requirements?

What you describe is a day count not a calendar system. A day count is a mechanism for converting the period between two dates into a year fraction.
Strata from OpenGamma includes implementations of many day counts, including 30E/360 which may be the method you need.

With Java-8 there are in principle two options for implementing any calendar:
Using the interfaces ChronoLocalDate and Chronology as starting point
Using the interface Temporal
In my honest opinion, both options are a no-go in your use case. The first option using the java.time.chrono-package forces you to bother with era, year-of-era etc. which is not relevant at all for 360-day-calendars. The second option is too abstract and simple to offer any surplus value compared with just implementing your calendar from the scratch.
A first starting point would be to study the literature and internet, for example in extreme short Wikipedia. It is also important to recognize and take into your design considerations that such a 360-day-"calendar" is not a calendar in strict sense because it does not define a unique and bijective mapping from the calendar date to julian days (several equal dates might belong to different real days! - another important reason to reject the use of chrono-package). The practical consequence would be only to define conversion/factory methods like
Financial360DayCalendar f360 = Financial360DayCalendar.of(LocalDate date);
but not the reverse direction. Beyond the question of mapping/conversion, the calculation of the duration in days between two such dates is the main issue in this "calendar". If you solve both aspects then your task is done. More stuff is probably not needed unless you need formatting. For formatting purposes, you might consider implementing the Java-8-interface TemporalAccessor.
An (incomplete) idea:
class Financial360DayCalendar {
private final int year;
private final int month;
private final int dayOfMonth;
private Financial360DayCalendar(int year, int month, int dayOfMonth) {
this.year = year;
this.month = month;
this.dayOfMonth = dayOfMonth;
}
public static Financial360DayCalendar of(LocalDate date) {
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
if (dayOfMonth == 31) {
dayOfMonth = 30;
}
return new Financial360DayCalendar(year, month, dayOfMonth);
}
public int durationInDaysUntil(Financial360DayCalendar other) {
// check also if other is not before this instance
// ...
// special algorithm (handling all intervening months as 30 days long)
int interestDays = 30 - this.dayOfMonth(); // current day excluded
int monthDelta = other.getMonthCount() - this.getMonthCount();
if (monthDelta > 0) {
monthDelta--;
}
interestDays += (30 * monthDelta + other.dayOfMonth);
return interestDays;
}
public double getYearFraction(Financial360DayCalendar other) {
return durationInDaysUntil(other) / 360.0;
}
private int getMonthCount() {
return this.year * 12 + this.month;
}
}
So it is rather a method for calculating interests, not a real calendar system. You can also refer to this website (in German) to see the details how to calculate the duration.

You should use standard calendar, there is no need to make a custom one. If you need to calculate a days between two dates based on 30 days month, use something like this method:
public int calculateDays(Date d1, Date d2) {
int months = 0;
int days = 0;
months = Months.monthsBetween(new DateTime(d1), new DateTime(d2)).getMonths();
int endOfMonth = d1.getDate() == 31 ? 31 : 30;
if(d1.getDate() > d2.getDate()){
days = endOfMonth - d1.getDate() + d2.getDate();
}else{
days = d2.getDate() - d1.getDate();
}
months = months * 30;
days = months + days;
return days;
}
I used JodaTime to simplify implementation.

Related

How to make code run every X seconds in C programming language

I am trying to make a code run repeatedly every X seconds.
Let me paint a wrestling scenario.
I have already written a code line to give Tyson fury a 5Kg punch at 40 seconds into the fight and then stop.. but there's no way I'm going to win the match with just one 5kg punch at 40 seconds. I need to be able to keep punching every 40 seconds.
Please who knows how I can achieve this?
PS.
{
real punch;
real time = CURRENT_TIME;
real tau = 40;
if (time<=tau)
{
punch=5;
}
else
{
punch=0;
}
return punch;
}
In a scenario where time acquisition is possible, as I can see you use
CURRENT_TIME
You can do it like this:
static int lastTimeExecuted = 0; // Using int here, but you should mach type of CURRENT_TIME
// See how much time passed since last execution
if ((CURRENT_TIME - lastTimeExecuted) >= 40)
{
punch = 5;
lastTimeExecuted = CURRENT_TIME ;
}
else
{
punch = 0;
}
Just remember that code abowe shuld be in a loop.

How do I correctly create a copy of an array in C or set a reference to one?

so, I'm very new to C, coming from a Java/C# background and I can't quite wrap my head around it so far.
What I'm trying to do is program a microcontroller (Adafruit Feather running an atmega32u4 in this case) to pose as a USB-coupled controller for Nintendo Switch and run automated commands.
The project I'm trying to expand upon is using a struct array of commands like this:
typedef struct {
Buttons_t button;
uint16_t duration; // 1 equals 0.025s on ATmega32u4 => 1s = 40
} command;
static const command loop[] = {
// do stuff
{ NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ A, 5 }, { NOTHING, 250 }
};
Now initially this was all there was to it, the program would loop through the commands, send a button to the console and "hold" it for the defined period of time. When the program ran to the end of the array, it would simply reset the index and start anew.
Now I'm trying to send different commands to the console, based on a few easy if..else queries. Specifically, the program will start with a day, month and year variable (the date the Switch console is currently set to) and roll days forward individually to get to a set date in the future. To this end, I want to check at every 'step' if the date +1 day is valid as described in this tutorial and based on the result either roll one day, one day and one month or one day, one month and one year forward. Then I want it to end after a set amount of days.
I wrote several arrays of commands to represent the different steps needed for setting up the controller, moving to where it's supposed to loop, rolling a day, a month or a year like this:
static const command setupController[] = {
// Setup controller
...
};
static const command moveToLoop[] = {
// Go into date settings
...
};
static const command rollDay[] = {
//roll to next day
...
};
static const command rollMonth[] = {
//roll to next month
...
};
static const command rollYear[] = {
//roll to next year
...
};
And another array I want to copy those to like this:
#define COMMANDMAXSIZE 100
static command activeCommand[COMMANDMAXSIZE];
I know this is (extremely) wasteful of memory, but I'm definitely not good enough at C to come up with fancier, more conservative solutions yet.
Then I go into my program, which looks like this:
int main(void) {
SetupHardware(); //Irrelevant, because it is exactly like I downloaded it and it works even with the bumbling changes I've made
GlobalInterruptEnable(); //Ditto
RunOnce(setupController);
RunOnce(moveToLoop);
while (daysSkipped != stopDay)
{
if (datevalid((dayOfMonth + 1), month, year)) {
dayOfMonth++;
RunOnce(rollDay);
}
else if (datevalid(1, (month + 1), year)) {
dayOfMonth = 1;
month++;
RunOnce(rollMonth);
}
else if (datevalid(1, 1, (year + 1))) {
dayOfMonth = 1;
month = 1;
year++;
RunOnce(rollYear);
}
daysSkipped++;
}
}
and finally (I swear I'll be done soon), the start of RunOnce looks like this
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
...
Later in the program, the task that translates commands into button presses for the console actually runs one fixed array, so I figured I'd just "mark" the commands to run as active, and only ever run the active array. Only, it doesn't work as expected:
The program runs, sets up the controller, moves to the date settings and indeed starts to roll a date, but then, regardless if the next day is valid or not, it rolls forward a month, then a year and then it gets stuck moving the simulated analog stick upwards and pressing A indefinitely.
I figure the problem lies in my memcpy to overwrite the active array with the steps I want to run next, but I can't think of a way to solve it. I tried writing a function that was supposed to overwrite the active array element by element using a for loop, but this way the controller wouldn't even set itself up correctly and effectively nothing happened. Usually with any kind of output capabilities I'd try to fit in prints at points of interest, but I have virtually no way of getting feedback on my microcontroller.
Any help would be greatly appreciated.
Ignoring that doing a hard copy of the data is incredibly slow and wasteful, it is also incorrect indeed.
memcpy(activeCommand, stepsToRun, sizeof(activeCommand));
Here you need to copy the size of the data you pass on, not the size of the target buffer! Right now you end up copying more data than you have, because all of these declarations static const command rollDay[] etc get a variable size depending on the number of items in the initializer list.
The quick & dirty fix to your immediate problem would be to pass along the size:
void RunOnce(size_t size, command stepsToRun[size])
{
memcpy(activeCommand, stepsToRun, size);
and then call this function with RunOnce(sizeof rollDay, rollDay); etc.
The activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]); part is also incorrect but not the immediate reason for the bug. See How to find the 'sizeof' (a pointer pointing to an array)? and What is array to pointer decay? etc.
When you pass array to function it decays to a pointer.
RunOnce(rollYear);
Thus
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
}
sizeof(stepsToRun) doesn't yield the correct result as you expected, since it is now sizeof(pointer) in function.
You will have to pass the size of the array as an extra argument to RunOnce function.

Postgresql passwordcheck.c modification

I need to modify the https://github.com/postgres/postgres/blob/REL9_5_13/contrib/passwordcheck/passwordcheck.c in order to check the password before set it.
I'm not very good with C.
So I added this check:
if (validuntil_null)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
and it works, it checks if the expiration date is set.
Now I want to check if this expiration date is reasonable, like no more than 3 months (using "validuntil_time") and if it is different from the previous set.
Any idea?
thanks in advance.
I am not familiar with the internals of PostgreSQL or the configuration of PostgreSQL. My first approach would be to study the documentation to determine if it is possible to set a maximum password expiration time using the admin privileges. I am guessing that you have studied that in detail already and feel that this is the best option.
Based on that, I did review some of the timestamp code in the Postgres github repository. I have not compiled this, but believe this is close. It was not clear to me what Datum is, whether that is already a TimeStampTz type, or if that needs to be converted in some way. It might not compile properly without answering that question. Let me know if this works for you:
At the top of the file, add this to the includes:
#include "utils/timestamp.h"
Later, at the same place where you placed your current code, replace your code with this:
if (validuntil_null) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
} else {
TimestampTz now = GetCurrentTimestamp();
const int ThreeMonthsInMiliSeconds = 90 * 24 * 3600 * 1000;
if(TimestampDifferenceExceeds(now, validuntil_time, ThreeMonthsInMiliSeconds) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration time is greater than 90 days")));
}
}
Here is the source code for that timedifference function from timestamp.c:
/*
* TimestampDifferenceExceeds -- report whether the difference between two
* timestamps is >= a threshold (expressed in milliseconds)
*
* Both inputs must be ordinary finite timestamps (in current usage,
* they'll be results from GetCurrentTimestamp()).
*/
bool
TimestampDifferenceExceeds(TimestampTz start_time,
TimestampTz stop_time,
int msec)
{
TimestampTz diff = stop_time - start_time;
return (diff >= msec * INT64CONST(1000));
}
Thanks John, at the end I managed in that way:
if (validuntil_null) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("password expiriration missing")));
} else {
TimestampTz now = GetCurrentTimestamp();
const off64_t threshold = (const off64_t)((off64_t)90 * 24 * 3600 * 1000 );
if (now > validuntil_time) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\nERROR now: %ld validuntil_time: %ld threshold: %ld",now,validuntil_time,threshold)));
} else {
const off64_t diff= (const off64_t)((off64_t)(validuntil_time - now)/1000);
if (diff >= threshold) {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\nERROR: DATE is more than 90 days: now: %ld validuntil_time: %ld threshold: %ld",now,validuntil_time,threshold)));
}
elog(INFO,"\nnow: %ld validuntil_time: %ld threshold: %ld diff: %ld",now,validuntil_time,threshold,diff);
}
}
Thanks

Not able to pass the hidden test in year to century program c

My code on codefights works well for all the test cases but doesn't pass one hidden test case. The problem is to convert the given year from 1<=year<=2005 into century.
I wrote all the code. I just don't get what I should change to get the hidden test passed.
This is my code:
int centuryFromYear(int year)
{
while(year>=1&&year<=2005)
{
int x=year/100;
if(year%10==0)
{
return(x);
}
else
{
return(x+1);
}
}
}
Corrected Code -
int centuryFromYear(int year)
{
int x=year/100;
if(year%100==0)
{
return(x);
}
else
{
return(x+1);
}
}
You were almost there too.
Hope this helps.
The part you're off on is when a century starts/ends.
The 20th century is from 1901 - 2000, the 19th century from 1801 - 1900, etc. So the result is to divide the year by 100 (right so far), then add 1 to the result unless the year is divisible by 100, not 10 as you have.
So instead of:
if(year%10==0)
You want:
if(year%100==0)
Also, the while loop is not needed. You can remove it entirely.
Assuming year is positive,
int centuryFromYear (int year)
{
return (year + 99) / 100;
}
would suffice

Cannot get MT4 indicator to work using prebuilt library

I'm using the code from this article https://www.mql5.com/en/articles/159 to calculate when a new bar opens but it's not displaying the historical data for the indicator.
I have modified the TimeCurrent() to iTime( _Symbol, _Period, shift ) so as to try to handle this, but it's not working.
Could you tell me what I'm doing wrong please?
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 RoyalBlue
#include <Lib_CisNewBar.mqh>
CisNewBar current_chart;
//---- input parameters
extern int Length=18; // Bollinger Bands Period
extern int Deviation=2; // Deviation was 2
extern double MoneyRisk=1.00; // Offset Factor
extern int Signal=1; // Display signals mode: 1-Signals & Stops; 0-only Stops; 2-only Signals;
extern int Line=1; // Display line mode: 0-no,1-yes
extern int Nbars=1000;
//---- indicator buffers
double TrendBuffer[];
extern bool SoundON=true;
bool TurnedUp = false;
bool TurnedDown = false;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- indicator line
SetIndexBuffer(0,TrendBuffer);
SetIndexStyle(0,DRAW_LINE,0,1);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
short_name="Example ("+Length+","+Deviation+")";
IndicatorShortName(short_name);
SetIndexLabel(0,"Trend Value");
//----
SetIndexDrawBegin(0,Length);
//----
return(INIT_SUCCEEDED);
}
void deinit()
{
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int shift;
for (shift=Nbars;shift>=0;shift--)
{
TrendBuffer[shift]=0;
}
for (shift=Nbars-Length-1;shift>=0;shift--)
{
int period_seconds=PeriodSeconds(_Period);
datetime new_time=iTime(_Symbol,_Period,shift)/period_seconds*period_seconds;
if(current_chart.isNewBar(new_time))
{
Print("time[shift] = "+TimeToString(time[shift]));
if( Close[shift] > Close[shift+1] )
TrendBuffer[shift]=1;
else if(Close[shift] < Close[shift+1] )
TrendBuffer[shift]=-1;
else
TrendBuffer[shift]=0;
}
}
return(0);
}
Thanks.
a) The "new"-MQL4.56789 has another syntax
For Custom Indicator, the "new"-MQL4.56789 source shall rather read
void OnInit(){ ... }andvoid OnDeinit( const int anMT4_Reason2callDeinit ){ ... }
b) The datetime
Your code defines a variable new_time, typed as a datetime
The datetime type is intended for storing the date and time as the number of seconds elapsed since January 01, 1970.
and
Values range from 1 January, 1970 to 31 December, 3000
So, in case of your new_time assignment, the proper iTime() value is divided by an amount of PeriodSeconds() and right next it is re-multiplied by the exact same value, which should not change the value of the iTime() result.
Such operation, while having no theoretical impact on result, might in practice of a code-execution introduce a risk of a numerical inaccuracy, range overflow/underflow and a theoretical notice about a resolution of an 8-byte class storage is not helping to go past the upper bound limit, stated in the documentation as Dec-31, 3000.
In similar cases unpredicatable results and even MT4 unhandled exceptions and MQL4-code terminations are to be expected.
What worse one may expect for a production grade software? So, avoid, avoid and avoid any such risk.
There is no direct positive value for such a Custom Indicator calculation step.
c) TimeCurrent() / PeriodSeconds() side-effect of rounding
While iTime() is always divisible by it's "own" time-frame PeriodSeconds(), TimeCurrent() is not.
Thus one may read the original ( assumed ) construct of
TimeCurrent() / PeriodSeconds() // .DIV is subject to rounding to int
* PeriodSeconds(); // before the forthcoming .MUL
"hacks" the need to align a [last known server time, time of the last quote receipt for one of the symbols selected in the "Market Watch" window] to one's "own" time-frame value of a start-of-current bar time.
d) The article is from 11 October 2010 (!) - be very carefull in MQL4
Current MQL4 code-execution engine is Build 890 ( 25 Sep 2015 ), so your cited source was using an MQL5 language syntax some 5 years old (!!), which namely in MQL4-domain means _be_very_carefull_
In the meantime string-s ceased to be string-s,
many GUI functions have several calling protocols in parallel,
andcountless man*years of DLL/API-code-base dev/maint were lost due to similar moving sands.
So -5- years gap is a warning per-se.
One never enters the same river twice
The recent state of "new"-MQL4.56789 allows a clean approach:
in case your motivation is just to be able to detect on-demand a situation a new bar has started, the Build-890/1174 compiler allows for a cleaner approach:
bool aNewBarEVENT( const string anFxSYMBOL, // _Symbol,
const int aTimeFRAME // PERIOD_M6
)
{ static int pBars = EMPTY; // previous
int oBars = iBars( anFxSYMBOL, aTimeFRAME ); // observed
if ( pBars == oBars ) return( False ); // .NACK
pBars = oBars, return( True ); // .UPD + .ACK
}

Resources