text:
Q: wrapper class check not working on VF page to render a block Below is my VF page on which i am trying to render a table using page block if the wrapper "productStyleWrapperList"is not empty. If.If it is empty i want to display a custom message.
I don't know why it's not working and i keep getting exception on my page instead of custom message i want to show.Error is "   Content Starts Here
List has no rows for assignment to SObject "Its because my wrapper class is empty.
Can someone please help me figure out what i am doing wrong
VF page
 <apex:page standardController="gii__SalesOrder__c" extensions="AddSalesOrderLinesCon" sidebar="true" tabStyle="gii__SalesOrder__c">
  <apex:stylesheet value="{!URLFOR($Resource.SalesOrderQuoteWizardResource, 'css/core.css')}"/>

  <apex:sectionHeader title="{!$Label.AddLinesFromForecast}"  subTitle="{!gii__SalesOrder__c.Name}"/>

    <apex:form >

    <apex:pageBlock >
        <c:WizardChevron id="Wizard_Chevron" Total_positions="{!strTotalPositions}"
            Default_Position="{!strDefaultHighlightPosition}" Highlight_position="{!strHighlightPosition}"
            Map_Position_Name="{!mapPositionAttributes}"/>

        <apex:pageBlockButtons location="bottom" >

                <apex:commandButton action="{!previousPage}" value="{!$Label.Previous_Button}"/>
                <apex:commandButton action="{!SaveProducts}" value="{!$Label.Next_buttton}"/>
                <apex:commandLink action="{!Cancel}"  value="{!$Label.Cancel_button}" styleClass="cancelBtnCss" />

        </apex:pageBlockButtons>

        <apex:pageBlockSection title="{!$Label.Search_Title}" collapsible="false" >
            <apex:pageBlockSection columns="3">
                <apex:outputLabel value="{!$Label.Product_Name_Search}"></apex:outputLabel>
                <apex:inputText value="{!searchtext}" />
                <apex:commandButton value="{!$Label.Search_button}" action="{!getProducts}" reRender="productdata"/>
            </apex:pageBlockSection>

        </apex:pageBlockSection>

        <apex:pageBlockSection columns="1" title="{!$Label.TableTitle_Products_From_Forecast}" collapsible="true" id="productdata">

            <apex:outputPanel layout="block" styleClass="pSearchShowMore" id="otpNav" >
                <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>
                <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>
                <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!HasPrevious}" reRender="productdata"/>
                <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(HasPrevious)}">Previous Page</apex:outputPanel>
                 ({!IF(PageNumber == 0,1,(PageNumber * PageSize)+1)}-{!IF(CountTotalRecords != null && CountTotalRecords < PageSize,CountTotalRecords,((PageNumber+1) * PageSize))})
                <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(HasNext)}" >Next Page</apex:outputPanel>
                <apex:commandLink title="Next Page" value="Next Page" rendered="{!HasNext}" action="{!Next}" reRender="productdata"/>
                <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>
                <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/>
            </apex:outputPanel>

        <apex:outputPanel >

                    {!$Label.Header_Product_Style}
                    {!$Label.Header_Allocation_Quantity}
                    {!$Label.Header_Product_Name}
                    {!$Label.Header_Product_Code}
                    {!$Label.Header_Forecast}
                    {!$Label.Header_Available_In_Inventory}
                    {!$Label.Header_Order_Quantity}
                    {!$Label.Header_Unit_Price}
                    {!$Label.Header_Unit_Amount_Off}
                    {!$Label.Header_Discount_Percent}
                    {!$Label.Header_Pricing_Overridden_Reason}
                    {!$Label.Header_Selling_Unit_of_Measure}

            <apex:repeat value="{!productStyleWrapperList}" var="prods">

                        <apex:outputText value="{!prods.productStyle}"></apex:outputText>

                        <apex:outputText value="{!productStyleQtyMap[prods.productStyleId]}"></apex:outputText>

                <apex:repeat value="{!prods.productList}" var="prod">

                            <apex:outputField value="{!Prod.sol.gii__Product__c}"></apex:outputField>

                            <apex:outputText value="{!Prod.ProductCode}"></apex:outputText>

                            <apex:outputText value="{!Prod.forecast}"></apex:outputText>

                            <apex:outputText value="{!ProductToAvailableMap[Prod.Id]}"></apex:outputText>

                            <apex:inputField value="{!Prod.sol.gii__OrderQuantity__c}"></apex:inputField>

                            <apex:inputField value="{!Prod.sol.gii__UnitPrice__c}"></apex:inputField>

                            <apex:inputField value="{!Prod.sol.gii__UnitAmountOff__c}"></apex:inputField>

                            <apex:inputField value="{!Prod.sol.gii__DiscountPercent__c}"></apex:inputField>

                            <apex:inputField value="{!Prod.sol.gii__PricingOverriddenReason__c}"></apex:inputField>

                            <apex:OutputText value="{!Prod.sellingUnitOfMeasure}"></apex:OutputText>

                </apex:repeat>
            </apex:repeat>

        </apex:outputPanel>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>

</apex:page>

