dart - how do check id/name if contains in List? - list

I have a case when the user wants to add a product to the cart, before that I want to check the id/name product whether or not he was in the cart.
if not then I will add it to the cart, if its already there I will just do edit (adding qty and price)
I have tried using the code below:
Future checkIfProductHasAdded(String uid) async {
for (var i = 0; i < _checkoutList.length; i++) {
print(_checkoutList[i].name);
if (_checkoutList[i].productName == getSelectedProduct.name) {
selectedProductCheckout(i);
print(getSelectedProduct.name +
"PRODUCT CHECKOUT HAS ADDED" +
_checkoutList[i].productName);
// await updateProductCheckout(uid);
break;
} else {
print(getSelectedProduct.name + "NOT FOUND AT PRODUCT CHECKOUT");
//await addProductToCheckout(uid);
break;
}
}
}
when I print() value i does not specify the position on the List, but stays in position 0.
how to make it work?
any answer will be appreciated.

You should check if a product exists in firstWhere clause.
Something like this:
var product = _checkoutList.firstWhere((product) => product.productName == getSelectedProduct.name, orElse: () => null);
if (product == null) addProductToCheckout(uid);
else updateProductCheckout(uid);

This solution is the quickest :
final bool _productIsInList =
_checkoutList.any((product) => product.name == getSelectedProduct.name);
if (_productIsInList) {
// The list contains the product
} else {
// The list does not contain the product
}
NOTE :
If you don't need to compare IDs/names, but you just want to check if a specific item is in a list, you can use _checkoutList.contains(item)

Related

If any row in range (G11:G25) contains boolean (true) then run function, else msgBox

The function I'm running (clearRowContents) in sheet 'Section 2' will clear contents and validation for any checked item (col H) in a list as well as the checkbox itself (col G). The remaining unchecked boxes and list items will then be sorted to clear any blank rows just created by the clearRowContents function. This functions works as tested.
However, if no item is checked (col G == false) and the "clear" button is pressed, how can I have a message pop up letting the user know that they must first check the box next to the item and then press the button to clear its contents from the list? I'm trying to figure out how to write the script for the clearItemMessage function.
Also, for script writing purposes, this sheet will be duplicated many times to create various validation menus for different topics... each sheet will be a different "chapter" in a manual with its own unique set of drop downs (in a MASTER DROPDOWN tab).
link to sheet: https://docs.google.com/spreadsheets/d/1ZdlJdhA0ZJOIwLA9dw5-y5v1FyLfRSywjmQ543EwMFQ/edit?usp=sharing
code:
function clearItemMessage(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var checkboxRange = ss.getRangeList("$G$11:$G$25").getValues();
if (checkboxRange == true){
clearRowContents (col);
} else (Browser.msgBox("To delete items, select the box next to the items and then press the delete button."));
}
function clearRowContents (col){ // col is the index of the column to check for checkbox being true
var col = 7; //col G
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = ss.getDataRange().getValues();
//Format font & size
var sheetFont = ss.getRange("A:Z");
var boxFont = ss.getRange("$G$11:$G$25");
var listFont = ss.getRange("$H$11:$H$25");
sheetFont.setFontFamily("Montserrat");
boxFont.setFontSize(8)
.setFontColor("#434343")
.setBackground("#ffffff");
listFont.setFontSize(12)
.setFontColor("#434343")
.setBackground("#ffffff");
//clear 'true' data validations
var deleteRanges = data.reduce(function(ar, e, i) {
if (e[col - 1] === true) {
return ar.concat(["H" + (i + 1), "G" + (i + 1)]);
}
return ar;
}, []);
if (deleteRanges.length > 0) {
ss.getRangeList(deleteRanges).clearContent().clearDataValidations();
}
//sort based on checkbox value
var range = ss.getRange("$G$11:$H$25");
range.sort({column: 7, ascending: false});
}
In your situation, how about modifying clearItemMessage() as follows?
Modified script:
function clearItemMessage(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var checkboxes = ss.getRange("$G$11:$G$25").getValues();
if (checkboxes.filter(([g]) => g === true).length > 0){ // or if (checkboxes.some(([g]) => g === true)) {
clearRowContents();
} else {
Browser.msgBox("To delete items, select the box next to the items and then press the delete button.");
}
}
From your question, I understood your clearRowContents works. So I proposed to modify clearItemMessage.
In your clearRowContents, var col = 7 is used. So I think that function clearRowContents (col){ can be modified to function clearRowContents (){.
Reference:
filter()

Place order, clear Cart in Nop Commerce 4

How can I Place an order from the cart and clear the cart?
I want to do this in my own controller and not by the checkout page.
I try to use this, but it doesn't work
//place order
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
GenerateOrderGuid(processPaymentRequest);
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName =
_genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer,
NopCustomerDefaults.SelectedPaymentMethodAttribute,
_storeContext.CurrentStore.Id);
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo",
processPaymentRequest);
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
You can use PlaceOrder method in IOrderProcessingService to place an order. CheckoutController also uses this method. For using it, you have to create a ProcessPaymentRequest by yourself. here is a sample code for such a task (I use the code placed in the CheckoutController which doing the same job):
var processPaymentRequest = HttpContext.Session.Get<ProcessPaymentRequest>("OrderPaymentInfo");
if (processPaymentRequest == null)
{
//Check whether payment workflow is required
if (_orderProcessingService.IsPaymentWorkflowRequired(cart))
return RedirectToRoute("CheckoutPaymentInfo");
processPaymentRequest = new ProcessPaymentRequest();
}
//prevent 2 orders being placed within an X seconds time frame
if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
//place order
processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService, _storeContext.CurrentStore.Id);
//____this is main line of code____
var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
if (placeOrderResult.Success)
{
HttpContext.Session.Set<ProcessPaymentRequest>("OrderPaymentInfo", null);
//do payment process:
var postProcessPaymentRequest = new PostProcessPaymentRequest
{
Order = placeOrderResult.PlacedOrder
};
_paymentService.PostProcessPayment(postProcessPaymentRequest);
if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
{
//redirection or POST has been done in PostProcessPayment
return Content("Redirected");
}
return RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id });
}

