creating a recursive method in C# for - recursion

Recursieve methode die voor een gegeven beginsaldo en een gegeven spaarpercentsge uitrekent hoeveel het eindsaldo is na een gegeven aantal jaren.
Must: beginsaldo, spaarpercentage en aantal jaren moet kunnen worden meegeeven aan methode als argumenten’.
Einsaldo teruggeven als returnwaarde
Spaarpercentage in %’
Methode is static en recursief
Methode maakt geen gebruik van static variabelen
English Version
Recursive method that calculates for a given opening balance and a given savings percentage how much the final balance is after a given number of years. Must: initial balance, savings percentage and number of years must be able to be credited to method as arguments'. Return net balance as return value% Savings percentage in% Method is static and recursive Method does not use static variables

public static float NettEnd(float NettStart, float percentage, int years)
{
if (years == 0)
return NettStart;
else
{
years = years - 1;
float factor = 1 + (percentage / 100);
return NettEnd(NettStart * factor, percentage, years);
}
}
I used google translate and I believe this is what u are looking for ;). I did test it before sharing!!

Related

How to translate the default ModelErrors in ASP.NET Core?

In my app, I have custom ModelErrors set, with a fixed message in my case in spanish, for example:
if (tripOdometer <= 0)
{
ModelState.AddModelError("Odometer", $"Inserte una distancia superior a la última almacenada, que fue de {lastFuelingEntryOdometer}");
return View(request);
}
But my problem is that the errors that come with DataAnnotations package are in english (logically), and produce in my case a spanglish output.
A property in one of my models:
[Required]
[Range(1970, 2021)]
[Display(Name = "Año de Fabricación")]
public int Year { get; set; }
OUTPUTS:
The Año de Fabricación field is required.
The field Año de Fabricación must be between 1970 and 2021.
Is it possible to translate them, in a general way for all the models and properties?

Woocommerce and WPML: Creating and traducing products

When I create a product with the methods of "WC_Product" with WPML enabled by default Woo creates it in the English language.
How can I determine the product creation language?
$product = new WC_Product;
$product->set_name('My test product');
$product->set_slug('test-product');
$product->set_description('This is my test product');
$product->set_sku('some_sku');
$product->save();
Thanks for your help!
I done it with the methods from $sitepress object:
global $sitepress;
// Create the product in defaul language
// First switch de language for the product to create
$language_code_default = 'es';
$sitepress->switch_lang($language_code_default);
// Create product with de Woo methods
$product_es = new WC_Product;
$product_es->set_name('PRODUCTO EN ESPAÑOL');
$product_es->set_slug('producto-wc');
$product_es->set_description('Este producto ha sido creado con WC_Product');
$product_es->set_short_description('Este producto ha sido creado con WC_Product');
$post_id_es = $product_es->save();
// Create the traduction
// Remember, switch the traduction language
$language_code_tr = 'en';
$sitepress->switch_lang($language_code_tr);
$product_en = new WC_Product;
$product_en->set_name('PRODUCT IN ENGLISH');
$product_en->set_slug('producto-wc-en');
$product_en->set_description('This product was made from spanish version');
$product_en->set_short_description('This product was made from spanish version');
$post_id_en = $product_en->save();
// And use the wpml methods to link de traduction with the original language
$element_type = 'post_product';
$trid = $sitepress->get_element_trid($post_id_es, $element_type);
$sitepress->set_element_language_details($post_id_en, $element_type, $trid, $language_code_tr, $language_code_default);
// And then copy de product meta from de original to the traduction
$sitepress->copy_custom_fields($post_id_es, $post_id_en);

Symfony query with Doctrine