Apex code
global class AddSalesOrderLinesCon{

    public ApexPages.StandardSetController con{get; set;}
    Public gii__SalesOrder__c salesOrder;
    Public gii__SalesOrder__c sorder{get;set;}
    Public Id warehouseId;
    public List<gii__Product2Add__c> products{get; set;}
    public Map<Id, Id> ProductToInventoryMap{get; set;}
    public Map<Id, Decimal> ProductToForecastMap{get; set;}
    public Map<Id, Decimal> ProductToAvailableMap{get; set;}
    public List<ProductStyleWarpper> productStyleWrapperList{get;set;}
    public list<gii__Location__c> location;
    public Map<Id, List<gii__Product2Add__c>> styleToProductMap{get;set;}
    public Map<Id, String> productStyleNameMap{get;set;}
    public Map<Id, Decimal> productStyleQtyMap{get;set;}
    public Set<Id> productIds{get;set;}
    public Map<String, gii.ProductPrice.ProductRefPrice> mapPP{get;set;}
    // will be used to store search product name
    public string searchtext {get;set;}
    // will be used to display totol number of records
    public Integer CountTotalRecords{get;set;}
    // will be used to display number of pages
    public Integer NoOfPages{get;set;}
    // will be used to set page size
    public Integer PageSize{get;set;}
    // will be used to display page number
    public Integer PageNumber{get;set;}
    public String priceBookName{get;set;}

    // will store product ids
    private Set<Id> productRefIds{get;set;}

    public String strTotalPositions {get;set;}
    public String strDefaultHighlightPosition {get;set;}
    public String strHighlightPosition {get;set;}
    public map<Integer, map<String,String>> mapPositionAttributes {get; set;}

    public AddSalesOrderLinesCon(ApexPages.StandardController controller) {
        // will use label for this
        PageSize = integer.valueOf(Label.Add_Lines_From_Forecast_Page_size);
        PageNumber = 0;
        searchtext = '';

        salesOrder = (gii__SalesOrder__c)controller.getRecord();

        strTotalPositions  = '3';
        strDefaultHighlightPosition = '1';
        strHighlightPosition = '2';
        mapPositionAttributes = new map<Integer, map<String,String>>();
        mapPositionAttributes = WizardChevronManager.fetchMapChevronParameters('Create_Sales_Order',strTotalPositions);

        sorder = [select gii__PriceBookName__c, gii__Warehouse__c, gii__Account__r.phone, gii__Account__r.owner.email, gii__Account__r.name, Sales_Year__c, Sales_Year__r.name, gii__Account__c, Name from gii__SalesOrder__c where id=: salesOrder.Id];
        priceBookName = sorder .gii__PriceBookName__c;

        system.debug('salesOrder:'+ salesOrder);
        warehouseId = sorder.gii__Warehouse__c;
        productRefIds = new Set<Id>();
        ProductToInventoryMap = new Map<Id,Id>();
        ProductToForecastMap = new Map<Id, Decimal>();
        ProductToAvailableMap = new Map<Id, Decimal>();

        location = [select Id from gii__Location__c where Sales_Year__c =: sorder.Sales_Year__c and gii__Warehouse__c= :warehouseId limit 1];

        for(Forecast__c forecast: [select Id, Product_Inventory__c, Product_Inventory__r.Available_to_Sell__c, Total_Quantity__c,Product_Reference__c, Warehouse__c from Forecast__c where Warehouse__c =: warehouseId order by Product_Reference__r.Name asc]){
            productRefIds.add(forecast.Product_Reference__c);
            ProductToForecastMap.put(forecast.Product_Reference__c, forecast.Total_Quantity__c);
            ProductToAvailableMap.put(forecast.Product_Reference__c, forecast.Product_Inventory__r.Available_to_Sell__c);
            ProductToInventoryMap.put(forecast.Product_Reference__c, forecast.Product_Inventory__c);
        }

        getProducts();

    }

    public PageReference previousPage(){
        PageReference pg = new PageReference('/apex/CreateSalesOrderHeader?id='+sorder.gii__Account__c+'&soid='+sorder.id);
        return pg;
    }

    /**********************************
        will navigate to sales order header mobile version page
        create on 7-May-2015
        Name        :   previous_PageMobile

    **********************************/
    public PageReference previous_PageMobile(){
        PageReference pg = new PageReference('/apex/CreateSalesOrderHeader_mobile?id='+sorder.gii__Account__c+'&soid='+sorder.id);
        return pg;
    }

    /**********************************
        will be used to get products created for paging purpose
        create on 13-april
        Name        :   getProducts
        productId   :   product ids
    **********************************/
    public void getProducts()
    {
        system.debug('\n--searchtext--'+searchtext+'\n--'+string.isEmpty(searchtext));
        integer offset = PageNumber*PageSize;
        String soql4count = '';
        if(string.isEmpty(searchtext))
        {
            products = [select Id, gii__ProductStyle__c,gii__StockUM__c, gii__SellingUnitofMeasure__c, gii__SellingUnitofMeasure__r.Name ,gii__ProductStyle__r.Name, gii__ProductCode__c, Name from gii__Product2Add__c where Id in: productRefIds and gii__ProductStyle__c!=null order by gii__ProductStyle__r.Name limit :PageSize offset :offset ];
            soql4count = 'Select count() from gii__Product2Add__c where Id in :productRefIds and gii__ProductStyle__c!=null';
        }
        else
        {
            String search ='%'+searchtext+'%';
            products = [select Id, gii__ProductStyle__c,gii__StockUM__c, gii__SellingUnitofMeasure__c, gii__SellingUnitofMeasure__r.Name ,gii__ProductStyle__r.Name, gii__ProductCode__c, Name from gii__Product2Add__c where Id in: productRefIds and gii__ProductStyle__c!=null and Name like :search order by gii__ProductStyle__r.Name limit :PageSize offset :offset ];
            soql4count = 'Select count() from gii__Product2Add__c where Id in :productRefIds and gii__ProductStyle__c!=null and Name like :search';
        }
        system.debug('\n--products--'+products);

        CountTotalRecords= Database.countQuery(soql4count);
        system.debug('\n--CountTotalRecords--'+CountTotalRecords);
        if(Math.mod(CountTotalRecords, PageSize) == 0)
            NoOfPages = CountTotalRecords/PageSize;
        else
            NoOfPages = CountTotalRecords/PageSize + 1;

        styleToProductMap = new Map<Id, List<gii__Product2Add__c>>();
        productStyleNameMap = new Map<Id, String>();
        productIds = new Set<Id>();
        for(gii__Product2Add__c prod: products){
            productIds.add(prod.Id);
            if(styleToProductMap.get(prod.gii__ProductStyle__c) == null)
               styleToProductMap.put(prod.gii__ProductStyle__c, new List<gii__Product2Add__c>());
            styleToProductMap.get(prod.gii__ProductStyle__c).add(prod);
            productStyleNameMap.put(prod.gii__ProductStyle__c, prod.gii__ProductStyle__r.Name);
        }

        findProductUnitPrice();
        createProductWrapper();
        findAllocationQuanityForStyles();
    }

    public void findProductUnitPrice(){
        List<gii.ProductPrice.ProductRefPrice> pp = new List<gii.ProductPrice.ProductRefPrice> ();
        // Instantiate ProductRefPrice and assign inputs to the members of object
        for(Id prodId: productIds){
            gii.ProductPrice.ProductRefPrice p = new gii.ProductPrice.ProductRefPrice();
            p.ProductReferenceId = prodId;
            p.PriceBookName = priceBookName;
            p.Key = prodId;
            pp.add(p);
        }

        mapPP = new mAP<String, gii.ProductPrice.ProductRefPrice> ();
        mapPP = gii.ProductPrice.getProductUnitPrice(pp);
        system.debug('mapPP'+mapPP);
        system.debug('mapPP'+productIds);

    }

    public PageReference SaveProducts(){
        List<gii__SalesOrderLine__c> solToInsert = new List<gii__SalesOrderLine__c>();
        for(ProductStyleWarpper sylewrap: productStyleWrapperList){
            for(ProductLineWrapper prod: sylewrap.productList){
                gii__SalesOrderLine__c sol = prod.sol;
                if(sol.gii__OrderQuantity__c !=null){
                    solToInsert.add(sol);
                }
            }
        }

        system.debug('solToInsert: '+solToInsert);
        if(solToInsert.size()>0)
            insert solToInsert;
        PageReference returnPage = new PageReference('/apex/ApplyDiscount?id=' + salesOrder.Id);
        return returnPage;
    }

    /**********************************
        will navigate to Discount mobile version page
        create on 7-May-2015
        Name        :   Save_ProductsMobile

    **********************************/
    public PageReference Save_ProductsMobile(){
        List<gii__SalesOrderLine__c> solToInsert = new List<gii__SalesOrderLine__c>();
        for(ProductStyleWarpper sylewrap: productStyleWrapperList){
            for(ProductLineWrapper prod: sylewrap.productList){
                gii__SalesOrderLine__c sol = prod.sol;
                if(sol.gii__OrderQuantity__c !=null){
                    solToInsert.add(sol);
                }
            }
        }

        system.debug('solToInsert: '+solToInsert);
        if(solToInsert.size()>0)
            insert solToInsert;
        PageReference returnPage = new PageReference('/apex/ApplyDiscount_mobile?id=' + salesOrder.Id);
        return returnPage;
    }

    public void findAllocationQuanityForStyles(){
        productStyleQtyMap = new Map<Id, Decimal>();
        for(gii__ProductInventory__c pibl: [select Id, Available_To_Sell__c,gii__Product__c  from gii__ProductInventory__c where gii__Warehouse__c=: warehouseId and gii__Product__c in: productStyleNameMap.keySet()]){
             productStyleQtyMap.put(pibl.gii__Product__c, pibl.Available_To_Sell__c);
        }
        for(Id styleId: productStyleNameMap.keySet()){
            if(productStyleQtyMap.get(styleId) == null)
                productStyleQtyMap.put(styleId, 0.0);
        }

        /*for(Id prodId: productIds){
            if(productStyleQtyMap.get(prodId) == null)
                productStyleQtyMap.put(prodId, 0.0);
        }*/

    }

    public void createProductWrapper(){
         productStyleWrapperList = new List<ProductStyleWarpper>();
         for(Id styleId :styleToProductMap.keySet()){
             ProductStyleWarpper stylewrap = new ProductStyleWarpper();
             stylewrap.productStyle = productStyleNameMap.get(styleId);
             stylewrap.productStyleId = styleId;
             List<ProductLineWrapper> productswrap = new List<ProductLineWrapper>();
             for(gii__Product2Add__c prod: styleToProductMap.get(styleId)){
                ProductLineWrapper prodWrapper = new ProductLineWrapper();
                prodWrapper.Name = prod.Name;
                prodWrapper.Id = prod.Id;
                prodWrapper.ProductCode = prod.gii__ProductCode__c;
                if(prod.gii__SellingUnitofMeasure__c != null)
                    prodWrapper.sellingUnitOfMeasure = prod.gii__SellingUnitofMeasure__r.Name;
                else
                    prodWrapper.sellingUnitOfMeasure = prod.gii__StockUM__c;
                prodWrapper.forecast = ProductToForecastMap.get(prod.Id);
                prodWrapper.AvailableInInventory = ProductToAvailableMap.get(prod.Id);

                gii__SalesOrderLine__c sol = new gii__SalesOrderLine__c();
                sol.gii__Warehouse__c = warehouseId;
                sol.gii__Product__c  = prod.Id;
                sol.gii__SalesOrder__c = salesOrder.Id;
                sol.gii__UnitPrice__c = mapPP.get(prod.Id).UnitPrice;
                prodWrapper.sol = sol;

                productswrap.add(prodWrapper);

             }
             productswrap.sort();
             stylewrap.productList = productswrap;
             productStyleWrapperList.add(stylewrap);

             productStyleWrapperList.sort();
         }
    }
    /*public void createProductWrapper(){
        productLineWrapperList = new List<ProductLineWrapper>();
        for(gii__Product2Add__c prod: products){
            ProductLineWrapper prodWrapper = new ProductLineWrapper();
            prodWrapper.productStyle = prod.gii__ProductStyle__r.Name;
            prodWrapper.Name = prod.Name;
            prodWrapper.ProductCode = prod.gii__ProductCode__c;
            prodWrapper.forecast = ProductToForecastMap.get(prod.Id);
            prodWrapper.AvailableInInventory = ProductToAvailableMap.get(prod.Id);
            productLineWrapperList.add(prodWrapper);
        }
    }*/

    global class ProductStyleWarpper implements Comparable{
        public String productStyle{get;set;}
        public String productStyleId{get;set;}
        public List<ProductLineWrapper> productList{get;set;}

        // Compare opportunities based on the opportunity amount.
        global Integer compareTo(Object compareTo) {

            // Cast argument to AccountHistoryWrapper
            ProductStyleWarpper CompareRec = (ProductStyleWarpper)compareTo;

            // The return value of 0 indicates that both elements are equal.
            Integer returnValue = 0;
            if (productStyle > CompareRec.productStyle) {
                // Set return value to a positive value.
                returnValue = 1;
            } else if (productStyle < CompareRec.productStyle) {
                // Set return value to a negative value.
                returnValue = -1;
            }

            return returnValue;
        }
    }

    global class ProductLineWrapper implements Comparable {

         public gii__SalesOrderLine__c sol{get;set;}
         public String Id{get;set;}
         public String Name{get;set;}
         public String ProductCode{get;set;}
         public Decimal forecast{get;set;}
         public Decimal AvailableInInventory{get;set;}
         public Double OrderQuanity{get;set;}
         public Double unitPrice{get;set;}
         public Double unitAmountOff{get;set;}
         public Double discount{get;set;}
         public String pricingOverridenReason{get;set;}
         public String sellingUnitOfMeasure{get;set;}

         // Compare opportunities based on the opportunity amount.
        global Integer compareTo(Object compareTo) {

            // Cast argument to AccountHistoryWrapper
            ProductLineWrapper CompareRec = (ProductLineWrapper)compareTo;

            // The return value of 0 indicates that both elements are equal.
            Integer returnValue = 0;
            if (Name > CompareRec.Name) {
                // Set return value to a positive value.
                returnValue = 1;
            } else if (Name < CompareRec.Name) {
                // Set return value to a negative value.
                returnValue = -1;
            }

            return returnValue;
        }
    }

    public Boolean hasNext
    {
        get
        {
            return (PageNumber+1)<NoOfPages;
        }
        set;
    }

    public Boolean hasPrevious
    {
        get
        {
            return PageNumber>0;
        }
        set;
    }

    public void previous()
    {
        PageNumber--;
        getProducts();
    }

    public void next()
    {
        PageNumber++;
        getProducts();
    }

}


text:
Q: How to run a longer job in SLURM if the default time limit of partition is not sufficient? I have submitted my job in a linux-cluster(that uses SLURM to schedule job), but the time limit of each partition is only 24hr(actually this limit is set by the admin) and it seems that my code need to run more than a week(as per my guess). I am new to SLURM script and understand a very little about the interplay between the following:
#SBATCH --nodes=
#SBATCH --ntasks-per-node=
#SBATCH --ntasks=
#SBATCH --ntasks-per-core=

I am seeking the way out there to avoid the time limit while submitting job and run my complete job.
Suggestions are appreciated.

A: Time limit is set by admin and that is defined in slurm.conf at /etc/slurm/slurm.conf. There should be partition that defines the limit.
and I am afraid you cannot bypass that limit.
So the only thing that you can do is:

*

*Run for 24 hour and before 24 hour is reached save all the state. (It can be difficult afaik)

*Ask admin to increase the timeout

*Use more number of nodes,core, threads?

For 1 you need to modify the program and save state which most program should provide if they are supposed to run for long duration?
It seems you are from Nepal and if you happen to run it in Kathmandu University HPC you can ask administration they should help you here.
Regarding your second question:
#SBATCH --nodes=
#SBATCH --ntasks-per-node=
#SBATCH --ntasks=
#SBATCH --ntasks-per-core=

nodes means number of physical node.
For ntask related thing I recommend you to look on this link: What does the --ntasks or -n tasks does in SLURM?

A: For anyone getting here, I would suggest looking at "singleton", I found a good example in the following link, which I am pasting below.
Example taken from https://researchcomputing.princeton.edu/support/knowledge-base/slurm
#!/bin/bash
#SBATCH --job-name=LongJob       # create a short name for your job
#SBATCH --nodes=1                # node count
#SBATCH --ntasks=1               # total number of tasks across all nodes
#SBATCH --cpus-per-task=1        # cpu-cores per task (>1 if multi-threaded tasks)
#SBATCH --mem=4G                 # memory per node (4G per cpu-core is default)
#SBATCH --time=00:01:00          # total run time limit (HH:MM:SS)
#SBATCH --dependency=singleton   # job dependency
#SBATCH --mail-type=begin        # send email when job begins
#SBATCH --mail-type=end          # send email when job ends
#SBATCH --mail-user=<YourNetID>@princeton.edu

module purge
module load anaconda3/2020.11
conda activate galaxy-env

python myscript.py