After Effects Expression (if layer is a CompItem)

I am trying to make slight modification at line 5 of below After Effects expression. Line 5 checks if the layer is visible and active but I have tried to add an extra check that the layer should not be a comp item. (In my project, layers are either text or image layer and I beileve an image layer means a comp item). Somehow the 'instanceof' method to ensure that layer should not be a comp item is not working. Please advise how to fix this error, thanks.
txt = "";
for (i = 1; i <= thisComp.numLayers; i++){
if (i == index) continue;
L = thisComp.layer(i);
if ((L.hasVideo && L.active) && !(thisComp.layer(i) instanceof CompItem)){
txt = i + " / " + thisComp.numLayers + " / " + L.text.sourceText.split(" ").length;
break;
}
}
txt
While compItem is available only in ExtendScript, you can actually check the properties available in the {my_layer}.source object.
Here's a working example (AE CC2018, CC2019 & CC2020): layer_is_comp.aep
The expression would be something similar to:
function isComp (layer)
{
try
{
/*
- used for when the layer doesn't have a ['source'] key or layer.source doesn't have a ['numLayers'] key
- ['numLayers'] is an object key available only for comp objects so it's ok to check against it
- if ['numLayers'] is not found the expression will throw an error hence the try-catch
*/
if (layer.source.numLayers) return true;
else return false;
}
catch (e)
{
return false;
}
}
try
{
// prevent an error when no layer is selected
isComp(effect("Layer Control")(1)) ? 'yes' : 'no';
}
catch (e)
{
'please select a layer';
}
For your second question, you can check if a layer is a TextLayer by verifying that it has the text.sourceText property.
Example:
function isTextLayer (layer)
{
try
{
/*
- prevent an expression error if the ['text'] object property is not found
*/
var dummyVar = layer.text.sourceText;
return true;
}
catch (e)
{
return false;
}
}
You're mixing up expressions and Extendscript. The compItem class is an Extendscript class and I'm pretty sure that it isn't available for expressions.
I'd suggest reading the docs: https://helpx.adobe.com/after-effects/user-guide.html?topic=/after-effects/morehelp/automation.ug.js