I'm working on a little exercise to improve myself with Symfony 3. I have got a mistake in building a query to get adverts not linked to applications and on which the date is older than 30 days.
I have created a new method in my controller, a new query in my advertRepository and a service named "Purger" in which I have to delete these old adverts.
I paste you the code just below (controller, service class, AdvertRepository, services.yml) :
public function purgeAction($days)
{
// Appel du service
$testPurge = $this->get('oc_platform.purger.advert');
$testPurge->purge($days);
return new Response("Purge done !");
}
namespace OC\PlatformBundle\Purger\Advert;
use OC\PlatformBundle\Entity\Advert;
use Doctrine\ORM\EntityManager;
class OCAdvertsPurger
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
//Ce service va récupérer et supprimer toutes les annonces dont la date de
modification
// est plus vieille que X jours. Ce "X" est le paramètre de la méthode.
public function purge($days)
{
$listAdverts = $this->em->getRepository('OCPlatformBundle:Advert')-
>getOldAdvertsOnly($days);
}
}
public function getOldAdvertsOnly($days)
{
// Liste de toutes les annonces
$qb = $this->createQueryBuilder('a')
->leftJoin('a.applications', "app")
->addSelect('app')
;
// On retire celles attachées à des candidatures
$qb->where($qb->expr()->isNull('app.advert_id'));
return $qb
->getQuery()
->getResult()
;
}
public function deleteOldAdvertsOnly($adverts)
{
$qb = $this->createQuery('DELETE $adverts FROM
OC\PlatformBundle\Entity\Advert WHERE DATE_DIFF(CURRENT_DATE(),
updated_at) > $days');
return $qb
->getQuery()
->getResut()
;
}
services:
oc_platform.purger.advert:
class: OC\PlatformBundle\Purger\Advert\OCAdvertsPurger
arguments:
- "#doctrine.orm.entity_manager"
I tried to do something with the DATE_DIFF function() in the same query with queryBuilder but there was a mistake because queryBuilder() doesn't know this function as CURRENT_DATE() I think so I was trying to make it work with two different queries (one with queryBuilder and one with the DQL langage).
Really thanks for going to help me !
To use DATEDIFF function (or any other) you have to install Doctrine Extension :
composer require beberlei/DoctrineExtensions
(https://github.com/beberlei/DoctrineExtensions)
and in your config.yml :
orm:
entity_managers:
default:
dql:
datetime_functions:
DateDiff: DoctrineExtensions\Query\Mysql\DateDiff
You can now use DATEDIFF in your query builder as you would do in SQL.
Functions available :
MySQL :
ACOS, AES_DECRYPT, AES_ENCRYPT, ANY_VALUE, ASCII, ASIN, ATAN, ATAN2, BINARY, BIT_COUNT, BIT_XOR, CEIL, CHAR_LENGTH, COLLATE, CONCAT_WS, CONVERT_TZ, COS, COT, COUNTIF, CRC32, DATE, DATE_FORMAT, DATEADD, DATEDIFF, DATESUB, DAY, DAYNAME, DAYOFWEEK, DAYOFYEAR, DEGREES, DIV, EXP, EXTRACT, FIELD, FIND_IN_SET, FLOOR, FROM_UNIXTIME, GREATEST, GROUP_CONCAT, HEX, HOUR, IFELSE, IFNULL, LAST_DAY, LEAST, LOG, LOG10, LOG2, LPAD, MATCH, MD5, MINUTE, MONTH, MONTHNAME, NOW, NULLIF, PI, POWER, QUARTER, RADIANS, RAND, REGEXP, REPLACE, ROUND, RPAD, SECOND, SECTOTIME, SHA1, SHA2, SIN, SOUNDEX, STD, STDDEV, STRTODATE, STR_TO_DATE, SUBSTRING_INDEX, TAN, TIME, TIMEDIFF, TIMESTAMPADD, TIMESTAMPDIFF, TIMETOSEC, UNHEX, UNIX_TIMESTAMP, UTC_TIMESTAMP, UUID_SHORT, VARIANCE, WEEK, WEEKDAY, YEAR, YEARWEEK
Oracle
DAY, LISTAGG, MONTH, NVL, TO_CHAR, TO_DATE, TRUNC, YEAR
Sqlite
DATE, MINUTE, HOUR, DAY, WEEK, WEEKDAY, MONTH, YEAR, STRFTIME, DATE_FORMAT*, CASE WHEN THEN ELSE END, IFNULL, REPLACE, ROUND
PostgreSQL
TO_DATE, TO_CHAR, AT_TIME_ZONE, COUNT_FILTER, STRING_AGG
I think you can do this in just one query. Which would looks smt like this:
$dateThreshold = new \DateTime();
$dateThreshold->modify("-30 days");
$qb = $this->createQueryBuilder('add')
->delete('add')
->where("add.app_id IS NULL")
->andWhere("add.updated_at <= :date_threshold")
->setParameter("date_threshold", $dateThreshold)
->getQuery()->execute()
I'm not familiar with your db structure, but you should get an idea frmo the example above.
Thank you guys ! I just modified my query and it worked !
I have to bear in mind your trick about adding SQL functions to Doctrine :)

Symfony : Form : get Key Children

How can I get children → elements key?
(see screenshot, I want to access and modify 0, 3, 2)
I need this for add error on collection form.
Thank you!
[EDIT]
foreach ($form->getData()->getCategs() as $d) {
if ($d->getNbHeures() > 8){
$form->get('categs')->get($nb)->get('nbHeures')->addError(new FormError('Vous ne pouvez pas saisir plus de 8h.'));
$nbErreur++;
}
}
I need to get $nb.
[EDIT]
I founded this, but I don't know if it's the best solution:
foreach ($form->get('categs') as $k => $d) {
if ($d->getData()->getNbHeures() > 8) {
$form->get('categs')->get($k)->get('nbHeures')->addError(new FormError('Vous ne pouvez pas saisir plus de 8h.'));
$nbErreur++;
}
}

Programmatically add an invoice to Dynamics AX 2009

I'm am pretty new to Dynamics AX 2009 and since I haven't really found the way to solve what I'm doing I decided to ask here.
I have a requirement to post(?) an invoice through X++.
I already found this HOWTO: Facturación selectiva de líneas en Dynamics AX and even though it's in Spanish I think you will get the idea.
Here is the code I modified from the link:
static void JAEE_PurchFormLetter(Args _args)
{
Num _invoiceNum; // Núm. factura
TransDate _invoiceDate; // Fecha factura
MyPurchFormLetter purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
PurchParmUpdate purchParmUpdate;
PurchParmTable purchParmTable;
PurchParmLine purchParmLine;
TradeLineRefId tableRefId;
PurchTable purchTable;
PurchLine purchLine;
;
ttsbegin;
_invoiceNum = 'Facbyjob';
_invoiceDate = str2date('14-01-2013', 123);
purchTable = PurchTable::find('00000019_062'); // Primer pedido
// Inizializar purchFormLetter con el primer pedido
purchFormLetter.parmCallerTable(purchTable);
purchFormLetter.callInitParmPurchTable(purchTable);
purchFormLetter.proforma(false); // Proforma: NO (Registrar: SI)
purchFormLetter.enableUpdateNowField(true); // Actualizar ahora: SI
purchFormLetter.printFormLetter(false); // Imprimir: NO
purchFormLetter.transDate(_invoiceDate); // Fecha de factura
// Inizializar purchParmUpdate con el primer pedido
purchParmUpdate.clear();
purchParmUpdate.initValue();
purchParmUpdate.ParmId = purchFormLetter.parmId();
purchParmUpdate.SumBy = AccountOrder::Account; // Agrupar por cliente
purchParmUpdate.SumNum = _invoiceNum; // Núm. Factura
purchParmUpdate.SpecQty = PurchUpdate::All; // Actualizar: Todo
purchParmUpdate.DocumentStatus = DocumentStatus::Invoice; // Tipo documento: Factura
purchParmUpdate.Proforma = NoYes::No; // Proforma: NO
purchParmUpdate.SumIncludePending = NoYes::No; // Incluir pendiente: NO
if (purchParmUpdate.validateWrite())
purchParmUpdate.insert();
else
throw Exception::Error;
purchFormLetter.purchParmUpdate(purchParmUpdate);
purchFormLetter.parmParmTableNum(purchParmUpdate.SumNum);
// Tabla temporal, se crea un registro de cabecera del primer pedido (sólo uno)
purchParmTable.clear();
purchParmTable.TableRefId = FormLetter::getTableRef();
purchFormLetter.createParmTable(purchParmTable, purchTable);
if (purchParmTable.validateWrite())
purchParmTable.insert();
else
throw Exception::Error;
tableRefId = purchParmTable.TableRefId;
// BEGIN - LINEAS
// - Repetir para cada línea que se quiera facturar y para cada una y
// - asignar las variabies purchTable y purchLine según proceda
purchParmLine.clear();
purchParmLine.initValue();
// Ajustar cantidades según necesidades
// Catnidades de compra
[purchParmLine.ReceiveNow,
purchParmLine.RemainBefore,
purchParmLine.RemainAfter] = purchFormLetter.qtyPurch(purchLine, naReal());
// Cantidades de inventario
[purchParmLine.InventNow,
purchParmLine.RemainBeforeInvent,
purchParmLine.RemainAfterInvent] = purchFormLetter.qtyInvent(purchLine, naReal());
if (purchParmLine.ReceiveNow)
{
purchParmLine.ParmId = purchParmUpdate.ParmId;
purchParmLine.initFromPurchLine(purchLine);
purchParmLine.setLineAmount();
purchParmLine.TableRefId = tableRefId;
if (purchParmLine.validateWrite())
purchParmLine.insert();
else
throw Exception::Error;
}
// END - LINEAS
// Registrar!
purchFormLetter.reArrangeNow(false); // No organizar
purchFormLetter.run();
ttscommit;
}
My question is in this line: purchFormLetter.callInitParmPurchTable(purchTable);.
Why should initParmPurchTable() be called from within a derived class of PurchFormLetter?
And also, how to accomplish this? I tried declaring my own class MyPurchFormLetter which extends PurchFormLetter, adding the callInitParmPurchTable() method but compiler tells me that the object does not have the method when I try to run the code.
It reads:
Error al ejecutar código: Object objeto no tiene el método 'callInitParmPurchTable'.
EDIT:
What I have done is add the method into the class, in such a way that callInitParmPurchTable() is part of the object. But I am leaving the question open since I don't think this is the right approach.
Have you modified PurchFormLetter::construct(DocumentStatus::Invoice); to return a MyPurchFormLetter?
Also look into the "compile forward" feature
I have found out the following:
It is correct to make a class that inherits from PurchFormLetter and implement there the method callInitParmPurchTable() which obviously is the one that executes initParmPurchTable().
Most likely the one part that I had been missing was to compile MyPurchFormLetter so that the compiler could tell the method existed.

Resources