Notice the line #SBATCH --dependency=singleton
And then run multiple times like so:
$ sbatch job.slurm   # step 1
$ sbatch job.slurm   # step 2
$ sbatch job.slurm   # step 3
$ sbatch job.slurm   # step 4
$ sbatch job.slurm   # step 5

redpajama_set_name: RedPajamaStackExchange


text:
Q: SELECT posts, its last 3 comments and count of all comments SELECT posts, its last 3 comments and count of all comments
My code:
SELECT p.*, u.id, u.username username, u.usersurname usersurname, u.usermainphoto userphoto, GROUP_CONCAT(c.text SEPARATOR 'a!k@h#md%o^v&') commenttext,GROUP_CONCAT(c.likes SEPARATOR '-') commentlikes,GROUP_CONCAT(c.dislikes SEPARATOR '-') commentdislikes, GROUP_CONCAT(c.commentdate) commentdate, GROUP_CONCAT(u2.username) commentauthorname, GROUP_CONCAT(c.anonim) commentanonym, GROUP_CONCAT(c.id) commentid, GROUP_CONCAT(u2.id) commentauthorid, GROUP_CONCAT(u2.usersurname) commentauthorsurname, GROUP_CONCAT(u2.usermainphoto) commentauthorphoto, GROUP_CONCAT(c.commentphotoid) commentphotoid
FROM posts p
LEFT JOIN comments c ON c.post = p.postid AND c.commentdel=0
LEFT JOIN users u ON u.id = p.postauthorid
LEFT JOIN users u2 ON u2.id = c.author
WHERE p.postwallid = :id AND p.postdel=0
GROUP BY postid
ORDER BY postid DESC

it gives me all comments, but I need only 3

A: You need a timestamp or counter of something to determine which comments are the three you want. Add that column name between the angle brackets below.
SELECT p.*, u.id, u.username username, u.usersurname usersurname, u.usermainphoto userphoto, GROUP_CONCAT(c.text SEPARATOR 'a!k@h#md%o^v&') commenttext,GROUP_CONCAT(c.likes SEPARATOR '-') commentlikes,GROUP_CONCAT(c.dislikes SEPARATOR '-') commentdislikes, GROUP_CONCAT(c.commentdate) commentdate, GROUP_CONCAT(u2.username) commentauthorname, GROUP_CONCAT(c.anonim) commentanonym, GROUP_CONCAT(c.id) commentid, GROUP_CONCAT(u2.id) commentauthorid, GROUP_CONCAT(u2.usersurname) commentauthorsurname, GROUP_CONCAT(u2.usermainphoto) commentauthorphoto, GROUP_CONCAT(c.commentphotoid) commentphotoid
FROM posts p
LEFT JOIN comments c ON c.post = p.postid AND c.commentdel = 0
LEFT JOIN users u ON u.id = p.postauthorid
LEFT JOIN users u2 ON u2.id = c.author
WHERE p.postwallid = :id AND p.postdel = 0
    and (
        select count(*) from comments as c2
        where c2.postid = p.postid and c2.commentdel = 0
        and c2.<timestamp> <= c.timestamp
    ) < 3
GROUP BY postid
ORDER BY postid DESC

Edit: I didn't add the count of all comments. I think you can easily add it with another subquery in the select list but I know MySQL people don't like subqueries very much.
(
select count(*) from comments as c2
where c2.postid = c.postid and c2.commentdel = 0
) as comment_count

A: I add in SELECT count(postid) as all_comments and at the end LIMIT 0, 3
SELECT count(postid) as all_comments, p.*, u.id, u.username username, u.usersurname usersurname, u.usermainphoto userphoto, GROUP_CONCAT(c.text SEPARATOR 'a!k@h#md%o^v&') commenttext,GROUP_CONCAT(c.likes SEPARATOR '-') commentlikes,GROUP_CONCAT(c.dislikes SEPARATOR '-') commentdislikes, GROUP_CONCAT(c.commentdate) commentdate, GROUP_CONCAT(u2.username) commentauthorname, GROUP_CONCAT(c.anonim) commentanonym, GROUP_CONCAT(c.id) commentid, GROUP_CONCAT(u2.id) commentauthorid, GROUP_CONCAT(u2.usersurname) commentauthorsurname, GROUP_CONCAT(u2.usermainphoto) commentauthorphoto, GROUP_CONCAT(c.commentphotoid) commentphotoid
FROM posts p
LEFT JOIN comments c ON c.post = p.postid AND c.commentdel=0
LEFT JOIN users u ON u.id = p.postauthorid
LEFT JOIN users u2 ON u2.id = c.author
WHERE p.postwallid = :id AND p.postdel=0
GROUP BY postid
ORDER BY postid DESC
LIMIT 0, 3


text:
Q: SonarQube Scanner for MS build with Jenkins failed in the end step These are the final logs:
The SonarQube MSBuild integration failed: SonarQube was unable to collect the required information about your projects.
Possible causes:

*

*The project has not been built - the project must be built in between the begin and end steps

*An unsupported version of MSBuild has been used to build the project. Currently MSBuild 14.0 upwards are supported

*The begin, build and end steps have not all been launched from the same folder

*None of the analyzed projects have a valid ProjectGuid and you have not used a solution (.sln)

Generation of the sonar-properties file failed. Unable to complete SonarQube analysis.


text:
Q: What is the meaning of [] in a matlab function argument? I found the following function call:
reshape(A, 1, [])

This flattens matrix A colum major. I am trying to understand the call. The function documentation says after A there should be a size vector for the reshaped matrix, but in here there is a one followed by [] instead of a two-vector. Is this a way of saying "Do whatever it takes so the matrix will have one row, I don't care what the width is"?
How come Matlab lets you exchange one argument for two like this? I tried googling around and did not find an explanation, and I want to understand what's going on here.

A: [] is an empty matrix. In many MATLAB built-in functions, an empty matrix is interpreted to mean "use the default argument here" or "automatically determine this value". Occasionally it is used to disambiguate two meanings of a function, as with the max function, where max(A,2) compares each element of A to 2 and returns the larger, while max(A,[],2) finds the largest element of each row.
If you read the help for reshape, you will see the following:

You can specify a single dimension size of [] to have the dimension size automatically calculated, such that the number of elements in B matches the number of elements in A. For example, if A is a 10-by-10 matrix, then reshape(A,2,2,[]) reshapes the 100 elements of A into a 2-by-2-by-25 array.


text:
Q: Regular Expression to match sentence with one variable word How do I match a list of words using regular expression.
Like I want to match
This is a apple
This is a orange
This is a peach

I tried This is a [apple|range|peach].
Does not work.
Any ideas? I've sent 5 hours on this, there are "rules" published, but without exhaustive examples, these rules are too mystic.

A: You can use
    Pattern pattern = Pattern.compile( "This is a (apple|orange|peach)" );

    Matcher matcher = pattern.matcher( "This is a orange" );
    if( matcher.find() ) {
        System.out.println( matcher.group( 1 ) );
    }

A: This is a ((?:(?:apple|orange|peach)/?)+)

will match
This is a apple/orange/peach.

whatever the order is .
You will get only one capturing group representing the all list.
(here "apple/orange/peach").

*

*'(?:apple|orange|peach)' means: match one of those three terms, do not capture it

*'(?:.../?)+': match a string finished by '/' or not, multiple times

*'(...)': capture the all list.

This is an apple <-match This is an orange <-match This is a peach <-match This is a banana <-no match.

This is a (apple|orange|peach)

is enough: [apple|orange|peach] that you tried is actually a character class, and would match any 'a', 'p', '|', 'o', ... etc.

A: I'm not sure about Java regexes, but it will be something like
/(apple|orange|peach)/
ie, group them, and use | to say 'or'.

A: Try this:
String str = "This is a peach";
boolean matches = str.matches("(apple|orange|peach)");

If you use a pattern, then you can use
String str = "This is a peach";
Pattern pat = Pattern.compile("(apple|orange|peach)");
Matcher matcher = pat.matcher(str);
boolean matches = matcher.find();


text:
Q: WooCommerce get post tags for products in product category - archive-product.php I need to customize functionality and do own filter in product categories by manufacturers (manufacturers are in product_tag taxonomy) but I can't figure it out..The theme using archive-product.php for category page..
I have the category id this way:
$obj = get_queried_object();
$cat_id = $obj->term_id;