when I select many row of table and insert breakpoint dont show my list correctly?

when I trace code don't show city list correctly
how I can fix it ?
My code
public ActionResult GetCity(int idCountry)
{
TravelEnterAdminTemplate.Models.LG.MyJsonResult myresult = new Models.LG.MyJsonResult();
var citystable = db.Cities.Where(p => p.CountryId == idCountry).ToList();
if (citystable != null)
{
myresult.Result = true;
myresult.obj = citystable;
}
else
{
myresult.Result = false;
myresult.message = "داده ای یافت نشد";
}
return Json(myresult, JsonRequestBehavior.AllowGet);
}
This is not the error you are getting the data. There were 32 data in cities table . You just click on every node there the detail will visible

Vote Restriction Coding Error by Programmer

I am not able to properly launch my site at http://www.enbloc.sg
This is because my programmer is not able to figure out a problem. Any help would be much appreciated.
Visitors vote by clicking on one colour on the traffic light. They are supposed to only have one vote.
The site first checks for cookies and then ip address of voter. If the 2 are identical to a previous visitor, then voting is not allowed. If only one of the 2 are repeated, then voting is permitted.
The idea of having a double restriction is to allow different voters behind a fixed IP to vote. E.g. the employees of a company would not be able to vote since they are likely to be accessing the site via a fixed IP address.
However, currently, visitors are able to click on ALL 3 colours to register 3 votes on their first visit to the site. My coder is not able to resolve this issue and has abandoned me.
I would be most grateful if someone can help. I believe the relevant codes are appended below.
Apologies if my posting is wrongly formatted.
Thanks very much,
Lin En
Extracted from http://www.enbloc.sg/js/functions.js
//update dashboard when vote by user
function vote_update(ip_address, issue_num, vote_status){
var vote_cookie = document.getElementById('vote_cookie').value;
if(vote_cookie != '')
{
if(document.getElementById('thanks').style.display == "none")
{
$("#multi_error").fadeIn("slow");
}
else
{
document.getElementById("thanks").style.display = "none";
$("#multi_error").fadeIn("slow");
}
}
else
{
if(ip_address != ' ' && issue_num != ' ')
{
http.open("POST", "update_vote.php"); // true
http.onreadystatechange = update_vote;
http.setRequestHeader("Content-Type", "application/x-www-form- urlencoded;charset=UTF-8");
http.send("ip="+ ip_address +"&issue_num="+ issue_num + "&vote_status=" + vote_status);
}
else
{
alert("Occur Error for IP or ISSUE!");
}
}
}
// ajax response function
function update_vote(){
if (http.readyState == 4)
{
if (http.status == 200)
{
var xmlDoc = http.responseXML;
var listElements = xmlDoc.getElementsByTagName("list");
var result = listElements[0].getElementsByTagName("total") [0].childNodes[0].nodeValue;
if (result == 1)
{
var issue_num = listElements[0].getElementsByTagName("issue")[0].childNodes[0].nodeValue;
var vote = listElements[0].getElementsByTagName("vote") [0].childNodes[0].nodeValue;
$("#thanks").fadeIn("slow");
load(issue_num, vote);
}
else if (result == 'Multi')
{
if(document.getElementById('thanks').style.display == "none")
{
$("#multi_error").fadeIn("slow");
}
else
{
document.getElementById("thanks").style.display = "none";
$("#multi_error").fadeIn("slow");
}
}
else
{
alert("error");
}
}
}
}
These changes will help:
var already_voted = false;
function vote_update(ip_address, issue_num, vote_status)
{
if(alread_voted) return;
already_voted = true;
// rest of the code
}
This will make sure that only one vote can be cast during a single visit. The cookies take care of the rest and are already working fine.