I trying to get tags for each category by this code but form is empty. :(
    function get_tags_in_use($category_ID, $type = 'name'){
    // Set up the query for our posts
    $my_posts = new WP_Query(array(
      'cat' => $category_ID, // Your category id
      'posts_per_page' => -1 // All posts from that category
    ));

    // Initialize our tag arrays
    $tags_by_id = array();
    $tags_by_name = array();
    $tags_by_slug = array();

    // If there are posts in this category, loop through them
    if ($my_posts->have_posts()): while ($my_posts->have_posts()): $my_posts->the_post();

      // Get all tags of current post
      $post_tags = wp_get_post_tags($my_posts->post->ID);

      // Loop through each tag
      foreach ($post_tags as $tag):

        // Set up our tags by id, name, and/or slug
        $tag_id = $tag->term_id;
        $tag_name = $tag->name;
        $tag_slug = $tag->slug;

        // Push each tag into our main array if not already in it
        if (!in_array($tag_id, $tags_by_id))
          array_push($tags_by_id, $tag_id);

        if (!in_array($tag_name, $tags_by_name))
          array_push($tags_by_name, $tag_name);

        if (!in_array($tag_slug, $tags_by_slug))
          array_push($tags_by_slug, $tag_slug);

      endforeach;
    endwhile; endif;

    // Return value specified
    if ($type == 'id')
        return $tags_by_id;

    if ($type == 'name')
        return $tags_by_name;

    if ($type == 'slug')
        return $tags_by_slug;
}

function get_some_tags_man($category_ID){
    $tags = get_tags_in_use($category_ID, 'name');

    // Start our output variable
    $html .= '<form name="terms" id="someID">';
    // Cycle through each tag and set it up
    foreach ($tags as $tag) {
        // Get our count
        $term = get_term_by('id', $tag, 'post_tag');
        $count = $term->count;

        // Get tag name
        $tag_info = get_tag($tag);
        $tag_name = $tag_info->name;

        $html .= "<input type='checkbox' id='$term->slug' name='$term->slug' value='$term->name'>slug'>$term->name
";
    }

    $html .= '</form>';
    return $html;
}

And here I trying to ouput:
echo get_some_tags_man($cat_id);

On this URL address: https://proairsoft.cz/airsoftove-zbrane/


text:
Q: Give/gave advice + every now and then Let's say you are describing your friend. And you say:

Mr.B is our go to person. He gives/gave us advice every now and then.

I constructed a paragraph few months ago, and I used the past verb tense preceeding ''every now and then''. Furthermore, If I use ''gave'' here in this sentence, then it does not sound correct for me.(I'm not sure)
Do we put:

simple present tense+''every now then''
  or
Past tense+''every now and then''

A: While every now and then suggests an activity that still continues intermittently, it is used both in the present tense and the past to mean occasionally.
It's quite legitimate to say both:

We meet them every now and then

and

We used to meet them every now and then.

So you can use either give or gave depending on whether Mr B still gives you advice.
Note that the expression go-to person requires a hyphen in the sense that you are using it.


text:
Q: Querying Relationships in Laravel 5.2 I am having issues trying to query an Eloquent relationship.
I have 2 tables
tbl_deals

*

*id

*deal_id

*merchant_id

tbl_merchants

*

*id

*merchant_id

*merchant_url_text

I defined a deal model as
class deal extends Model
{
    public function merchant() {
        return $this->hasOne('App\merchant', 'merchant_id', 'merchant_id');
    }
}

Now, I want to query all deals based where merchant_url_text = a variable in my controller
Here's what I am trying
$deals = deal::with('merchant')->get(); //Retrieving all the deals with merchants

If I return $deals its giving me all deals with merchant relationship.
How do I constraint the deals by saying where merchant_url_text = $variable
I am trying
return $deals->where('merchant_url_text', $merchant_url_text)->get();

but it is giving me an error saying :

"Missing argument 1 for Illuminate\Support\Collection::get(), called in ..."

I tried to lookup the documentation for querying relationships in Laravel Docs. It talks about this example
$user = App\User::find(1);

$user->posts()->where('active', 1)->get();

In this case, its trying to get the first user and finding corresponding posts related to the user.
In my case I want to filter from all deals, the deals that have merchant_url_text = a specific variable in my controller.
Any help on how I can achieve this?
Thanks

A: Try the following code :
$specific_merchant_url_text = "i don't know";
$deals_with_specific_merchant_url_text = [];
$deals = deal::with('merchant')->get();

foreach($deals as $deal)
     if( $deal->merchant->merchant_url_text==$specific_merchant_url_text)
          array_push($deals_with_specific_merchant_url_text, $deal);

So you get array of deals with specific merchant url text in deals_with_specific_merchant_url_text.
Another approach using DB object :
$deals = DB::table('deals')
        ->join('merchants', 'deals.merchant_id', '=', 'merchants.id')
        ->select('deals.*')
        ->where('merchants.merchant_url_text', $merchant_url_text)
        ->get();

Yours with raw :
$deals = deal::selectRaw('tbl_deals.*')
         ->Join('merchants','deals.merchant_id','=','merchants.merchant_id')
         ->where('merchants.merchant_url_text', '=', $merchant_url_text) ->get();

Hope this helps.

A: With takes a callback. This will bring back all deals but only eager load merchants that match.
$deals = Deal::with(['merchant' => function ($query) use ($url_text){
    return $query->where('merchant_url_text', $url_text);
}])->get();

Flip-side: if you only want deals with a matching merchant, use where has.
$deals = Deal::whereHas('merchant', function ($query) use ($url_text){
    return $query->where('merchant_url_text', $url_text);
})->get();

If you want both, chain them:
$deals = Deal::whereHas('merchant', function ($query) use ($url_text){
    return $query->where('merchant_url_text', $url_text);
})->with(['merchant' => function ($query) use ($url_text){
    return $query->where('merchant_url_text', $url_text);
}])->get();

I capitalized deal because it's standard. It wasn't capitalized in your example.

A: You can use query builder join query .

    DB::table('tbl_merchants')
         ->join('tbl_deals', 'tbl_merchants.merchant_id', '=','tbl_deals.merchant_id')
         ->where('tbl_merchants.merchant_url_text',$merchant_url_text)
         ->get();


text:
Q: ?Help command not doing what is intended and message logger returning false errors in discord.js so here is my code in events/messages:
module.exports = {
    name: 'message',
    execute(message) {
        console.log(`\nServer: ${message.guild.name}\nChannel #${message.channel.name}\nUser: ${message.author.tag}\nContent:\n${message.content}`);
    },
};

the purpose of the above code is to say something like this in console:
Server: Nyomi's server
Channel #general
User: Torcenta#3619
Content:
?help

and here is my help command:
const { prefix } = require('../../config.json');

module.exports = {
    name: 'help',
    description: 'List all of my commands or info about a specific command.',
    aliases: ['commands'],
    usage: '[command name]',
    cooldown: 5,
    execute(message, args) {
        const data = [];
        const { commands } = message.client;

        if (!args.length) {
            data.push('Here\'s a list of all my commands:');
            data.push(commands.map(command => command.name).join(', '));
            data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);

            return message.author.send(data, { split: true })
                .then(() => {
                    if (message.channel.type === 'dm') return;
                    message.reply('I\'ve sent you a DM with all my commands!');
                })
                .catch(error => {
                    console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
                    message.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
                });

        }

        const name = args[0].toLowerCase();
        const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));

        if (!command) {
            return message.reply('that\'s not a valid command!');
        }

        data.push(`**Name:** ${command.name}`);

        if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
        if (command.description) data.push(`**Description:** ${command.description}`);
        if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);

        data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);

        message.channel.send(data, { split: true });

    },
};

but whenever I say ?help in chat, it gives me an error:
Could not send help DM to Torcenta#3619.
 TypeError: Cannot read property 'name' of null
    at Object.execute (/home/runner/Nyomi/events/message.js:4:42)
    at Client.<anonymous> (/home/runner/Nyomi/index.js:37:61)
    at Client.emit (events.js:326:22)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/Nyomi/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at /home/runner/Nyomi/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:52
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 0)

and in chat the bot responds with
<@442082888209399808>, it seems like I can't DM you! Do you have DMs disabled?

(I am <@442082888209399808> it is @ing me)
yet the bot dms me the help command and I can see all of the commands.
and sometimes, when doing the ?help command, it crashes the bot with the following error:
/home/runner/Nyomi/events/message.js:4
        console.log(`\nServer: ${message.guild.name}\nChannel #${message.channel.name}\nUser: ${message.author.tag}\nContent:\n${message.content}`);
                                               ^

TypeError: Cannot read property 'name' of null
    at Object.execute (/home/runner/Nyomi/events/message.js:4:42)
    at Client.<anonymous> (/home/runner/Nyomi/index.js:37:61)
    at Client.emit (events.js:326:22)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/Nyomi/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Nyomi/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/Nyomi/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/Nyomi/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/Nyomi/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/Nyomi/node_modules/ws/lib/event-target.js:132:16)

I am fairly new to this, and request that you help me understand what is wrong and how to fix it.

A: answered by @Diamond

updated the events/message code to be:
module.exports = {
    name: 'message',
    execute(message) {
        if(message.channel.type === 'dm'){
            console.log(`\nMessage was made in DM's\nUser: ${message.author.tag}\nContent:\n${message.content}`)
        } else {
        console.log(`\nServer: ${message.guild.name}\nChannel #${message.channel.name}\nUser: ${message.author.tag}\nContent:\n${message.content}`);}
    },
};


text:
Q: Postgres to Snowflake How to change a Postgres code to Snowflake that has the following signs?
$$ and $1?
Example:
CREATE FUNCTION FCT_Name(timestamp without time zone) returns integer
    language plpgsql
as
$$
DECLARE
  payperiod integer;
  year_start_timestamp timestamp;

BEGIN
  IF $1 is null then
    return null;
  END IF;

  IF date_part('year', $1 at time zone 'z' at time zone 'us/central')::int < 2019 THEN

...
I tried to replace $1 by timestamp without time zone but didn't work.


text:
Q: Box-shadow not working as expected I found this nice box-shadow example on: http://www.paulund.co.uk/creating-different-css3-box-shadows-effects.
I want to apply effect number 2 on a website template that I am building however if I use the code from example 2 anywhere in the site it works fine but as soon as I put it inside the header the shadow doesn't come up anymore:

Logo

 // suppose to get the shadow effect but not

Nav element

Nav element

Nav element

Nav element

Nav element

Nav element

Full code here:http://jsfiddle.net/3NDMB/1/
tks

A: You have 2 problems
The header_2 class in the header states white background, that makes the shadow hard to see.
And your box2 class has a height too high, that also makes the shadow invisible. I changed it to 80 px.
The result:
[http://jsfiddle.net/vals/3NDMB/2/]


text:
Q: Use integrated GPU for desktop display and leave dedicated GPU for computing tasks on Ubuntu 22.04 I have just built a desktop for Deep Learning, using Ubuntu 22.04.
My purpose is straightforward - use IGPU (i7 13700K) for display purposes and leave DGPU (RTX 3090) free for Deep Learning tasks.
In the past, I had done this successfully on my Laptop Lenovo Y520 (i7 7700HQ, GTX 1050) by following method 1, but with Ubuntu 18.04.
I tried the old method, but it did not work (when I plugged HDMI into Mainboard, it showed a black screen). So, I moved to method 2 (with some additional steps, which are proven to work on Ubuntu 20.04). However, the result showed no differences.
Did someone manage to perform this on Ubuntu 22.04 successfully, could you share your experience?
Any advice will be appreciated.


text:
Q: constructor and member init syntax in C++ I saw this piece of code
class Foo {
public:
  int x;
  double y;
  float z;

  Foo(int x, double y, float z)
  // XXX: What are the following doing?
    : x(x),
      y(y),
      z(z) {}

}

I'm guessing what was written after the : is assigning the values to the members (x, y, z ) from the arguments.
Question 1: Why that way and not the following?
  Foo(int x, double y, float z) {
     this->x = x;
     this->y = y;
     this->z = z;
  }

Question 2: in the original style, how does the compiler distinguish the member x from the parameter x? (In my modified pice of code, the qualifier this was used for that purpose)
For example, if I were to write this:
 Foo(int x, double y, float z)
          // XXX: What are the following doing?
            : x(x * 2),
              y(x * 3 + y ),  // which 'x' is the 'x' in 'x * 2'?
              z(z) {}

        }

A: You guess correctly. Those are member initializer lists. The reason this is preferred over directly assigning in the constructor is because it is necessary for const class members, classes with no default constructors, and reference variables. Example:
class A
{
    int b;
public:
    A(int c) : b(c) {}; // No default constructor
};

class Test
{
    A a;         // A class with no default constructor
    const int x; // A constant
    int& r;      // A reference
public:
    Test(int d) : a(5), x(2), r(d) {};
};

int main()
{
    Test test;
}

In this example, both members a and x of class Test cannot be assigned to because the first has no default constructor, while the latter is constant, meaning assignment to it would create an error. Finally, since reference variables cannot be assigned to, an initializer list is needed.
In the end, the primary difference comes down to the fact that initializer lists initialize the variable (who knew?), while assignment in the constructor is done after those member variables' constructors have been called.
As for your second question, you can see for yourself that the parameters are picked before the member variables during the initialization.


text:
Q: How do I debug server side code in Aptana Jaxer? I'm trying to debug some server-side JavaScript code running in Aptana Jaxer and I'm not having any success.  I haven't even been able to find any tutorials or posts about this issue.  Does anyone know if it's possible and if so, what am I missing?

A: You can set you Jaxer.Config.DEV_MODE = true; to get some error information in your browser.
Also use the Jaxer.Log to debug.
Hope this helps a bit.

A: Jaxer and Aptana Studio do not yet have the ability to debug remote scripts from the client side.  That is, you can't single-step into a callback and have your code window show you the first line of code in the remote method.  This is on their wishlist, of course, but it'd be pretty tricky to do well.
Personally, I use logging.  Jaxer has strong facilities for this, in Jaxer.Log.*.
A lot of people sneer at "printf() debugging", but the fact is, it works, and it's often less trouble to set up than an interactive debugger, especially for server applications and remote method invocation.  You just sprinkle logging messages wherever you want to know the state of the system at that point, then make your app try to do the thing that's failing.  Study the logs, rinse, repeat.

A: tail -f /opt/AptanaJaxer/logs/jaxer.log


text:
Q: HP UFT 12.51 Sets same "creationTime" property for multiple Chrome Profiles I want to test one scenario which involves multiple chrome profiles to be setup, and login on each profile using different users and test one Chat client for our company.
Test scenario steps
Launch Profile 1 - Login to the application under test
Launch profile 2 - Login to application under test
Launch profile 3 - Login to application under test
Start chatting on group conversations.
issue Description
When I login to first profile I am setting CreationTime property for next iteration to +1 expecting UFT to identify the same objects on another profile which is not happening. [When I try to manually identify the object they could be identified in object spy.Also Add in is enabled on all profiles]
What I think of that this issue may be because of some user-data argument of chrome. But could not figure out how to fix this. Any help is greatly appreciated!


text:
Q: Automate file transfer activity from local machine to remote machine using WinSCP script I want to transfer file(s) in bulk (approx 50 files at a time) from my local machine to remote machine (Linux server) and I wanted to automate this activity using WinSCP.
I already have generated code by doing manually in WinSCP. Saved the code and created batch file. But it is throwing error like

The filename, directory name, or volume label syntax is incorrect
The system cannot find the path specified.

However the given destination and source are valid/correct.
@echo

"open sftp://XXXXXXXXXXXXXX/ -hostkey=""ssh-rsa XXXX gk:op:09:n8:00:44:32:00:11:bn:mm:pp:45:bh:03:ea"""
"lcd C:\Users\007\Documents\testdata"
"cd /XXX/XXX/XXX/testdata"
"put *"
"exit"

set WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
  echo Success
) else (
  echo Error
)

exit /b %WINSCP_RESULT%

A: What you have posted is no way a batch file that WinSCP would generate. You must have manually altered the script (and broke it).
A batch file that WinSCP would generate would look like:
@echo off

"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
  /log="C:\writable\path\to\log\WinSCP.log" /ini=nul ^
  /command ^
    "open sftp://XXXXXXXXXXXXXX/ -hostkey=""ssh-rsa XXXX gk:op:09:n8:00:44:32:00:11:bn:mm:pp:45:bh:03:ea""" ^
    "lcd C:\Users\007\Documents\testdata" ^
    "cd /XXX/XXX/XXX/testdata" ^
    "put *" ^
    "exit"

set WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
  echo Success
) else (
  echo Error
)

exit /b %WINSCP_RESULT%

An example of WinSCP dialog for generating a batch file for a file transfer:


text:
Q: vtkOrientationMarkerWidget embedded in QTWidget I have embedded the vtkOrientationMarkerWidget to the QTWidget as an axes indicator, but I met a problem there arises a bug:

ERROR: In C:\Dev\Soft\vtk\source\Rendering\OpenGL2\vtkWin32OpenGLRenderWindow.cxx, line 217
vtkWin32OpenGLRenderWindow (00000278F82D1AD0): wglMakeCurrent failed in MakeCurrent(), error: Handle
Invalid

when I multiply generate QTWidget instances by clicking the button.
Because I want to add some buttons in the 3D view, I use QTWidget as a container, which is the root cause of the problem. Are there some solutions for this?
My environment is Python 3.8+PyQT5.15.0+VTK9.0.1
The code is:

*

*The main window:

from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QFrame, QVBoxLayout, QApplication, QPushButton
from axes_widget import VTKWidget2
from axes import Axes
from axes2 import Axes2

class Widget:
    def __init__(self):
        self.window = QMainWindow()
        self.window.resize(500, 400)
        self.window.move(300, 310)

        self.button = QPushButton('3D', self.window)
        self.button.clicked.connect(self.click_3d)
        self.button.move(380, 80)

    def click_3d(self):
        self._win_vtk = VTKWidget2()
        self._win_vtk.show()

if __name__ == '__main__':
    app = QApplication([])
    widget_ins=Widget()
    widget_ins.window.show()
    app.exec_()

*The VTK window:

from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QFrame, QVBoxLayout, QApplication
import sys
import vtk
import vtkmodules.qt
vtkmodules.qt.QVTKRWIBase = "QGLWidget"
# QGLWidget as the base class of the QVTKRenderWindowInteractor, instead of QWidget.
# This change is because it is reported that sometimes QWidget can cause rendering problems.
from vtkmodules.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from serum import dependency, singleton, inject

# @singleton
class VTKWidget2(QMainWindow):
    def __init__(self, parent=None):
        super(VTKWidget2, self).__init__(parent)

        self.camera_focal_point = [0, 0, 0]
        self.camera_position = [-4500, 0, 0]
        self.camera_view_up = [0, -1, 0]  # default, [0,1,0]

        self.camera_azimuth = 0  # -20
        self.camera_zoom = 1.8  # 1.75

        self.z_angle = 0
        self.x_angle = 0
        self.y_angle = 0
        self.x_transform = 200
        self.y_transform = -900  # -820
        self.z_transform = 1000

        # vtk.vtkOutputWindow.SetGlobalWarningDisplay(0)
        self.initial()

    def initial(self):
        self.setWindowTitle("3D_Model")
        self.resize(1000, 800)
        screen = QDesktopWidget().geometry()
        self.self_size = self.geometry()
        self.move(int((screen.width() - self.self_size.width()) / 2),
                  int((screen.height() - self.self_size.height()) / 2))  #

        self.colors = vtk.vtkNamedColors()

        # Create an actor
        # self.actor = vtk.vtkActor()
        self.left_text_actor = vtk.vtkTextActor()
        self.right_text_actor = vtk.vtkTextActor()

        # A renderer and render window
        self.renderer = vtk.vtkRenderer()
        # renderWindow = vtk.vtkRenderWindow()
        # renderWindow.SetWindowName("Display Coordinate Axes")
        # renderWindow.AddRenderer(renderer)

        # An interactor
        # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        # renderWindowInteractor.SetRenderWindow(renderWindow)
        self.renderWindowInteractor = QVTKRenderWindowInteractor()
        self.renderWindow = self.renderWindowInteractor.GetRenderWindow()
        self.renderWindow.AddRenderer(self.renderer)

        # Add the actors to the scene
        # self.renderer.AddActor(self.actor)
        self.renderer.SetBackground(self.colors.GetColor3d("SlateGray"))

        # add mouse interaction mode
        vtkStyle = vtk.vtkInteractorStyleTrackballCamera()
        # vtkStyle = MyInteractorStyle(self.renderWindow)
        # vtkStyle =  vtk.vtkInteractorStyleSwitch()
        # vtkStyle = vtk.vtkInteractorStyleTrackballActor()
        self.renderWindowInteractor.SetInteractorStyle(vtkStyle)
        # self.renderWindow.GetInteractor().SetInteractorStyle(vtkStyle)

        self.transform = vtk.vtkTransform()
        self.transform.Translate(self.x_transform, self.y_transform, self.z_transform)

        # set axes
        self.add_axes()

        self.vtkCamera = vtk.vtkCamera()
        self.update_camera()

        frame = QFrame()
        self.setCentralWidget(frame)  # QMainWindow's property
        vl = QVBoxLayout()
        vl.addWidget(self.renderWindowInteractor)
        # vl.addWidget(self.widget)  # problem: wrong: no widget for QT
        frame.setLayout(vl)

        # Begin mouse interaction
        self.renderWindowInteractor.Initialize()
        self.renderWindowInteractor.Start()

    def add_axes(self):
        # set axes
        ### important: widget must be set as field, otherwise it doesn't show.
        # problem: no widget for QT
        self.widget = vtk.vtkOrientationMarkerWidget()
        self.axis = vtk.vtkAxesActor()
        rgba = [0] * 4
        self.colors.GetColor("Carrot", rgba)
        self.widget.SetOutlineColor(rgba[0], rgba[1], rgba[2])
        self.widget.SetOrientationMarker(self.axis)  ### important
        self.widget.SetInteractor(self.renderWindowInteractor)
        self.widget.SetViewport(0.0, 0.0, 0.4, 0.4)
        self.widget.SetEnabled(1)
        self.widget.InteractiveOn()

    def update_camera(self):
        self.renderer.ResetCamera()
        self.renderer.SetActiveCamera(self.vtkCamera)
        self.vtkCamera.SetFocalPoint(self.camera_focal_point)
        self.vtkCamera.SetPosition(self.camera_position)
        self.vtkCamera.SetViewUp(self.camera_view_up)
        self.vtkCamera.Azimuth(self.camera_azimuth)
        self.vtkCamera.Zoom(self.camera_zoom)
        self.renderWindow.Render()

A: The problem lies in Widget.click_3d(self). Every time you click the button you reassign a new VTKWidget2 to self._win_vtk. Since self._win_vtk is the only reference in your program to any of the VTKWidget2 windows, as soon as you assign a new value to self._win_vtk, the previous VTKWidget2 window will be deleted by the garbage collector (which apparently causes problems with the underlying QGLWidget). One way around this is to make a persistent reference to all the windows, for example by putting them in a list, e.g.
class Widget:
    def __init__(self):
        ....
        self.vtk_windows = []

    def click_3d(self):
        win = VTKWidget2()
        self.vtk_windows.append(win)
        win.show()

This still causes a bunch of errors when the last window is closed an the program exits which seems to be cause by using a QGLWidget as the base of your QVTKRenderWindowInteractor.


text:
Q: stack in reverse order trying to create a function which prints a stack in reverse.
this is the code i have so far:
def read_ints(num):
  integer = int(input("Enter a integer:"))
  stack = Stack()
  for i in range(integer):
    if stack.is_empty() == True:
      stack.push(num)
    else:
      stack.pop()

I have created a test case:
read_integers(3)
4
3
2

so when i type 4, 3 and 2. the output should be 2,3 4.
any help would be great thanks ! at the moment its just printing out one integer three times. So I'm getting 3, 3,3

A:   integer = int(input("Enter a integer:"))

This line needs to be inside your for loop - otherwise you're accepting input once and then looping three times, which is silly.
for i in range(integer):

Assuming you want to read num integers, you should loop up to range(num), not range(integer).
if stack.is_empty() == True:
  stack.push(num)
else:
  stack.pop()

This is probably not what you want -- you're only adding to the stack if it's empty, or else immediately popping. Instead, you want to push all the numbers on first, then pop them all at the end. Also, you've confused num and integer again - you want to add your input to the stack, not your loop limit!
So, assuming your Stack.pop prints out what's being popped:
for i in range(num):
    integer = int(input("Enter an integer: "))
    stack.push(integer)

while not stack.is_empty():
    stack.pop()


text:
Q: The output of functorch.hessian is not understandable I am calculating the hessian of a ( 2,2) linear model using functorch.hessian as follows
model = torch.nn.Linear(2,2).to(device)
inputs = torch.rand(1,2).to(device)
criterion = torch.nn.CrossEntropyLoss()
target=torch.ones(len(inputs), dtype=torch.long).to(device)

func, func_params = functorch.make_functional(model)

def loss(params):
    out = func(params, inputs)
    return criterion(out, target)

H=functorch.hessian(loss)(func_params)

Since I have 2 inputs and 2 outputs so we have basically 4 parameters I was expecting to see the second derivative with respect to these 4 parameters but the output looks different or not understandable. For example, the output of the code above is the following:
((tensor([[[[ 0.0217,  0.0701],
            [-0.0217, -0.0701]],

           [[ 0.0701,  0.2266],
            [-0.0701, -0.2266]]],

          [[[-0.0217, -0.0701],
            [ 0.0217,  0.0701]],

           [[-0.0701, -0.2266],
            [ 0.0701,  0.2266]]]], device='cuda:0', grad_fn=<ViewBackward0>),
  tensor([[[ 0.0718, -0.0718],
           [ 0.2321, -0.2321]],

          [[-0.0718,  0.0718],
           [-0.2321,  0.2321]]], device='cuda:0', grad_fn=<ViewBackward0>)),
 (tensor([[[ 0.0718,  0.2321],
           [-0.0718, -0.2321]],

          [[-0.0718, -0.2321],
           [ 0.0718,  0.2321]]], device='cuda:0', grad_fn=<ViewBackward0>),
  tensor([[ 0.2377, -0.2377],
          [-0.2377,  0.2377]], device='cuda:0', grad_fn=<ViewBackward0>)))

Does anyone have an idea what's going on? and how can I calculate the trace of the hessian matrix in this case?


text:
Q: Foreign key join using hibernate Hi all i've got some errors using join with hibernate
I use postgresql 9.5.
My db tables: cart (cart_id - primary key, cart.product_id references product.product_id - foreign key) and product (product_id - primary key)
Java classes Cart and Product
@Entity
@Table(name = "product")
public class Product{
    @Id
    @Column(name = "product_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int productId;

    @Column(name = "article")
    private String article;

    @Column(name = "name")
    private String name;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "description")
    private String description;

    @Column(name = "manufacturer")
    private String manufacturer;

    @Column(name = "category")
    private String category;

    @Column(name = "unitsinstock")
    private long unitsInStock;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Cart cart;

and
    @Entity
    @Table(name = "cart")
    public class Cart {
    @Id
    @Column(name = "cart_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int cartId;

    @Column(name = "user_id")
    private int userId;

    @Column(name = "product_id")
    private int productId;

    @Column(name = "quantity")
    private int quantity;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "cart", cascade = CascadeType.ALL)
    private Product product;

How should i annotate my classes in order to have query SELECT * FROM cart AS c INNER JOIN product p ON c.product_id = p.product_id?
I tried annotane @PrimaryKeyJoinColumn and @JoinColumn with names/referencedColumnName, but got errors or
hibernate made query (mostly) like SELECT * FROM cart AS c INNER JOIN product p ON c.cart_id = p.product_id So it "connects cart_id and product_id, when I need product_id and product_id in cart and product tables.
Upd. It worked fine before, but after dumping/restoring db this errors appeared.
My HQL query is SELECT c FROM Cart c JOIN c.product

A: Firstly, lazy fetch won't work on @OneToOne. Watch this

You have foreign key on Cart table, so you should map it like this:
Cart entity:
@OneToOne(cascade = CascadeType.All)
@JoinColumn(name = "product_id")
    private Product product;

And for Product entity:
@OneToOne(mappedBy = "product")
    private Cart cart;

Vote it as an answer if i helped you)


text:
Q: CSRF - Axios is removing headers I am using Axios module for Nuxt.js.
I do have problem with CSRF token. Whenever I log in into the app, I cannot send any POST request. The response is always 403.
Axios configuration:
Inside nuxt.config.js
axios: {
    debug: true,
    credentials: true,
    baseURL: `${process.env.API_PROTOCOL}://${process.env.API_HOST}${process.env.API_PORT ? `:${process.env.API_PORT}` : ''}${process.env.API_PREFIX}`,
},

Inside 'axios.js' plugin / interceptor
const EXPIRED_TOKEN_MESSAGE = 'Expired JWT Token';

export default function ({
    $axios, redirect, store,
}) {
    $axios.setHeader('Content-Type', 'application/json');
    $axios.setHeader('Accept', 'application/json');

    $axios.onRequest((config) => {
        const configLocal = config;

        if (config.method === 'post') {
            configLocal.headers['X-Requested-With'] = 'XMLHttpRequest';
            configLocal.headers['x-csrf-token'] = store.state.authentication.csrf;
        }
    });

    $axios.onError((error) => {
        const { response: { data: { message } } } = error;
        // const msg = status === 500 ? 'Internal Server Error' : message;
        if (message === EXPIRED_TOKEN_MESSAGE && store.state.authentication.csrf) {
            store.dispatch('authentication/logout');
            return redirect('/');
        }

        if (process.client) {
            // store.dispatch('alerts/addAlert', { type: 'error', message: msg });
        }

        return Promise.reject(error.response);
    });
}

Request call:
this.app.$axios.$post('resources/add', data).then(() => {
        }).catch(e => console.log(e));

Reproduction steps - under the hood of request:

After I printed request config inside $axios.onRequest as we can see from above everything is set, but in networking not at all

Going further backend server is not receiving any headers:

With console log:
`2019-07-04 18:45:18.380 DEBUG 712 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2019-07-04 18:45:18.380 DEBUG 712 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.`

Any ideas what's wrong ?


text:
Q: How to tell if a key is held down How can i tell if a key is being held down as though it were part of a key combination like Ctrl-Alt-Del or Alt-Tab?
How does one go about accomplishing this?

A: Can you tell us more? What's the desired programming language and operating system?
In C#, VB or C++ on Windows you can use GetKeyState() and GetAsyncKeyState() to determine wether a key is (was) pressed and wether the key is up or down. (MSDN Library)


text:
Q: DNN API Controller - A task was canceled Log We have an JQuery Ajax call that will execute when a user is about to leave a page on a DNN module.
This error is being logged the whole time in the DNN logs.
How can I improve the error handling so that it doesn't log the whole time?
Here is the DNN log:

Here is the Front End Code on the Module :
$(window).on("beforeunload", function () {
    ClearTempUserSessionWhenLeavePage();
});

function ClearTempUserSessionWhenLeavePage() {

    if ($fromButtonEvent == false) {
        var Url = $.fn.GetBaseURL() + 'DesktopModules/DNNCommon/API/Store/ClearTempUserSessionWhenLeavePage';

        $.ajax({
            url: Url,
            type: 'GET',
            async: true,
            dataType: 'json',
            success: function () {

            },
            error: function (x, y, z) {

            }
        }).promise().done(function () {

        });
    }

    $fromButtonEvent = false;
}

We are  inheriting the DNNApiController class on our DNNCommon class.

This is the C# method being called:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{

    if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
    {
        System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
        SessionManager.SetSessionObject("NewCreatedWebUser", null);
        SessionManager.SetSessionObject("UserInfo", null);
        SessionManager.SetSessionObject("NewCustomerCode", null);
    }
}

I have attempted to add two different types of Try Catch clauses, but when I debug the code it won't hit the breakpoints and somehow it still logs the error in the DNN Admin logs. Is there perhaps a Try Catch in the DNNController class that is writing this error?
First attempt with Try Catch Clause with TaskCanceledException and TimeoutException:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
      try
        {
            if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
            {
                System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
                SessionManager.SetSessionObject("NewCreatedWebUser", null);
                SessionManager.SetSessionObject("UserInfo", null);
                SessionManager.SetSessionObject("NewCustomerCode", null);
            }

        }
        catch (Exception ex)
        {
            EventLogController logController = new EventLogController();

            if (ex.InnerException is TimeoutException)
            {
                ex = ex.InnerException;
            }
            else if (ex is TaskCanceledException)
            {
                if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                {
                    ex = new TimeoutException("Timeout occurred");
                    logController.AddLog("Timout Occured - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
                }
          }
         logController.AddLog("Problem Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
 }
}

Second attempt with a TaskCanceledException:
    [AllowAnonymous]
    [HttpGet]
    public void ClearTempUserSessionWhenLeavePage()
    {
        try
        {
            if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
            {
                System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
                SessionManager.SetSessionObject("NewCreatedWebUser", null);
                SessionManager.SetSessionObject("UserInfo", null);
                SessionManager.SetSessionObject("NewCustomerCode", null);
            }

        }
        catch (TaskCanceledException ex)
        {
            EventLogController logController = new EventLogController();
            logController.AddLog("Task Cancelled Exception - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
        }
    }


text:
Q: VBA Access Format Chart in Excel EDITED
If you guys have a link that might help with this problem I'd really like to read it, because so far I haven't seen anything very useful.
In access I'm trying to export arbitrary data to excel, create multiple charts (right now just working on a pie chart), format these charts and then send them to a blank (Chart) sheet.  So far I've exported the data and am able to create the charts, I just have no idea how to format them.
The formatting I want to do is to get rid of the legend, put data labels with the name, value, and percentage, and move it to a "Chart" sheet.
Edit I am now able to get rid of the legend as well as insert the data labels with name, value and percentage.  I am still stuck on moving the Chart object to a new sheet, code at bottom.
I've also tried to record a macro in excel, edit it slightly and then move it over to access but I keep erroring out, usually with an error similar to "This object doesn't have that method".  Below I'll include a test table that I might get and how I create the pie chart.
Code:
Function Excel_Export_Two_Column()
Dim db As DAO.Database, rs As DAO.Recordset
Dim WBO As Object, WSO As Object, WSO2 As Object, XLO As Object, oChart As Object
Dim x As Long, y As Long, z As Integer, strTab As String, strcompany As String
Dim endTable As Long
Dim tempName As String, tempNum1 As Long, tempNum2 As Long, totalEnd As Long

z = 1
Set db = CurrentDb()
Set rs = db.OpenRecordset("QRY2Col")

Set XLO = CreateObject("Excel.Application")
XLO.Application.Workbooks.Add

Set WBO = XLO.Application.ActiveWorkbook
Set WSO = WBO.Worksheets(1)
Set WSO2 = WBO.Worksheets(2)

WSO.Name = Left("export", 31)

For y = 0 To rs.Fields.Count - 1
    WSO.Cells(1, 1) = "Num"
    WSO.Cells(1, y + 2) = rs(y).Name
Next y

x = 1
Do While Not rs.EOF()
    x = x + 1
    WSO.Cells(x, 1) = x - 1
    For y = 0 To rs.Fields.Count - 1
        WSO.Cells(x, y + 2) = Trim(rs(y))
    Next y

    rs.MoveNext
    DoEvents
Loop

WSO.Cells.Rows(1).AutoFilter
WSO.Application.Cells.Select
WSO.Cells.EntireColumn.AutoFit

x = 1
Do While WSO.Cells(x, 1) <> ""
    x = x + 1
Loop

endTable = x - 1

WSO2.Cells(1, 1) = "Name"
WSO2.Cells(1, 2) = "Num"
totalEnd = 2
For x = 2 To endTable
    If (WSO.Cells(x, 2) <> "") Then
        tempName = WSO.Cells(x, 2)
        tempNum1 = WSO.Cells(x, 3)

        For y = 2 To totalEnd
            If (WSO2.Cells(y, 1) = tempName) Then
                tempNum2 = WSO2.Cells(y, 2)
                WSO2.Cells(y, 2) = tempNum1 + tempNum2
                Exit For
            ElseIf (y = totalEnd) Then
                WSO2.Cells(y, 1) = tempName
                WSO2.Cells(y, 2) = tempNum1
                totalEnd = totalEnd + 1
            End If
        Next y
    End If
Next x

Set oChart = WSO2.ChartObjects.Add(500, 100, 500, 300).Chart
oChart.SetSourceData Source:=WSO2.Range("A1").Resize(totalEnd - 1, 2)
oChart.ChartType = 5

strcompany = "Export"
If Dir(CurrentProject.Path & "\COLA_AR_" & Format(Date, "yyyymm") & "_XXX_" & strcompany & ".xlsx") <> "" Then
    Kill CurrentProject.Path & "\COLA_AR_" & Format(Date, "yyyymm") & "_XXX_" & strcompany & ".xlsx"
End If

Call WBO.SaveAs(CurrentProject.Path & "\COLA_AR_" & Format(Date, "yyyymm") & "_test_2_Col.xlsx")

WBO.Close savechanges:=True
Set WBO = Nothing

XLO.Application.Quit
Set XLO = Nothing

rs.Close
db.Close
End Function

Table: Note that this table is in a Query (named "QRY2Col") in Access
Field1          Field2
CTOD            64646515
BFTBC2          6656532
WTOW            451512355
DT3             684321818
STC2            652553548
BFTBC2          12
DT3             84954987
ATCR            99999999
CTOD            64185435
BFTBC2          321569846
STC2            6543518
STC2            3518684
ATCR            35481354

Code for data labels
Set oChart = WSO2.ChartObjects.Add(500, 100, 500, 300).Chart
oChart.SetSourceData Source:=WSO2.Range("A1").Resize(totalEnd - 1, 2)
' Number corresponds to a pie chart
oChart.ChartType = 5

' Adds data Labels
oChart.SeriesCollection(1).HasDataLabels = True

' Format chart
oChart.SeriesCollection(1).DataLabels.ShowCategoryName = True
oChart.SeriesCollection(1).DataLabels.ShowPercentage = True
oChart.SeriesCollection(1).HasLeaderLines = True
oChart.Legend.Delete

Attempted code to move chart
Below is an example of what I recorded (edited by adding "oChart") but this still doesn't work.  The problem that gets highlighted is the "xlLocationAsNewSheet" and VBA says that the "Variable is not defined".
oChart.Location Where:=xlLocationAsNewSheet

Thank you,
Jesse Smothermon

A: For the last part, try this:
oChart.Location Where:=1

' xlLocationAsNewSheet = 1
' xlLocationAsObject = 2
' xlLocationAutomatic = 3

As David pointed out, you cannot use the types/enums etcetera defined in the Excel object library without a reference to it, thus you are stuck using integer constants instead.


text:
Q: Не обновляются сущности @ManyToMany Есть 2 сущности:
Order.java
@Entity
@Table(name = "orders")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private int id;

@Column(name = "price")
private int price;

@ManyToMany(mappedBy = "orders",
        fetch = FetchType.LAZY,
        cascade= CascadeType.ALL
)
private Set<Master> masters;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "garage_id")
private Garage garage;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "client_id")
private Client client;

...........
}

и
Master.java
Entity
@Table(name = "masters")
public class Master extends Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private int id;

@ManyToOne(targetEntity = Order.class,
        fetch = FetchType.LAZY
)
@JoinColumn(name = "current_order_id")
private Order currentOrder;

@ManyToMany(mappedBy = "masters",
        fetch = FetchType.LAZY
)
private Set<Garage> garage;

@ManyToMany(fetch = FetchType.LAZY,
        cascade = CascadeType.ALL)
@JoinTable(name = "orders_and_masters",
        joinColumns = @JoinColumn(name = "master_id"),
        inverseJoinColumns = @JoinColumn(name = "order_id")
)
private Set<Order> orders = new HashSet<>();

.................
}

Если сделать update заказа, то сет с мастерами не изменится.
Также, если сделать update мастера, то currentOrder тоже не изменится.
Ошибка, я думаю, в связях. Ибо передаю правильно и в дебаге прямо перед выполнением update, у сущности все поля правильно изменились, даже сет с мастерами у заказа.
Остальные поля, то есть Garage, Client обновятся и с ними всё хорошо.


text:
Q: Redis connection closed after 5 minutes using docker-compose I've got a simple Node.js application that I'm using docker-compose to run locally. It includes a Redis service using the official Redis Docker image (version 5.0).
My Node.js app is using the official Node image (version 14.17.5).
My custom Node.js application connects to the Redis service using Node Redis (version 4.0.1). The Node Redis client is event based, and at the 5 minute mark is publishing the "end" event, indicating that the connection has been closed. I want the connection to be kept alive.
The connection is kept alive permanently in our staging environment which is using Kubernetes so I don't think it's an issue with the Node.js code. I suspect their is an issue with my docker-compose.yml.
I tried decreasing the Redis tcp-keepalive setting of my Redis application from 300 to 200 (seconds) but this didn't fix my issue.

A: I found a solution that worked for me.
In the docker-compose.yml I added the following configuration to my Node.js service:
services:
  app:
    sysctls:
      - net.ipv4.tcp_keepalive_time=200

Looks like the OS was timing out the TCP connection.


text:
Q: How to find last line in a mapreduce job I am processing a .csvfile. I would like to print only my first and last lines. I have accomplished this using normal Java code but, I did not find any Inputformatwhich will read the lines and find first and last line. My Java code is as as below.
public class CSVToJSON {
public static void main(String[] args) throws ParseException, ClassNotFoundException, FileNotFoundException {
    File file = new File("/../Desktop/ABCD.txt");
    try  {
    BufferedReader csvFile = new BufferedReader(new FileReader("/../Desktop/.csv"));
    BufferedWriter jsonFile = new BufferedWriter(new FileWriter(file));
    InputStream inputStream = new ByteArrayInputStream(jsonNew.getBytes(StandardCharsets.UTF_8));
    jsonFile.write(jsonNew);
    jsonFile.newLine();
    String next, fileContent = csvFile.readLine();
    for (boolean first = true, last = (fileContent == null); !last; first = false, fileContent = next)
    {
       last = ((next = csvFile.readLine()) == null);
       if (first)
    {
       String[] tab = fileContent.split(",");
       String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
       InputStream inputStreamNew = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
       jsonFile.write(line);
       jsonFile.newLine();
    }else if (last) {
        String[] tab = fileContent.split(",");
        String lineLast = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "]" + "\n" + "];
        InputStream inputStreamNewLine = new ByteArrayInputStream(lineLast.getBytes(StandardCharsets.UTF_8));
        jsonFile.write(lineLast);
        jsonFile.newLine();
    }else {
        String[] tab = fileContent.split(",");
        String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
        inputStream inputStreamNormalLine = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
        jsonFile.write(line);
        jsonFile.newLine();
    }
    }
        csvFile.close();
        jsonFile.close();
    } catch (FileNotFoundException e) {
         Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException e) {
        Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
    }


text:
Q: How best to pivot wider only selected rows Below is the sample data
  indcode <- c(71,72,81,82,99,000000,71,72,81,82,99,000000)
  year <- c(2020,2020,2020,2020,2020,2020,2021,2021,2021,2021,2021,2021)
  employment <- c(3,5,7,9,2,26,4,6,8,10,3,31)

  test <- data.frame(indcode, year, employment)

The task is to create a new column that would the 000000 value for each year. I know that this involves a pivot wider but how to get the 000000 to repeat is my struggle. Below is the desired result. Hoping to not have 000000 (Total, all industries) be a row. It would be essentially be a duplicate.
   Year       indcode    employment     total
   2020         71            3           26
   2020         72            5           26
   2020         81            7           26
   2020         82            9           26
   2020         99            2           26
   2021         71            4           31
           and so on...

A: We could do this by detecting one or more zeros (+) from the start (^) to the end ($) of the string in 'indcode' to subset the 'employment' for each 'year' (grouped) to create a new column and then filter out the 0 rows
library(dplyr)
library(stringr)
test %>%
  group_by(year) %>%
  mutate(total = employment[str_detect(indcode, '^0+$')]) %>%
  ungroup %>%
  filter(str_detect(indcode, "^0+$", negate = TRUE))


text:
Q: Is there a way to pause mail delivery in Postfix (accumulate in queue)? When using combination of Postfix/Dovecot, is there a way to tell smtp server (Postfix) not to store mails on disk but hold/add them to queue until "maintenance finished"?
Useful for disk upgrades, volume extensions, chkdisk etc.

A: Just shut down postfix. Any legit sending server will queue your mail and retry after a time delay  if it is not able to contact your server. As long as your maintenance is short, say under 6 hours, your chances of losing mail are very small.

A: I don't believe so; the incoming queue is on disk. Perhaps you could temporarily move the queue to a ramdisk mount?
mkdir /mnt/pframqueue
mount -t tmpfs -o size=512M tmpfs /mnt/pframqueue
service postfix stop
mv /var/spool/postfix/* /mnt/pframqueue/
<<<adjust 'queue_directory' in main.cf to /mnt/pframqueue>>>
service postfix start

Do the opposite once you're done.
IMHO that's more trouble than it's worth, especially if something goes screwy in the mv

A: Use this to stop (pause) and start delivery of outgoing mail again:
sudo postconf -e defer_transports=smtp; sudo postfix reload
sudo postconf -e defer_transports=; sudo postfix reload; sudo postfix flush

This should be applicable to other transports as well.
Source: nixtips.net


text:
Q: Amazon SQS duplicated messages in queue I am not an experienced used in the Amazon SQS service. I have to read messages from a queue that I do not own and process them making a small database with some of the information.
Up until now I just had some code that would read all the messages in the queue and process them. The script was running periodically.
However, recently I observed that the amount of messages in the queue has suddenly become very large. When I took a 10000 sample messages I observed that around 6000 where duplicates.
I am puzzled by this sudden change in behavior (up until now I did not observe duplicate messages). The queue never seems to run out.
This is the code I use to read all the messages from the queue.
conn = boto.sqs.connect_to_region(
    'myregions',
    aws_access_key_id='myacceskey',
    aws_secret_access_key='secretAccesKey')
q = boto.sqs.queue.Queue(connection=conn, url='outputQueue')

rs = q.get_messages(10)
all_messages = []
while len(rs) > 0:
    all_messages.extend(rs)
    print (len(all_messages))
    rs = q.get_messages(10)

Can anybody explain why I am getting duplicated messages suddenly? I do not have permissions to see how large the queue is, how can I get all messages in it? Am I doing it right?

A: After processing a message from the queue you need to send back a notification that the message has been processed and it should be deleted. Failure to do so will just mean the message sits in the queue and is re-fetched until such a time that it reaches the fetch limit and is sent to the dead letter queue or it expires.
SQS does not guarantee uniqueness and you can get duplicates, you can set a Visibility Timeout to prevent the message being read for a period of time after it has been retrieved e.g. a minute or so to give you time to process the message and delete it from the queue. This should avoid duplicates.
As for deleting the message iterate over the messages, process them and then run either...
conn.delete_message(q, message)
or
q.delete_message(message)


text:
Q: Rails , when using destroy_all, is there a way to return number of records, if any deleted? right now I have:
PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

Is there a way I can get back the number, deleted? 0 or more?
deleted_count = PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

deleted_count being either 0 or higher?
Thanks

A: If you use delete_all, it will skip all the destroy callbacks for the records that you're deleting (helpful for when you don't want these to run) and it will return the number of records that have been deleted.

A: Per the documentation, destroy_all returns a collection of the objects destroyed. Knowing this, all you need to do is get that collection's length:
destroyed = PollVote.destroy_all(:user_id => record.user_id, :poll_id => record.poll_id)

destroyed_count = destroyed.length # => The number of records destroyed


text:
Q: What determines the amount of tokens awarded after completing an explorable dungeon? I just completed my first explorable dungeon and was happy to receive 30 tokens, until I realized the rest of the group got 60 and 55 tokens.
Do you miss out if you are dead at the wrong moment in a boss kill, or what determines the number of tokens received when completing the dungeon?

A: Changes from September 25th patch:
"ArenaNet said that dungeons reward 20 tokens for completion and now reward an additional 40 tokens the first time they are completed each day."
"Dungeon tokens are now rewarded at the end of an explorable chain."
Source
Note: There have been various players debating the validity of this information. Many players within the same group have received a varying amount of tokens. As such, there may be other factors involved, or the system may be temporarily bugged.
(Before the patch, dungeon bosses provided tokens, and additional tokens were provided upon the completion of the dungeon)

A: From the recent update, each player gets awarded an extra 40 tokens on top of the usual 20 for each dungeon route he takes in a day (doing three times the same dungeon with the three different routes will give you 180 tokens).
However, update had bugs. Some players were considered to exploit the dungeon and get rewarded only 15 tokens for their first dungeon (then 6), and others only 30. (Behaviour has been corrected since the 2nd of October)
There have been rumors that these players would get their tokens back in a future update, but only if they have reported the bug (these are rumors). It is recommended to send bug reports when this happens and you are still in the dungeon (type "/bug" in the chat).
I personally only receive 15 tokens on my first dungeon and report the bug each time, in case the update would give me the missing one back.


text:
Q: Cбой операции во время установки NLog.Configuration Cбой во время установки НЛог там говориться что оно уже установлено но как можно включить это в референсес в Visual Studio 2012
Идет попытка разрешить зависимость "NLog (≥ 4.5.8)".
У "NLog" уже есть зависимость, определенная для "NETStandard.Library".


text:
Q: How to get the element by class? htmlunit I am using htmlunit to get the webpage data. And I want to get the data with the
. But I can't find the method that is find by the class. How do I get the data?
Here is the webpage source:

2GoGoGo Limited

                                Tel:

+111 1111 2222

                                Fax:

+111 1111 3333

                                E-mail

gogogo@2gogogo.com

                                Company website

http://www.2gotrade.com

                                Address

Company address

                                   Introduction

 We are....

How to get the company detail on the source? thanks lot.

A: We can use function getByXPath as following.
getByXPath("//div[@class='class1 class2']");

In above example,
 '//' indicates to search direct and indirect element
 'div' indicates that my element is type of div
 '@class' indicates attribute name, we can use @id, @name etc.
 'class1 class2' we need to pass all class names here, only 'class1' doesn't work
  here


text:
Q: We are not getting price and images urls catalogProductAttributeMediaList and catalogProductGetSpecialPrice in magento soap api calls? We are getting neither price nor image urls from magento soap api calls  catalogProductAttributeMediaList and catalogProductGetSpecialPrice.
can anyone help me please?

A: when requesting catalogProductAttributeMediaList you will get array of stdObject's with following properties:

*

*file

*label

*position

*exclude

*url

*types

if not, please post your api response to get further advice


text:
Q: Reuse my formula in a SSRS report i'm just starting out with ssrs, and i have a little calculation on two fields in my dataset in textbox A (so the content of textbox A is dataset1.field1 * dataset1.field2)
Now i want to add that number to the another number, and put it in textbox B.
So i thought: i reference the content of textbox A from a calculation in textbox B.
So i googled and found lots of this solution:
ReportItems!textbox1.Value

But that doesn't work?
So i thought: i stick the calculation in a variable, and reference that from textbox A and B, but i can't get that to work (don't know where to define the variable and where to give it the appropriate value)

A: You can declare variables with global scope or group scope.
Global scope variables are visible to the whole report (just like parameters). You can declare global scope variables by right clicking an empty area, click Report Properties, and then select Variables on the left side.
Group scope variables are visible within the group. If you select a Tablix, you will see Row Groups and Column Groups towards the bottom of the designer. Click the arrow at the end of the group and click Group Properties. You can declare variables in there.
Group scope variable is probably what you looking for.
More details here: http://blogs.msdn.com/b/robertbruckner/archive/2008/07/20/using-group-variables-in-reporting-services-2008-for-custom-aggregation.aspx


text:
Q: True random number generation using cell phone Consider a scenario.
True random number generation procedure demands that you have an external hardware device or external system attached to your system from which you can generate true random numbers.A usefulness of true random numbers is that they are hard to reproduce and are widely used in cryptographic applications.
My Method of True Random Number Generation
I have a following scenario.I have radio in my cell phone by tuning my radio to specific known frequency i will output cell phone sound(voice) data to my desktop c# or java application and read raw bytes which i guess will be random.(?)
Is my procedure correct?
if not what can be done in my scenario?


text:
Q: How do you get the XML documentation to show for a referenced C# library? Suppose you have a C# library with several functions, all documented with the usual /// <summary> filled out nicely. Referencing the project will make the function and parameter description appear in the Visual Studio contextual help. But is it possible to have this show if you don't reference the project itself, just a build (and potentially some other file that has the documentation inside)?

A: Yes there is  - the library needs to be built with the "XML Documentation file" tickbox checked (in the project property pages)

With this option ticked the build process will now build an extra XML file in the output directory which contains all of the xml documentation - whenever Visual Studio references an assembly by file it will load and show intellisense documentation from this XML file (if it can be found).

You should distribute this file alongside (in the same directory as) your compiled library.


text:
Q: time comparison with the help of another column I posted a similar question here Determining at most 1 hour time difference between car and non-car mode
but since I didn't get the answer I change the output format to make it simpler. (not sure even its simpler or not)
I have
 household       person     time           mode
      1           1          07:45:00        non-car
      1           1          09:05:00         car
      1           2          08:10:00         non-car
      1           3          22:45:00       non-car
      1           4          08:30:00         car
      2           1          07:45:00        non-car
      2           2          16:45:00       car

I want to find a column to find if non-car mode is at most 1 hour before a car mode in each family.
In the above example first family, the time of first person is 1 hour before person 4, so in new column 4 infant of first person and 1 infant of 4th person.
output:
 household       person     time           mode          household       person     time           mode
      1           1          07:45:00        non-car        1           4          08:30:00        car
      1           2          08:10:00        non-car        1           4          08:30:00        car
      1           3          22:45:00        non-car       NA          NA           NA            NA
      1           2          08:10:00        non-car        1           1          09:05:00        car
      2           1          07:45:00        non-car        NA          NA.          NA            NA
      2           2          16:45:00        car            NA          NA.          NA            NA

no intersection with other family member is NA or whatever like 0
Basically I just need to check if a driver is available for a non-driver or not. a driver is available for a non-driver if:
   the non-driver person's time is at most 1 hour before driver.

so in each household I need to do this comparison. and match driver and non-driver if they can travel together. So if you think you can do that with another output please feel free to do that.
If you think it can not be done with R plz let me know I will think how I can change problem.
Thanks for your time


text:
Q: Suspend Windows Phone 8.1 Silverlight App How to suspend a Windows Phone 8.1 Silverlight App when user presses the back key?

A: A WP8.1 Silverlight has little different lifecycle than WP8.1 RunTime - it inherits it from WP8.0 Silverlight.
Just in short - you don't have Suspended/Resumed, in WP8.0/8.1 Silverlight, instead your app can be put into Dormant/Tombstoned states. You app will call Activated and Deactivated events.


text:
Q: How to delete 90 days older record from room database in android I am trying to delete records older than 90 days but it's not working in room database. I have timestamp in mytable. timestamp storing timestamp of record when record inserted. I am storing timestamp in long in room database.
my timestamps are being inserted please check the image

I also tried to do something like this but is also not working for me
@Query("DELETE FROM datacaptureinfoalibi WHERE timeStamp <= strftime('%s', datetime('now', '-90 day') )")
int deleteOlderData(/*long timeStamp*/);

there are so many solutions available in stackoverflow but non are working for me
Please help me, Any help would be highly appreciated.

A: From your data you are storing the data at the millisecond level strftime('%s','2021-05-07') will result in 1620345600 down to seconds, not milliseconds.
As such none of the stored timestamps that are displayed will be less than the result of the right hand side of the expression (and wouldn't be way into the future).
So you could either divide the stored value by 1000 to drop the milliseconds.
e.g. @Query("DELETE FROM datacaptureinfoalibi WHERE (timeStamp /1000) <= strftime('%s', datetime('now', '-90 day') )") should work (ex1_seconds below)
or alternately multiply the right hand by 1000 to add milliseconds :-
e.g. @Query("DELETE FROM datacaptureinfoalibi WHERE timeStamp <= (strftime('%s', datetime('now', '-90 day') ) * 1000) ") (ex3_millis below)
There is no need for the datetime function so simpler more concise SQL  could be:-
@Query("DELETE FROM datacaptureinfoalibi WHERE (timeStamp /1000) <= strftime('%s','now', '-90 day')") (ex2_seconds below)
or
@Query("DELETE FROM datacaptureinfoalibi WHERE timeStamp <= (strftime('%s','now', '-90 day') * 1000) ") (ex4_millis below)
To demonstrate (the right hand side of the expression/comparison) :-
SELECT
    strftime('%s',datetime('now','-90 day')) AS ex1_seconds,
    strftime('%s','now','-90 day')  AS ex2_seconds,
    (strftime('%s',datetime('now','-90 day')) * 1000) AS ex3_millis,
    (strftime('%s','now','-90 day') * 1000) AS ex4_millis;

results in :-

A: this MikeT answer not worked for me
after so many try below query worked for me
@Query("DELETE from datacaptureinfoalibi where timeStamp<=:timeStampOfNinetyDays")
int deleteOlderData(long timeStampOfNinetyDays);

A: you can delete orlder than particular time by below query
DELETE FROM table_name WHERE date_field <= date('now','-90 day')