text:
Q: DockbarX Applet not loading I used to have dockbarX applet installed on my gnome panel. However one day when I login in I got a error message which can be seen in the screenshot below. So I removed it, and then tried adding it again to the gnome panel but I still get the error message.
I am running the latest version of dockbarX 0.43 on Ubuntu 10.10 Maverick Meerkat with the helpers enabled and media buttons etc. I did not update it recently and have been using this version for a couple of weeks now and got this problem only now.
I tried a reinstall of all the components of dockbarX but still get the error message.
Here is the ~/.dockbarx/log/dockbarx.log
ERROR   | 2011-03-02 12:10:18,984   | Traceback (most recent call last):
ERROR   | 2011-03-02 12:10:18,985   |   File "/usr/bin/dockbarx_factory", line 31, in <module>
ERROR   | 2011-03-02 12:10:18,985   |     import dockbarx.dockbar
ERROR   | 2011-03-02 12:10:18,985   |   File "/usr/lib/pymodules/python2.6/dockbarx/dockbar.py", line 37, in <module>
ERROR   | 2011-03-02 12:10:19,187   |     from groupbutton import *
ERROR   | 2011-03-02 12:10:19,187   |   File "/usr/lib/pymodules/python2.6/dockbarx/groupbutton.py", line 40, in <module>
ERROR   | 2011-03-02 12:10:19,324   |     import zg
ERROR   | 2011-03-02 12:10:19,324   |   File "/usr/lib/pymodules/python2.6/dockbarx/zg.py", line 34, in <module>
ERROR   | 2011-03-02 12:10:19,399   |     iface = client.ZeitgeistDBusInterface()
ERROR   | 2011-03-02 12:10:19,400   |   File "/usr/lib/pymodules/python2.6/zeitgeist/client.py", line 184, in __init__
ERROR   | 2011-03-02 12:10:19,428   |     self.OBJECT_PATH)
ERROR   | 2011-03-02 12:10:19,428   |   File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 244, in get_object
ERROR   | 2011-03-02 12:10:19,496   |     follow_name_owner_changes=follow_name_owner_changes)
ERROR   | 2011-03-02 12:10:19,496   |   File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 241, in __init__
ERROR   | 2011-03-02 12:10:19,520   |     self._named_service = conn.activate_name_owner(bus_name)
ERROR   | 2011-03-02 12:10:19,520   |   File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 183, in activate_name_owner
ERROR   | 2011-03-02 12:10:19,520   |     self.start_service_by_name(bus_name)
ERROR   | 2011-03-02 12:10:19,520   |   File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 281, in start_service_by_name
ERROR   | 2011-03-02 12:10:19,521   |     'su', (bus_name, flags)))
ERROR   | 2011-03-02 12:10:19,521   |   File "/usr/lib/pymodules/python2.6/dbus/connection.py", line 620, in call_blocking
ERROR   | 2011-03-02 12:10:19,574   |     message, timeout)
ERROR   | 2011-03-02 12:10:19,575   | dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: Failed to execute program /usr/local/bin/zeitgeist-daemon: Success

How can I solve this problem?

A: Ok, that's a known problem. There's a bug in zeitgeist and DockbarX 0.43 don't handle that error as it should. Next version will simply not use zeitgeist if there's an error instead of crashing.
It might take a while before the next release of DockbarX (I'm doing some code cleanup that is much more work than I suspected). In the mean time, try to install zeitgeist from the ppa (ppa:zeitgeist/ppa) or remove the ppa and downgrade zeitgest to mavericks own version if you already use the ppa.


text:
Q: Why is Prop not applied to component in component library vue js? I am busy moving my components from our projects into a component library for ease of use and maintainability purposes.
I am using this Vue/Nuxt Library template  following the structure and processes outlined.
Currently I only have 2 components in there a TestButton.vue and a LoaderModal.vue .

The test button works fine when imported/called from an application when it sits in the library as it shows as expected and looks like it should as it is actually a mdb button (which I just used to test component imports). (we use MDB as our main component lib
The problem is with the Loading Modal. Normally you would set the show property of the modal to show or hide it like so.

<template>
  <mdb-modal centered :show="showLoader">
    <mdb-modal-body class="text-center">

          Loading...

{{ longLoadingText }}

{{ text }}

    </mdb-modal-body>
  </mdb-modal>
</template>

using props to show,hide and control text like so

 props: {
    showLoader: { default: true, type: Boolean },
    text: { default: "Loading", type: String },
  },

and it works fine if I run it in the component library itself using

vue serve ./src/components/LoaderModal

but when I set the showLoader prop to true from the application that imports the library it does not show. I can see the modal is in the DOM but the display is set to none.
There are no errors in the console and if I change the Display to "block" the LoadingModal Shows.
Here is the html copied from the DOM that shows it is there, but display is just set to "none"

Loading...

Loading some stuff

My Library Package.json looks as follow

{
  "name": "@myScope/web-commons",
  "version": "0.1.23",
  "private": false,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build --report --target lib --name web-commons ./src/index.js",
    "lint": "vue-cli-service lint",
    "docs:build": "vuepress build docs",
    "docs:dev": "vuepress dev docs"
  },
  "main": "dist/web-commons.common.js",
  "files": [
    "src",
    "assets",https://stackoverflow.com/posts/63504989/edit#
    "dist/*.{js,css}"
  ],
  "dependencies": {
    "mdbvue": "^6.7.1",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/babel-preset-app": "^4.4.6",
    "@vue/cli-plugin-babel": "^4.4.6",
    "@vue/cli-plugin-eslint": "^4.4.6",
    "@vue/cli-service": "^4.4.6",
    "babel-eslint": "^10.1.0",
    "eslint": "^7.3.1",
    "eslint-plugin-vue": "^6.2.2",
    "vue-template-compiler": "^2.6.11",
    "vuepress": "^1.5.2"
  }
}

and the plugin looks as follows in my main project.

import Vue from 'vue'
import * as componets from '@myScope/web-commons'
Vue.use(componets)

Then it is also added to the nuxt.config as a plugin.
Please help
EDIT
Below is the value of the props from the vue dev panel

Update

The following is the link to the codesandbox project for the component library. The library is also on Npm. Try using the LoaderModal Component in any nuxt project to see problem.
Code Sandbox Component Library
Component Implementation Example Nuxt js

A: I see your codesandbox. There is a small mistake using the props in your code for LoaderModal component. If you use a value directly for the props you don't need to bind (:text) it. So you can use the component as below.
<LoaderModal :showLoader="true" text="Some Loading Text"/>

if you use a data element as a props then bind it:
<LoaderModal :showLoader="true" :text="variableName"/>

Here is the working demo of your codesandbox

A: The actual problem seem to have been that all the required css components of the mdblibrary was not being import despite being imported in the index of the component library.
It seems that when adding a plugin to nuxt it calls the install method and nothing else. The solution was to import the css into the component itself and making it "scoped" otherwise it will affect the components in the main application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert a String[] into a set? I did this:
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);

This gives error:
 The method addAll(Collection<? extends String>) in the type Set<String> is
 not applicable for the arguments (String[])

I think my intentions are clear.
Side ques: is there a better way to achieve my desired set? I know already there are no repeated value in my list.

A: The TreeSet constructor accepts a Collection, a String[] can be converted to a List which implements Collection using Arrays.asList().
public static void main(String[] args) {

    String list = "word,another,word2"; //No need for () here
    String[] wordArr = list.split(",");
    Set<String> mySet = new TreeSet<String>(Arrays.asList(wordArr));

    for(String s:mySet){
        System.out.println(s);
    }

}

A: Here's an example using Guava:
package com.sandbox;

import com.google.common.collect.Sets;

import java.util.Set;

public class Sandbox {

    public static void main(String[] args) {
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        Set<String> mySet = Sets.newHashSet(wordArr);
    }
}

If you want to do this without Arrays (I don't recommend, but you're in a class so maybe you can't use it):
package com.sandbox;

import java.util.Set;
import java.util.TreeSet;

public class Sandbox {

    public static void main(String[] args) {
        Set<String> mySet = new TreeSet<String>();
        String list = ("word,another,word2"); // actually this is much bigger
        String[] wordArr = list.split(",");
        for (String s : wordArr) {
            mySet.add(s);
        }
    }

}


text:
Q: How to write a test class for a wrapper class I have created a Class called "SalesMarketing" and i am writing the test class called "SalesMarketingTest" although the test class is passing the "SalesMarketing" class has 0% Code Coverage
/*************************************************************************************************************************
Class Name      :   SalesMarketing
Class Desc.     :   Class used for Sales & Marketing Visual Force Page
Author          :   DM
Description     :   This class is used to populate the Sales & Marketing VF component, displaying  Material Name,Product,
                    item from Material_Records__c and Quantity from Materials_Junction__c. Records are selected from the
                    page (using the checkbox) once an quantity is added the user pushes "save" these records will map
                    back to the "Sales & Marketing" Object with relevant information selected.

***************************************************************************************************************************/

public with sharing class SalesMarketing
{
    public List<Material_Records__c> Materials {get;set;}
    public List<materialWrapper> materialWrapperList {get;set;}
    public Materials_Junction__c marketingJunction {get;set;}
    public String searchString {get;set;}
    public SalesMarketing(ApexPages.StandardController controller)
    //public SalesMarketing()
    {
        system.debug('++ Inside Constructor ');
        marketingJunction = (Materials_Junction__c) controller.getRecord();
        materialWrapperList = new List<materialWrapper>();
        Materials = [select ID,name,Product__c, Item__c, Active__c from Material_Records__c where Active__c =true limit 10];
        for(Material_Records__c obj : Materials)
        {
            materialWrapper tempObj= new materialWrapper();
            tempObj.recordId = obj.id;
            tempObj.name = obj.name;
            tempObj.product = obj.Product__c;
            tempObj.item = obj.Item__c;
            tempObj.selectB = false;
            materialWrapperList.add(tempObj);
        }
    }

    public Pagereference getProductOrItemData(){
        materialWrapperList.clear();
        system.debug('+++ searchString is '+ searchString);
        system.debug('+++ Length for searchString is '+ searchString.length());
        //String searchVal= searchString.trim();
        String searchVal='%'+searchString.trim() +'%';
        system.debug('+++ searchString is '+ searchVal);

         Materials = [select ID,name,Product__c, Item__c, Active__c from Material_Records__c where Active__c =true and (Product__c like :searchVal OR Item__c like :searchVal)];
        for(Material_Records__c obj : Materials)
        {
            materialWrapper tempObj= new materialWrapper();
            tempObj.recordId = obj.id;
            tempObj.name = obj.name;
            tempObj.product = obj.Product__c;
            tempObj.item = obj.Item__c;
            tempObj.selectB = false;
            materialWrapperList.add(tempObj);
        }
        system.debug('+++ materialWrapperList is '+ materialWrapperList);
        system.debug('++ materialWrapperList size is '+ materialWrapperList.size());
        return null;
    }

    //save method
    public Pagereference save()
    {
        list<Materials_Junction__c> recordToInsert = new list<Materials_Junction__c>();
        try{
        for(materialWrapper obj : materialWrapperList)
        {
         Materials_Junction__c temp ;
            if(obj.selectB == true)
            {
                temp = new Materials_Junction__c();
                temp.sales_and_marketing__c = marketingJunction.sales_and_marketing__c;
                temp.Material_Records__c= obj.recordId;
                temp.quantity__C = obj.quantity;
                recordToInsert.add(temp);
            }
            //recordToInsert.add(temp); you are adding element outside the if condition that the reason for save button error
        }
        insert recordToInsert;
        return new Pagereference('/'+marketingJunction.sales_and_marketing__c);
        }catch(Exception e){
        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.Error,e.getMessage()));
        return null;
        }
    }

    public class materialWrapper
    {
        public string recordId {get; set;}
        public string name {get; set;}
        public string product {get; set;}
        public string item {get; set;}
        public Decimal quantity {get; set;}
        public boolean selectB {get; set;}

        public void materialWrapper()
        {
            recordId = '';
            name = '';
            product = '';
            item = '';
            quantity = 0.0;
            selectB = false;
        }
    }
}

THIS IS THE SalesMarketingTest TEST CLASS
@isTest
private class SalesMarketingTest
{
    static testmethod void  SalesMarketing()
    {

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Account
        *****************************************************************************************
        */
            Account acct = new Account
                  (Name='Test');
            insert acct;

        /**
        *****************************************************************************************
        *                     Querying RT Object for Contact object
        * Sales_Contact__c on Material Request has an Filter Criteria Applied on lookup
        *Filter = Contact Record Type = Schroders Employee
        *****************************************************************************************
        */

        RecordType rt = [select id,developername,Name from RecordType where SobjectType='Contact' and developername='Employee' Limit 1];

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Contact
        *                         Passing Contact RT Id From Query Above
        *****************************************************************************************
        */
            Contact cont = new Contact (
                   AccountId= acct.id,
                   MailingCountry ='United States',
                   recordTypeId=rt.id,
                   LastName ='Test Name');
            insert cont;

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Material Request
        *****************************************************************************************
        */

            sales_and_marketing__c MKTRequest = new sales_and_marketing__c(
                   Name = 'Test Name',
                   Sales_Contact__c = Cont.id,
                         //  Delivery_Date__c =   datatype "Date/Time"
                   Delivery_Date__c = DateTime.newInstance(2011, 11, 18, 3, 3, 3),
                       //Event_Date__c = datatype "Date"
                   Event_Date__c = Date.newInstance(2017,2,2)
                       );
            insert MKTRequest;

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Material Record
        *****************************************************************************************
        */
            Material_Records__c MRecords= new Material_Records__c(
                   Active__c = True,
                   Item__c='United States',
                   Product__c='Test Name');
            insert MRecords;

        /**
        *****************************************************************************************
        *                          This is test data for Materials_Junction
        *****************************************************************************************
        */
            Materials_Junction__c MJunction= new Materials_Junction__c(
                   Material_Records__c =MRecords.id,
                   sales_and_marketing__c= MKTRequest.id);
            insert MJunction;

        /**
        *****************************************************************************************
        *Checking that Materials_Junction__c has a record.
        *****************************************************************************************
        */
        MJunction = [
            Select
            Id,
            Name,
            Material_Records__c,
            sales_and_marketing__c
                From Materials_Junction__c
            WHERE sales_and_marketing__r.id =:MKTRequest.Id
            AND  Material_Records__r.id =:MRecords.id];
        /**
        *****************************************************************************************
        *System Assert Statements. Checking that Record has the correct value from insert statements
        *****************************************************************************************
        */
        system.assertEquals(MKTRequest.Id, MJunction.sales_and_marketing__c); //Check that Sales& MKT Id is same as MKTRequest.Id
        system.assertEquals(MRecords.Id, MJunction.Material_Records__c ); //Check that MaterialRecordsID is same as MRecords.Id

        /**
        *****************************************************************************************
        *Wrapper
        *****************************************************************************************
        */

        //Test.StartTest();

        //materialWrapper obj = new materialWrapper();

        SalesMarketing.materialWrapper wrapper= new SalesMarketing.materialWrapper();
        //Test.StopTest();
    }
}

A: You were not calling SalesMarketing class methods from within your test class. Try this test class.
@isTest
private class SalesMarketingTest
{
    static testmethod void  SalesMarketing()
    {

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Account
        *****************************************************************************************
        */
        Account acct = new Account
              (Name='Test');
        insert acct;

        /**
        *****************************************************************************************
        *                     Querying RT Object for Contact object
        * Sales_Contact__c on Material Request has an Filter Criteria Applied on lookup
        *Filter = Contact Record Type = Schroders Employee
        *****************************************************************************************
        */

        RecordType rt = [select id,developername,Name from RecordType where SobjectType='Contact' and developername='Employee' Limit 1];

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Contact
        *                         Passing Contact RT Id From Query Above
        *****************************************************************************************
        */
        Contact cont = new Contact (
               AccountId= acct.id,
               MailingCountry ='United States',
               recordTypeId=rt.id,
               LastName ='Test Name');
        insert cont;

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Material Request
        *****************************************************************************************
        */

        sales_and_marketing__c MKTRequest = new sales_and_marketing__c(
               Name = 'Test Name',
               Sales_Contact__c = Cont.id,
                     //  Delivery_Date__c =   datatype "Date/Time"
               Delivery_Date__c = DateTime.newInstance(2011, 11, 18, 3, 3, 3),
                   //Event_Date__c = datatype "Date"
               Event_Date__c = Date.newInstance(2017,2,2)
                   );
        insert MKTRequest;

        /**
        *****************************************************************************************
        *                     This is test data for Creating an Material Record
        *****************************************************************************************
        */
        Material_Records__c MRecords= new Material_Records__c(
               Active__c = True,
               Item__c='United States',
               Product__c='Test Name');
        insert MRecords;

        /**
        *****************************************************************************************
        *                          This is test data for Materials_Junction
        *****************************************************************************************
        */
        Materials_Junction__c MJunction= new Materials_Junction__c(
               Material_Records__c =MRecords.id,
               sales_and_marketing__c= MKTRequest.id);
        insert MJunction;

        /**
        *****************************************************************************************
        *Checking that Materials_Junction__c has a record.
        *****************************************************************************************
        */
        MJunction = [
            Select
            Id,
            Name,
            Material_Records__c,
            sales_and_marketing__c
                From Materials_Junction__c
            WHERE sales_and_marketing__r.id =:MKTRequest.Id
            AND  Material_Records__r.id =:MRecords.id];
        /**
        *****************************************************************************************
        *System Assert Statements. Checking that Record has the correct value from insert statements
        *****************************************************************************************
        */
        system.assertEquals(MKTRequest.Id, MJunction.sales_and_marketing__c); //Check that Sales& MKT Id is same as MKTRequest.Id
        system.assertEquals(MRecords.Id, MJunction.Material_Records__c ); //Check that MaterialRecordsID is same as MRecords.Id

        /**
        *****************************************************************************************
        *Wrapper
        *****************************************************************************************
        */

        Test.StartTest();
        ApexPages.StandardController sc = new ApexPages.StandardController(MJunction);

        SalesMarketing controller = new SalesMarketing(sc);
        controller.searchString = 'Test Name';
        controller.getProductOrItemData();
        System.assertEquals(controller.save().getUrl(), '/'+MKTRequest.id);
        SalesMarketing.materialWrapper wrapper= new SalesMarketing.materialWrapper();
        Test.StopTest();
    }
}


text:
Q: Post to 2 (two) Wordpress websites at the same time I'm running two Wordpress websites on two different servers with two different domain names.
Sometimes I would like to be able to post on one website and have that post push to the other Wordpress website too so I don't have to copy-paste again.
I've tried searching but there's nothing concrete that came up. Is there a solution to this issue? If it's a paid plugin that works, that's even better. I would prefer a paid plugin over a hack since updating it for every Wordpress update is going to be a pain.
regards,


text:
Q: Font Awesome not displaying in Chrome on Android I've setup a WordPress website using Avada theme (6.0.3). I'm using Font Awesome in the site.
I now find that, using a Google Pixel 3 mobile phone with Android 9 operating system and Chrome 78, the Font Awesome icons do not display.
I've trawled the web and Stack Overflow looking for answers. There are a few documented problems (going back to 2018 and earlier) with previous versions of Chrome but no solutions that work for me.
Just wondering if (as at Nov. 2019) this is still a known problem with FA/Chrome? If so, are there any possible solutions?
Thanks,
Mekong

A: So it looks like it was a Cross-Origin Resource Sharing (CORS) problem.
Pasting the code below into .htaccess file solved the issue:
# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".
<IfModule mod_headers.c>
    <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
       Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>


text:
Q: D3 zoom callback Take this timeless example of D3 zoom. Shortened code below:
var svg = d3.select("svg")
  ...;

var zoom = d3.zoom()
    .scaleExtent([1, 40])
    .translateExtent([[-100, -100], [width + 90, height + 100]])
    .on("zoom", zoomed);

...

d3.select("button")
    .on("click", resetted);

svg.call(zoom);

function zoomed() {
  view.attr("transform", d3.event.transform);
  gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));
  gY.call(yAxis.scale(d3.event.transform.rescaleY(y)));
}

function resetted() {
  svg.transition()
      .duration(750)
      .call(zoom.transform, d3.zoomIdentity);
}

In the D3 Zoom library one specifies the zoom behavior, then applies the zoom to the canvas or SVG target. How/where could I send a callback as a param to zoomed() without redefining the zoom behavior?

A: Since you asked...

How/where could I send a callback as a param?

... your question is dangerously too broad. But here is a possibility (out of many):
Suppose this simple callback function:
function callback(x){
    console.log(x);
}

We can send it to the zoom function changing the listener. So, instead of:
.on("zoom", zoomed);

We can do:
.on("zoom", function(){
    zoomed(callback)
});

And, in the zoom function, setting the callback argument. For instance, let's log the d3.event.transform:
function zoomed(fn) {
    fn(d3.event.transform);
    //rest of the code...
}

Here is a demo bl.ocks: http://blockbuilder.org/GerardoFurtado/38c77c024ba4cc42c86221117fed4164


text:
Q: Can't add Kubernetes backend pool to outbound rule in Azure Load Balancer created automatically for AKS cluster I have created an AKS cluster (Kubernetes version 1.24.6) using Pulumi Azure Classic KubernetesCluster provider what resulted in creating AKS cluster with the following network profile:
{
    "networkProfile": {
        "dnsServiceIp": "10.0.0.10",
        "dockerBridgeCidr": "172.17.0.1/16",
        "ipFamilies": [
            "IPv4"
        ],
        "loadBalancerProfile": {
            "allocatedOutboundPorts": 0,
            "effectiveOutboundIPs": [{
                    "id": "/subscriptions/<subscription_id>/resourceGroups/<rg-id>/providers/Microsoft.Network/publicIPAddresses/<ip-id>",
                    "resourceGroup": "MC_rg-gw-aks-test00e1a208_aks-gw-konsolidator-test_westeurope"
                }
            ],
            "enableMultipleStandardLoadBalancers": null,
            "idleTimeoutInMinutes": 25,
            "managedOutboundIPs": {
                "count": 1,
                "countIpv6": null
            },
            "outboundIPs": null,
            "outboundIpPrefixes": null
        },
        "loadBalancerSku": "Standard",
        "natGatewayProfile": null,
        "networkMode": null,
        "networkPlugin": "azure",
        "networkPolicy": "calico",
        "outboundType": "loadBalancer",
        "podCidr": null,
        "podCidrs": null,
        "serviceCidr": "10.0.0.0/16",
        "serviceCidrs": [
            "10.0.0.0/16"
        ]
    }
}

my main goal was to have a static egress IP for the traffic outgoing from the cluster and enforce higher than default idleTimeoutInMinutes. Autogenerated Azure Load Balancer has Standard tier. I'm using ingress-nginx as ingress controller. However, after deploying the cluster and performing some troubleshooting I have noticed that:

*

*Egress IP is different than I would expect (tested by hitting curl -s checkip.dyndns.org from a pod inside the AKS cluster)  - it doesn't match any of the IPs specified in Frontend IP configuration (in particular it doesn't match the one mentioned in networkProfile.effectiveOutboundIPs). In general the outbound traffic is working, it isn't blocked, only long-running TCP traffic without keepalives is killed silently (without TCP RST) - I've checked it for requests lasting 5 minutes. I'm not using any other firewalls/network components outside of the AKS cluster apart from the Load Balancer.

*In Azure Load Balancer there is an outbound rule "aksOutboundRule" automatically created after creation of AKS cluster that uses one of the Frontend IP addresses defined in Frontend IP Configurations (that is the expected egress IP), but it has an empty (with 0 instances) backend pool assigned to it. Moreover, if I try to add "kubernetes" backend pool there manually, it is greyed out:
enter image description here
a. When creating a brand new outbound rule it is also not possible to configure "kubernetes" backend pool for it as it is also greyed out.
b. It is also not possible to add any IP configurations for the nodes from the kubernetes cluster to any other backend pool (new one or existing one), as the saving of the backend pool fails with bad request and the following details:

{
    "status": "Failed",
    "error": {
        "code": "MinimumApiVersionNotSpecifiedToSetTheProperty",
        "message": "Specified api-version 2020-12-01 does not meet the minimum required api-version 2022-03-01 to set this property skuOnPublicIPAddressConfiguration.",
        "details": []
    }
}

Does anyone have any clue what am I missing? What can be the cause of the issue I'm facing?
I've looked into MS documentation, especially into:

*

*https://learn.microsoft.com/en-us/azure/load-balancer/outbound-rules

*https://learn.microsoft.com/en-us/azure/aks/load-balancer-standard

*https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic
and I haven't found any explanation why kuberenetes backend pool may be greyed out or why mentioned errors can be thrown.


text:
Q: SqlConnection.ChangePassword new password does not work immediately I inherited a web application that has uses individual SQL account for authentication.  I need to update the login procedure to use a different type of hash.
Pseudo code
if (login(newhash(password)) == 0) // login using new hash function doesn't work
{
    if (login(oldhash(password)) == 1) // login with old hash works
    {
        SqlConnection.ChangePassword(connstr);
        login(newhash(password));
    }
}

The problem is the second login(newhash(password) would not immediately work.  If I put a System.Threading.Thread.Sleep(5000) in between the ChangePassword and the login then it would work.  SqlConnection is closed properly when doing the login()
I also tried using sp_password instead, but it still won't authenticate immediately with the new password.  Is there any way to eliminate this "password change lag"?
EDIT:
I added SqlConnection.ClearPool(conn) and the problem persist. SQL Profiler showed the following:

*

*Audit Login Failed

*Audit Login

*SQL:BatchStarting

*SQLBatchCompleted

*Audit Login Change Password Event

*Audit Login

*Audit Login Failed

So everything is expected from 1-6, however I don't know where does #7 come from.

A: I believe it's a connection in the connection pool that is getting in your way, How Can I Prevent Recurring Automatic Connections to Oracle Database? . Try clearing the pool before trying to reauthenticate, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearpool(v=vs.110).aspx .


text:
Q: +1 при нанажатии на кнопку Есть кнопка и лейбл счетчика, нужно, чтобы при нажатии на кнопку счетчик прибавлял 1 и отображал новое значение. Не могу понять где надо вводить переменную, пытался и внутри лямбды, и отдельным классом, и за setOnAction, но  консоль выдает "local variables referenced from a lambda expression must be final or effectively final".
myBtn.setOnAction(e -> {
  //логика
});

A: Если мы используем переменную внутри анонимного класса то она должна быть final. Это справедливо и для лямбд, потому что последние, по сути, тоже являются таковыми.
Есть несколько способов обойти данное ограничение:

*

*объявить final массив размером 1 с заданным типом

*использовать mutable объект, в вашем случае объявить переменную типа AtomicInteger
Переменная должна быть полем у класса.


text:
Q: Better way to convert a list of Years expressed by a int datatype to DatetimeIndex I have the following list of integers containing Years and I want to convert to DatetimeIndex.
date_1=[2000,2001,2002,2003]
#converting to string
date_1_str=[str(i) for i in date_1]
#converting to Datetime
test=pd.to_datetime(date_1_str,format="%Y")
print(test)

Output:
DatetimeIndex(['2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01'], dtype='datetime64[ns]', freq=None)

Why I can't do something more direct like:
pd.to_datetime(date_1, unit="Y")

Why I have to convert first to a string datatype?
There is any better option available?

A: I think reason is unit parameter in to_datetime working different, working with unix times:

unit , default 'ns'

The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit='ms' and origin='unix' (the default), this would calculate the number of milliseconds to the unix epoch start.

But if values are years in  integers it is only different format of datetime, so for me this is more logic using here.


text:
Q: AWS CloudWatch Monitoring NetworkIn - no data points I'm trying to see if an EC2 instance on AWS is receiving traffic from a streaming service (if no traffic is received i plan to close the instance).
To do this i measure the NetworkIn with a CloudWatchClient (with phpSDK). The problem is that when i put the 'Period' to 60 sec i receive no data points. The same code works fine if i put the period to 300(and adjust start and end time to a 300 sec interval) Any idea ?
 $time_const     =   60;// in sec
 $end_time       =   time();
 $start_time     =   $end_time-$time_const;

 $result = $cloudwatch_client->getMetricStatistics([
    'Dimensions' => [
        [
            'Name' => 'InstanceId', // REQUIRED
            'Value' => $InstanceId, // REQUIRED
        ],
    ],
    'EndTime'       => $end_time, // REQUIRED
    'StartTime'     => $start_time, // REQUIRED
    'MetricName'    => 'NetworkIn', // REQUIRED
    'Namespace'     => 'AWS/EC2', // REQUIRED
    'Period'        => $time_const, // REQUIRED
    'Unit'          => 'Bytes',
    'Statistics'    => array('Sum'),
    ]);

Thanks

A: By default, EC2 CloudWatch metrics are only available on 5-minute (300 second) intervals. To monitor this at 60 second intervals, you need to enable EC2 detailed monitoring for the given instance.  From the documentation:

Data is available in 1-minute periods for an additional cost. To get this level of data, you must specifically enable it for the instance. For the instances where you've enabled detailed monitoring, you can also get aggregated data across groups of similar instances.

You can enable this from this AWS console, or via the CLI/SDK.  CLI example, from the linked documetation above:
aws ec2 monitor-instances --instance-ids i-1234567890abcdef0


text:
Q: Reading Multiple Files for Text Mining in R Using TM Package? I am trying to read few csv files for some text mining assignment.
I have used this command to check the # of files in the working directory:
length(dir(path="D:/Shivi/R Project", all.files = TRUE))

This results to more than 220 approx.
I just need 3 files from these to use for the text mining purpose however if i use:
docs<- Corpus(DirSource(directory = "D:/Shivi/R Project"))

this reads all the 220+ files
Please suggest how to achieve this feat.


text:
Q: C#, HtmlUnit JavaScript Support I am trying to read a test page using NHtmlUnit.WebClient. The page is keep asking to enable JavaScript. Am I missing something?
My Code:
var client = new NHtmlUnit.WebClient(BrowserVersion.FIREFOX_17);
client.Options.JavaScriptEnabled = true;
client.WaitForBackgroundJavaScript(10000);

client.Options.ThrowExceptionOnFailingStatusCode = false;
client.AjaxController = new NicelyResynchronizingAjaxController();
var page = (HtmlPage)client.GetPage(googleCaptchaUrl);
var pageStr = page.AsXml().ToString();


text:
Q: Local images: Editing gatsby schema to convert a local path to a file I'm using gatsby and I need to display multiple images for a given entity. Image paths are stored on a MySQL table and I'm fetching them just fine.
My query looks like this:
{
  mysqlSet(entity_id: {eq: "10270"}) {
    name
    images {
      url
    }
  }
}

Which gives me a result like this:
{
  "data": {
    "mysqlSet": {
      "name": "My Entity Name",
      "images": [
        {
          "url": "./images/10270-0.png"
        },
        {
          "url": "./images/10270-1.png"
        },
        {
          "url": "./images/10270-2.png"
        }
      ]
    }
  }
}

So, the question is: How do I modify my schema to reflect that those fields are actually images? I mean, that's the path I'm following but I can't figure out how to do it.
Basically, I need to grab the images as files to use them with gatsby's built-in Img component.

A: You can query using allFile and filter with the desired extension like:
 {
      allFile(filter: {ext: {eq: ".png"}}) {
        edges {
          node {
            absolutePath
          }
        }
      }
    }


text:
Q: How to make Motherboard Beep through C++ Code? How can I make the motherboard internal speaker produce sounds, for example using the Beep command but directed towards the motherboards speakers.

OS = Windows 7 x64

I currently know how to provide beeps to the default sound device, including tone and millisecond's but this does not answer my question since I cant force any of these sounds towards the motherboard internal speakers.
Beep(523, 500);

My question is mainly based around an alternative to Beep which would play through the motherboards speakers rather than the computer audio card. Or a way to direct the Beep command or incoming audio frequencies towards the motherboards speakers.

A: The question was later specified to refer to Win32 programming environment, this question describes a Linux solution.
You can use the KIOCSOUND ioctl to generate a tone, as such
ioctl(fd,KIOCSOUND,(int) tone)

The Linux Programming Interface is a fabulous book that describes using IOCTLs in detail, but there are public resources that describe the IOCTL such as the perennially classic TLDP.

A: In Windows 7, Beep was rewritten to pass the beep to the default sound device for the session. This is normally the sound card, except when run under Terminal Services, in which case the beep is rendered on the client. source
There is apparently one possible modification of system descibed here.


text:
Q: Is there any option in wget to get the referers or parent of a link that are crawled by wget Is there any to get or find the referrers of a link that were crawled by wget?
Suppose that some link returns a 400 error. wget only shows the url on which the 400 error occurrs, not the referrer of error url. If possible please provide any utility similar to wget in linux or wget option for doing this.

A: The referrer is passed as part of the request header. Wget prints it if you turn on debug with -d. Then use grep to find the "referer" (note that debug output is probably written to stderr).


text:
Q: QtWebKit CSS Path Having an QWebElement, how to generate the unique CSS path for that element?
The argument for:
QWebElement::findFirst(const QString & selectorQuery)

(something like "Copy CSS path" in Chrome or "Copy Unique Selector" in Firefox)


text:
Q: Is there anyway to import Mass Effect 3 character to Mass Effect 1? I want to play Mass Effect 1 using the character I have made in Mass Effect 3. Anyone knows how to? Maybe like by copying files or something?

A: No.
Each of the Mass Effect games made changes to the character files which are irreversible without hacking/editing the files yourself, or finding tools to do so. However I'm unable to find any such tools.

A: As others have said, you can't import an ME3 character to ME1.
If you're primarily concerned with making the two characters look the same, take note of the letter and number string in the corner of the character design the screen
eg. 141.KN8.FTL.922.L9K.HFW.CNJ.3HB.915.1N8.E36.3
It represents the facial characteristics of your character.
If you write it down, you can use it to manually recreate the character in ME1.
(This is how I managed to maintain my ME2 Shepard in ME3 before they fixed the importer bug.)


text:
Q: Speeding calculations With some 20K observations, the following code takes some 7.5 sec to run
'Remember time when macro starts
StartTime = Timer
For i = 2 To UBound(avTransposed, 2)
    For J = 1 To UBound(avTransposed, 1)
        k = IIf(J = 1, k + 1, k)
        '                    If J = 1 Then k = k + 1
        ReDim Preserve TrueUsedRangeArray(1 To Dim2, 1 To k)
        TrueUsedRangeArray(J, k) = avTransposed(J, i)
    Next
Next
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)

Without the
k = IIf(J = 1, k + 1, k) line (or  If J = 1 Then k = k + 1),  it takes less than one sec!!
Any idea?

A: The ReDim Preserve is probably killing performance. Every time it is used, it creates a new array and copies the existing array in.
You can work out up-front the size of TrueUsedRangeArray, something like the following
ReDim TrueUsedRangeArray(1 To Ubound(avTransposed, 2), 1 To Ubound(avTransposed, 1))

A: Too many things in your inner loop which do not need to be there:
For i = 2 To UBound(avTransposed, 2)
    k = k + 1
    ReDim Preserve TrueUsedRangeArray(1 To Dim2, 1 To k)
    For J = 1 To UBound(avTransposed, 1)
        TrueUsedRangeArray(J, k) = avTransposed(J, i)
    Next
Next

As Patrick notes though, you do not need the redim preserve in the loop, since you already know the final size of TrueUsedRangeArray from the dimensions of avTransposed


text:
Q: Change last character's color of PS1v promt based on exit status of previous command I've customized my .bashrc settings similar to default's PS1 settings from Clear Linux.
My file contents these lines:
EXIT="$?"
BLUE="\[\e[38;5;39m\]"
RED="\[\e[31m\]"
ORANGE="\[\e[38;5;208m\]"
WHITE="\[\e[0m\]"
    if [ "$EXIT" = "0" ]; then
          endchar="${BLUE}\\$""$WHITE"
    else
          endchar="${RED}\\$""$WHITE"
    fi

    if [ "$UID" = "0" ]; then
          username="${RED}\u${WHITE}"
    else
          username="${BLUE}\u${WHITE}"
    fi

host="${ORANGE}\H${WHITE}"
dir="${BLUE}\w${WHITE}"
PS1="${username}@${host} ${dir} ${endchar} "

The file is sourced with no errors on login or opening new terminal windows, with one exception:
Last character in resulting PS1 string remains forever blue, though i type mistakes on terminal.
Expected behaviour of my settings is that prompt's last character $ turns red when exit status of previous command is greater than 0.
Any suggestions?
Thanks in advance

A: Add this color code to the end
DEF='\e[0m' #Default color and effects
PS1="${username}@${host} ${dir} ${endchar}$DEF "

And take a look here

A: Just give you another example:
function _ps1_command()
{
    local rcode=$?

    if (( rcode )); then
        g_prompt_color=$'\e[1;31m'
    else
        g_prompt_color=$'\e[0m'
    fi
}
PROMPT_COMMAND=_ps1_command
PS1='[\w] \[$g_prompt_color\]\$\[\e[0m\] '


text:
Q: Why does std::istream::gcount return one char more than expected I'm just wondering why this standard function is returning a char count of 9 for the sample code at cplusplus.com
// cin.gcount example
#include <iostream>     // std::cin, std::cout

int main () {
  char str[20];

  std::cout << "Please, enter a word: ";
  std::cin.getline(str,20);
  std::cout << std::cin.gcount() << " characters read: " << str << '\n';

  return 0;
}

Please, enter a word: simplify
9 characters read: simplify
Why is this returned as 9 characters?

A: Because of the enter key.  When you press enter, a newline character ('\n') is entered into the stream.  getline reads up to that newline, stores the text in the array, and then reads and discards the newline.  Thus, when you read simplify, you actually read simplify\n which is 9 characters.

A: cplusplus.com is generally considered by many people to be a poor site for C++ documentation.  You really should use cppreference.com instead.
For instance, cppreference's istream::getline() documentation states the following:

Behaves as UnformattedInputFunction. After constructing and checking the sentry object, extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):

*

*end of file condition occurs in the input sequence (in which case setstate(eofbit) is executed)

*the next available character c is the delimiter, as determined by Traits::eq(c, delim). The delimiter is extracted (unlike basic_istream::get()) and counted towards gcount(), but is not stored.

*count-1 characters have been extracted (in which case setstate(failbit) is executed).
If the function extracts no characters (e.g. if count < 1), setstate(failbit) is executed.

cplusplus's istream::getline() documentation states the following instead:

The delimiting character is the newline character ('\n') for the first form, and delim for the second: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s.
...
The number of characters successfully read and stored by this function can be accessed by calling member gcount.

Which is a little misleading, as it implies that getline() only counts characters that are stored in the user's buffer, but the delimiter is not stored in the buffer and yet it still counts towards gcount().


text:
Q: Need to reset android AOSP code to Lollipop I have downloaded the current master of Android AOSP which is Android 6.0 source code.
Is there a way available using repo to set the master to Android 5.1 so that all git repositories are set accordingly?
Note: I wish to do this without downloading again.

A: Quoting from source.android.com:

To check out a branch other than "master", specify it with -b. For a
  list of branches, see Source Code Tags and Builds.
$ repo init -u https://android.googlesource.com/platform/manifest -b android-4.0.1_r1

Edit

Note: I wish to do this without downloading again.

You can try with:
repo init -b <manifest-branch>
repo sync -j8

Edit 2

I want to know if there is way to do it without downloading. The sync
  would download from google servers.

The documentation is really clear about the sync command:

Downloads new changes and updates the working files in your local
  environment. If you run repo sync without any arguments, it will
  synchronize the files for all the projects.
When you run repo sync, this is what happens:

*

*If the project has never been synchronized, then repo sync is equivalent to git clone. All branches in the remote repository are
  copied to the local project directory.

*If the project has already been synchronized once, then repo sync is equivalent to:
git remote update
git rebase origin/<BRANCH>

where  is the currently checked-out branch in the local
  project directory. If the local branch is not tracking a branch in the
  remote repository, then no synchronization will occur for the project.

*If the git rebase operation results in merge conflicts, you will need to use the normal Git commands (for example, git rebase
  --continue) to resolve the conflicts.

Since you already synchronized the project once the sync command is equivalent to a rebase.


text:
Q: SSL certificate on CNAME We have a SaaS web app. We have a wildcard SSL cert on the main domain: *.webapp.com
Customers can add a custom domain to their account, so instead of client.webapp.com they can setup a CNAME to have: clientdomain.com
We have some clients that want to add a SSL cert to their custom domains. Webapp already runs https://client.webapp.com but they want https://clientdomain.com
We are using apache (via Plesk) on the main server.
Is it possible to achieve this?


text:
Q: html table cell width 0 not working? for some reason I have to use a table which contains two cells in each row I want to animate the width of the first cell by setting its overflow property to hidden and its width to 0 but when I set the width to 0 the actual rendered width is 3px
here is my markup

  .news-element {
  width: auto;
  position: relative;
  display: inline-block;
  flex: 0 0 auto;
  .news-element-table {
    border-collapse: collapse;
    display: table;
  }
  .news-element-img {
    width: 17vw;
    height: 300px;
    display: table-cell;
    position: relative;
    overflow: hidden;
    .news-element-img-wrapper {
      position: absolute;
      height: 100%;
      width: 100%;
      top: 0;
      left: 0;
    }
    img {
      position: absolute;
      height: 100%;
      width: auto;
      min-width: 100%;
      top: 0;
      left: 50%;
      bottom: 0;
      right: 0;
      transform: translateX(-50%);
      margin: auto;
    }
    // h 336
    // w 236
  }
  .news-element-description {
    width: 0;
    // w 414
    position: relative;
    overflow: hidden;
    height: 100%;
    display: table-cell;
    .news-element-description-wrapper {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      text-align: center;
      padding: 10px;
    }
  }
  .news-element-title {
    width: 100%;
    padding-top: 10px;
    padding-bottom: 3px;
    background: #2E3132;
    color: #fff;
  }

              blah blah blah

            <img src="<?= getFileLink(" /assests/imgs/Media05.jpg "); ?>" />

foo

I'm using the table method so I can set the height of the first cell according to its sibling  .

A: I used this CSS to completely hide my cells:
.hide-col {
  overflow: hidden;
  width: 0!important;
  max-width: 0!important;
  padding: 0!important;
  border-width: 0!important;
  font-size: 0!important;
}

A: I just had a similar problem with table row heights and column widths that refused to become 0. My solution was to set width and max-width or height and max-height to s.th. slightly above 0, like so
width:0.01px; max-width:0.01px;
height:0.01px; max-height:0.01px;

perhaps combined with
visibility:hidden;

No idea, why setting them to 0 does not work...


text:
Q: Login MVVM / Labels i have a question regarding to Binding. I have a Login that I now decided to transfer to MVVM until now i had labels with content "wrong password" and such in code behind and i was setting their visibility. Btw I do have RESX file and I am binding my labels, just not sure how to approach this.
bool isPreparedToBeSubmitted = true;
            if (string.IsNullOrEmpty(UserName))
            {
                isPreparedToBeSubmitted = false;
                emailValLabel.IsVisible = true;

            }

            if (string.IsNullOrEmpty(Password))
            {
                isPreparedToBeSubmitted = false;
                 passwordEntryValLabel.IsVisible = true;
            }

But I think this can be done much nicer, but I am not sure how. Do i get the visibility bool in Model and then set binding to the label in View?

A: Since you want to use MVVM. It would be better to bind the text of entry to ViewModel . Don't forget to set the binding mode as OneWayToSource .
You could check the following demo . The page contains two entries . The submit button will appear when user both input the user name and password .
in xaml
<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">

    <Entry Placeholder="input username"  Text="{Binding UserName,Mode=OneWayToSource}" HeightRequest="40" WidthRequest="200" />
    <Entry Placeholder="input password"  Text="{Binding Password,Mode=OneWayToSource}" HeightRequest="40" WidthRequest="200" />

    <Button Text="Submit" IsVisible="{Binding IsVisible}"  Command="{Binding SubmitCommand}"  />

</StackLayout>

in ViewModel
public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ICommand SubmitCommand { get; set; }

    //IsVisible

    bool isVisible;
    public bool IsVisible
    {

        get
        {
            return isVisible;
        }
        set
        {
            if (isVisible != value)
            {
                isVisible = value;

                NotifyPropertyChanged("IsVisible");
            }
        }

    }
    string userName;
    public string UserName
    {

        get
        {
            return userName;
        }
        set
        {
            if (userName != value)
            {
                userName = value;
                IsSubmitVisible();
                NotifyPropertyChanged("UserName");
            }
        }

    }

    string password;
    public string Password
    {

        get
        {
            return password;
        }
        set
        {
            if (password != value)
            {
                password = value;
                IsSubmitVisible();
                NotifyPropertyChanged("Password");
            }
        }

    }

    void IsSubmitVisible()
    {
        if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
        {
            IsVisible = true;
        }
        else
        {
            IsVisible = false;
        }
    }

    public MyViewModel()
    {
        SubmitCommand = new Command(()=> {

            //...

        });
    }

}


text:
Q: Shift+home / shift+end not working on linux Like I said in the title: shift+home (and shift+end) key combinations don't result in selecting line from current cursor position to beginning (or end) of the line. Cursor just jumps to the beginning (or end) of the line without selecting anything. Is there any way to achieve the behavior with selection?
PS. I have configured Linux so that shift+home selecting is enabled in other applications.


text:
Q: Using Typescript/Angular to hide HTML elements with RXJS There are divs that display recipes (from a  property on the component in an object array - 'Recipes', 'Recipes' includes a property 'Recipes.diet' that is a string of diets), I have a filterf component that sends subscriptions of diets (currently 'Vegetarian,'GlutenFree','Vegan'). I want to hide recipes that include the diet keyword e.g. an observable of 'Vegetarian' hides all recipes that don't have the 'Vegetarian' keyword included in their 'diet' property.
Currently I'm not getting difference.
I've tried using angular ngClass, ngStyle to dynamically filter the class lists to includes '.hide' (which sets the display to none).
When I statically set the display to 'none' it's successful, I'm currently trying a method that manipulates the Dom directly through HTML Element objects but that isn't working either.
I've checked that the keywords are coming through, and they're matching up successfully with the correct divs. I've tried just setting the style attribute through typescript and adding a class type (this is the method I'm trying below).
I know this will be a very simple issue but I've run out of ways to check, I've searched online and StackOverflow & tried about every variations of DOM/Angular changing I can think of.
HTML:
 <div *ngFor="let recipe of recipes" id="{{recipe.title}}-card" (click)="recipeWasChosen(recipe)">
    <app-recipe-title class="recipe-card" [recipe]="recipe">
    </app-recipe-title>
</div>

Typescript:
this.recipeService.recipeRestrictions.subscribe((restrictions: string[]) => {
      this.recipes.forEach((recipe: Recipe) => {
        let hide = false;
        for (const restriction of restrictions) {
          if (!recipe.diet.includes(restriction)) {
            hide = true;
          }
        }
        if (hide) {
          this.hideCardWithHTMLElement(recipe.title);
        } else this.hideCardWithHTMLElement(recipe.title);
      });
    });

  hideCardWithHTMLElement(title: string) {
    let card = document.getElementById(`${title}card`);
    if (card.classList.contains('hidden')) {
      card.className = '';
    } else card.className = 'hidden';
  }

CSS:
.hidden {
  display: none;
}

A: If you just want to filter your list by type of restriction, You don't need to hide the elements, but you can filter out the ones that contain restrictions in general .you can do something like this
this.recipes$ = this.recipeService.recipeRestrictions
.pipe(
   map((restrictions: string[]) => {
      return this.recipes.filter((recipe) => restrictions.every((restriction) => !recipe.diet.includes(restriction)))
   })
)

and in template
<div *ngFor="let recipe of recipes$ | async">
...
</div>

A: Have you tried using a *ngIf to dynamically hide a recipe based on its hide status?
Since you can't add a *ngFor and *ngIf on the same container you can use a ng-container like this:
<div *ngFor="let recipe of recipes" id="{{recipe.title}}-card" (click)="recipeWasChosen(recipe)">
    <ng-container *ngIf="isFiltered(receipe)">
        <app-recipe-title class="recipe-card" [recipe]="recipe"></app-recipe-title>
    </ng-container>
</div>

the isFiltered(receipe) method is your filter which returns either true or false depending on the recipe is filtered or not.
Also make sure to avoid manipulating the DOM over java script (better use ngIf directives) since this can lead to problems.


text:
Q: Error in C simple program This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>

int main(void) {
    char sen, ben;

    printf("Type in a character: ");

    scanf("%c", &sen);
    printf("The key just accepted is %d", sen);

    printf("\nType in another character: ");
    scanf("%c", &ben);
    printf("The key just accepted is %d", ben);
}

A: Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>

int main(void) {
    char sen, ben;
    printf("Type in a character: ");
    sen = getchar();
    printf("The key just accepted is %d", sen);
    printf("\nType in another character: ");
    getchar();
    ben = getchar();
    printf("The key just accepted is %d", ben);
}

Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.

A: Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.

A: When you pressed your key and then hit enter, you typed in two keys.  The first was the desired key ,a for example, and the second was the key <enter> typically written as \n.  So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture.  This is done by accepting more input after the character up until you see a newline character \n.  Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
  scanf("%c", &flush);
}

// now read my desired input
scanf("%c", &ben);

A: that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.


text:
Q: Detecting whether cookies are enabled through Java Is it possible in Java (SE, not J2EE) to detect whether cookies are enabled in the default browser?
This isn't a client/server application.  It's simply a desktop application that happens to interact with the default browser.

A: I am not sure what you mean by "default browser" but the fundamental thing to understand here is that the code, be it written in Java, C++, Python, you name it, that handles a HTTP request should set a cookie using Set-Cookie and look for what was set being available in Cookie header in the subsequent requests from the browser. If cookies are turned off in the client, then there won't be a Cookie header in the subsequent requests. A simple redirect to the initial request can also be used to generate a "subsequent" request.

A: There are many browsers out there, and each one uses a different mechanism for storing the user's preferences ... including the preferences that determine whether the user has disabled cookies.
You could conceivably implement a Java application that knew how to unpick the settings information for some popular browsers.
But this would contain a lot of browser specific and operating system specific code.  And in the case of Windows, it would entail grovelling around in the registry; e.g. using some third party library.  And of course, this would all be rather fragile because:

*

*the next version/release of the user's browser could use a different settings representation,

*the user could use some new browser you've never heard of,

*different Linux distros, etc could be configured to use different default locations for settings files, and/or the preference file that says what the user's default browser is, and

*the user could override the default locations anyway, in ways that a generic desktop application could not fathom.
EDIT - on the other hand, if your desktop application (acting in the server role of the HTTP protocol) simply needs to figure out if the browser it is currently talking to will allow it to set cookies, the simple solution is to try to do it and see if it works.
Finally, you need to bear in mind that the user may not be using the default browser for whatever it is he is trying to do.  I frequently have multiple browsers installed on a machine, and may use the non-default one for certain things.

A: Assuming your application is acting as a localhost server to the browser, which is what your question seems to say...
One way is to redirect the request to a special URL with a special cookie, say "CookieCheck" set to some known special value and the original URL encoded as query data.  When a request is received for the special URL, if "CookieCheck" is received then the browser accepted the cookie - you can then redirect back to the original URL but with the cookie set to a real value.
This can be difficult to do for POST requests unless you can store the post data server side or encode it into query data.  It also transforms the request from POST to GET, which can be problematic.


text:
Q: APS missing entitlements Just received an email from Apple stating that my app is (copied below)
Ok no problem. I deleted my old provisioning profile, made sure the new one has an aps key
**<key>aps-environment</key>
<string>production</string>**

and resubmitted again.
And of course I received the same message.
How should I proceed? Any ideas?

We have discovered one or more issues with your recent delivery for
  "iPicture Frames LT". Your delivery was successful, but you may wish
  to correct the following issues in your next delivery: Missing Push
  Notification Entitlement - Your app appears to include API used to
  register with the Apple Push Notification service, but the app
  signature's entitlements do not include the "aps-environment"
  entitlement. If your app uses the Apple Push Notification service,
  make sure your App ID is enabled for Push Notification in the
  Provisioning Portal, and resubmit after signing your app with a
  Distribution provisioning profile that includes the "aps-environment"
  entitlement. See "Provisioning and Development" in the Local and Push
  Notification Programming Guide for more information. If your app does
  not use the Apple Push Notification service, no action is required.
  You may remove the API from future submissions to stop this warning.
  If you use a third-party framework, you may need to contact the
  developer for information on removing the API. If you would like to
  update your binary for this app, you can reject this binary from the
  Binary Details page in iTunes Connect. Note that rejecting your binary
  will remove your app from the review queue and the review process will
  start over from the beginning when you resubmit your binary.

A: After MULTIPLE trials of deleting files, cleaning project and restarting Xcode I managed to submit the app. Uff. finally.


text:
Q: Index of a normal subgroup If G is finite group, then every subgroup of G is finite. If we take normal subgroup H of G and look at it's index in G. That index has to be finite, if I am thinking right?

A: Yes, because if $G$ is finite and $H$ is its subgroup, the index of $H$ is simply $$\frac{|G|}{|H|}$$

A: Yes, and it is also true if $H$ is not normal.
If $H$ is a subgroup of $G$ then its index is defined as the cardinality of the set $P=\{aH\mid a\in G\}$.
Observe that $P$ is a partition of $G$ and consequently has a cardinality that will not exceed the cardinality of $G$.

A: When $H$ is a subgroup of $G$, you can define two equivalence relations on $G$, that I usually denote with $\sim_H$ and $_H{\sim}$:
\begin{align}
x\sim_H y &\quad\text{if and only if}\quad xy^{-1}\in H \\
x\mathrel{_H{\sim}} y &\quad\text{if and only if}\quad x^{-1}y\in H
\end{align}
Proving that these are equivalence relations is a good exercise in applying subgroup properties.
The main property of these equivalence relations are, denoting by $[x]_{\sim}$ the equivalence class of $x$ under the equivalence relation $\sim$,

*

*$[1]_{\sim_H}=H$

*for every $x\in G$, the map $h\mapsto hx$ is a bijection $[1]_{\sim_H}\to[x]_{\sim_H}$; in particular, $[x]_{\sim_H}=Hx$

*$[1]_{_H{\sim}}=H$

*for every $x\in G$, the map $h\mapsto xh$ is a bijection $[1]_{_H{\sim}}\to[x]_{_H{\sim}}$; in particular, $[x]_{_H{\sim}}=xH$

In particular, if $G$ is finite, all equivalence classes under $\sim_H$ have the same cardinality as $H$, so the number of equivalence classes is $|G|/|H|$. This number is the index of $H$ in $G$.
Note that this is a proof of Lagrange's theorem that $|H|$ divides $|G|$.
In the same fashion, all equivalence classes under $_H{\sim}$ have the same cardinality as $H$, so it's immaterial whether you use one or the other equivalence relation for defining the index.
The subgroup $H$ is normal in $G$ if and only if $\sim_H$ is the same relation as $_H{\sim}$, because this reduces to the statement "$xH=Hx$, for all $x\in G$".


text:
Q: Mongoose validators not updated I'm using mongoose and the npm package mongoose-unique-validator for validation.
It worked just fine when plugged into my schema, but I changed the validation from an attribute to another one. And now I am still getting the unique mongo error for that old validation (MongoError 11000) for the email... although I moved it to the username, as if the validators from before was not removed and not properly updated.
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;

let userSchema = new Schema({
    username:{
        type: String,
        required: true,
        unique: true,
        uniqueCaseInsensitive: true
    },
    email: {
        type: String,
        required: true
    }
}
userSchema.plugin(uniqueValidator, {message : 'username must be unique'});

module.exports.User = mongoose.model('User', userSchema);

Is there a way to update the validators ? I haven't found anything yet

A: Please drop your collections completely, and run your project again. After that every things will be OK, because unique index created in your mongodb based on your email and still exists...
for delete index you can use a IDE for mongodb like robo 3t or ...
with command you can drop a index
db.getCollection('CollocationName').dropIndex( "indexName_1" )

for you is :
db.getCollection('users').dropIndex( "email_1" )

if index is created by mongoose you should use indexName with _1


text:
Q: Logging full stack trace with Monolog I use Monolog as a stand-alone library in my application and recently I ran into an issue. Let's say, at some point in my application I catch an exception and I want to log it:
$mylogger->error('Exception caught', array('exception' => $exception));

This works perfectly except one tiny thing - it doesn't log whole stack trace. Is it possible to log exception's full stack trace using monolog build-in formatters?

A: Actually since version 1.12.0 it is possible to include stacktrace at your log file: there is new method of LineFormatter called includeStacktraces.
To use this, you need to overwrite default behaviour of monolog formatter:
config.yml
monolog:
    handlers:
        main:
            formatter: your.monolog.service.id
            (rest of config is as usual)

services.yml
services:
    your.monolog.service.id:
        class: Monolog\Formatter\LineFormatter
        calls:
            - [includeStacktraces]

Check github for more info:
Pull request

A: This is how I do it, yes years later...
$mylogger->error('Exception caught', $exception->getTrace());
since getTrace() returns an array, which is what Monolog wants.

A: I have a very simple solution!!!
$mylogger->error((string) $exception);

A: You can simply use the config file (Symfony Bundle) with the "include_stacktraces" parameter:
monolog:
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: info
            channels: ["!event"]
            max_files: 10
            include_stacktraces: true <--- SET TO TRUE

@see this commit
@see the full schema (configuration)

A: Adding to Tomasz Madeyski's answer, this is how you can use it via code only:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\ErrorHandler;
use Monolog\Formatter\LineFormatter;

$formatter = new LineFormatter(LineFormatter::SIMPLE_FORMAT, LineFormatter::SIMPLE_DATE);
$formatter->includeStacktraces(true); // <--

$stream = new StreamHandler('error.log');
$stream->setFormatter($formatter);

$logger = new Logger('logger');
$logger->pushHandler($stream);

A: No, You cannot log the stack trace using the built-in formatters.  See my question here.
If you take a look at LineFormatter.php you see that the normalizeException method is responsible for grabbing the exception data. So, I had to create a new formatter that extended LineFormatter.  Here's the code:
<?php

namespace Monolog\Formatter;

use Exception;

class ExceptionLineFormatter extends LineFormatter
{
    protected function normalizeException(Exception $e)
    {
        return 'Message: ' . $e->getMessage() .
                'Stack Trace: '. $e->getTraceAsString();
    }
}

And I initialized my logger like so:
$logFile = 'MyLogFile.txt';
$handler = new StreamHandler($logFile);
$handler->setFormatter(new ExceptionLineFormatter);
$log = new Logger('MyLogger');
$handler = self::getStreamHander();
$log->pushHandler($handler);

This will will print out your stack trace.

A: The Upvoted answer works, but you are not forced to create a custom service for that.
The monolog.formatter.line already exists on Symfony 3.4 full stack. You can simply add a method call on it thanks to the CompilerPassInterface:
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use use Symfony\Component\HttpKernel\Kernel;

class AppKernel extends Kernel implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container->getDefinition('monolog.formatter.line')->addMethodCall('includeStacktraces');
    }
}

The monolog handler does not seems to receive the service by default, so you still have to specify it. Example:
monolog:
    handlers:
        main:
            type: rotating_file
            max_files: 12
            date_format: 'Y-m'
            path: '%kernel.logs_dir%/%kernel.environment%.log'
            level: debug
            formatter: monolog.formatter.line

A: If you want to log stacktrace only when Exception is thrown, you can do this, in the AppServiceProvider:
public function register()
{
     $logger = Log::getMonolog();
     $logger->pushProcessor(function ($record) {
        if (isset($record['context']['exception']))
        {
            $record['extra']['stacktrace'] = $record['context']['exception']->getTraceAsString();
        }

        return $record;
    });
}

This will add the stacktrace to extra column, which then can be used per LineFormatter

A: getTraceAsString will give you the Stack Trace array as a 'End of Line' delimited string.  Explode on PHP_EOL and then foreach through the array logging each element.  Hope this helps.
<?php
function test() {
    throw new Exception;
}

try {
    test();
} catch(Exception $e) {
    $array = explode(PHP_EOL, $e->getTraceAsString());
    foreach($array as $line){
        $mylogger->error($line);
}

Should produce something like this:
#0 index.php(14): test()
#1 {main}


text:
Q: Using Function Library to Call browser When I call on my action page to open the browser, it does open it and then it closes it. And then opens it again and then closes it repeatedly. I checked my function library but cannot seem to figure out why it does it. I am using Keyword driven framework.
I tried re writing the code and also commenting out the closing browser part but even then it closes it and opens repeatedly.
Here is my function library  to open the browser  and as well as another procedure to close browser
'Open application'
   Function OpenApp(AppName)
   If Browser("title:=.*").Exist Then
   Browser("title:=.*").CloseAllTabs
   End If

   systemutil.Run AppName
   wait(5)

  End Function

'Close application'
  Function CloseApp()
  Browser("title:=.*").CloseAllTabs
  wait(3)
  End Function

And Here is how I am calling it the browser in action, from my excel sheet.
 If ActionKey = "OpenApp" Then
 Call OpenApp(Obj_value)
 End If

I want the code to open the browser and keep it opened so I can perform other actions.


text:
Q: How can I implement previous/next buttons in an image gallery? I have a GridView populate from a database. When i click an image in the GridView, it opens in a new image called imgFull. This image may explain more:

I want to put next and previous button to get in my div the next image from database.
I want to develop it in jQuery or JavaScript. This is a sample of my code:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
  Font-Names="Arial">
 <Columns>
  <asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="FileName" HeaderText="Image Name" />
<asp:TemplateField HeaderText="Preview Image">
    <ItemTemplate>
        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# "images/"     +Eval("FilePath")  %>' Width="100px" Height="100px" Style="cursor: pointer" OnClientClick = "return LoadDiv(this.src);"/>

  </ItemTemplate>
</asp:TemplateField>
 </Columns>
</asp:GridView>

           <input id="btnNext" type="button" value="next" />
                <input id="Button1" type="button" value="left" />
           <input id="Button2" type="button" value="right" />

 <input id="btnClose" type="button" value="close" onclick="HideDiv()"/>

Would someone help me?

A: your previous/next buttons will need click event handlers:
$('#yourNextButtonId').bind('click', function(){
    sendAjaxRequestFunction();
}

make an ajax call to a server-side script (such as php), which will return the path of the image you want to display.
http://api.jquery.com/jQuery.ajax/
$.ajax({
    url: "./scripts/chatLogout.php",
    type: "post",
    success: function(response, textStatus, jqXHR)
    {
        $('#yourImageId').attr('src', response);
    }
});

this is just one solution.
depending on the size of your gallery, you can also load all your images upfront, and use jquery/javascript to toggle the visibility of the appropriate image.


text:
Q: Setting up an ftp_get i am attempting to setup a script that connects to an FTP and downloads a file, i used the most basic code:
 <?php
// connect and login to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

$local_file = "local.zip";
$server_file = "server.zip";

// download server file
if (ftp_get($ftp_conn, $local_file, $server_file, FTP_ASCII))
  {
  echo "Successfully written to $local_file.";
  }
else
  {
  echo "Error downloading $server_file.";
  }

// close connection
ftp_close($ftp_conn);
?>

When run on my local machine its connects gets the files, but if i try to set the script up on a different FTP to run in on, it crashes out with no error at step: ftp_get
What am i doing wrong here?
Strangest part is it was working at some point, so im pretty sure the approach should work


text:
Q: How to crawl website that uses Direct Web Remoting (DWR) to return Javascript that manipulates page's HTML I am having issues crawling a particular website that seems to generate all its content dynamically using DWR. The page source reveals a small amount of HTML as a 'shell' which contains no links that I want to crawl. Instead, I see POST requests whose responses contain only Javascript:
throw 'allowScriptTagRemoting is false.';
//#DWR-INSERT
//#DWR-REPLY
var a1 = {}; var a2 = {}; var a3 = {}; // ... etc.
a1.configs=a3;a1.defaultSite=true;a1.defaultValues=a4; // ... etc.

and a bunch of stuff totaling about 150 lines.
I understand that this is how DWR works, but I'd like to know how web crawlers generally get around this. Are there ways for it to execute the javascript from the AJAX's response and then wait for the HTML to finish being edited?
I feel this is different from traditional Ajax requests since they may return HTML and the DOM is updated as soon as the Ajax request is complete. Or, they return some data, and the rest of the page's Javascript updates the DOM. In either case though, there is no need to execute the response afterward.
Any insight would be well appreciated.

A: Not sure on what platform you are trying to crawl the website, but you can try using PhantomJS to run the JavaScript and render the site. If you are trying to crawl it with AJAX from another site, you can send a request to your own server that runs PhantomJS in the back-end and displays the rendered content as the output.


text:
Q: Why the compiler in C++ execute a command before another? could anyone please explain why when i write this code
    int x = 6;
    cout << x << endl << ++x << endl;

the output is
7
7
instead of
6
7
sorry i'm a beginner in this language , when i moved from VB.Net to C++ i feel it's more complicated ..

A: cout << x << endl << ++x << endl;

translates to
cout.operator<<(x).operator<<(endl).operator<<(++x).operator<<(endl);

(where each operator<< call returns a reference to cout for precisely this call chaining), and this is essentially the same as
operator<<(operator<<(operator<<(cout, x), endl), ++x)

(with the last/outermost call discarded for clarity, and the member function call rewritten as an equivalent free function).
Ignoring the endl (which doesn't touch x), the critical part is just a function call of the form
struct C;
C& f(C&, int);
...
f(f(c, x), ++x)

and, like any other function call, the order in which its arguments are evaluated is not defined.  That is, the compiler can emit
int a = f(c, x);
int b = ++x;
f(a, b);

or
int b = ++x;
int a = f(c, x);
f(a, b);

There are good reasons for leaving this evaluation order unspecified (not undefined): different platforms have different calling conventions, and it gives the optimiser more room to manoeuvre.
Still, if you care about the order in which they're evaluated, you have to make it explicit.

A: In a c++ expression, evaluation order of sub-expressions is not specified by the standard and is left as implementation-defined. Thus in your expression your expectation that the x part is evaluated before the ++x part is unfounded: the standard makes no such requirement. In your case the ++x sub-expression is evaluated first, resulting in 7 being passed as the parameter value in both cases of the operator<< invocation. It could just as easily have been the other way round, leading to your expected output: both are correct from the standard's point of view.


text:
Q: IsUPXCompressed Problem The function to determine if an exe file has been compressed (written by RRUZ) is excellent except I found a problem with the code. If the function IsUPXCompressed is called then you try to run upx, UPX can not save the file it modifies. There is something not sharing rights correctly in the function. I have tested this for several hours. If I do not call the method then UPX can write the files with no problem. If you call it then try to run UPX it will not save the file. UPX reports an IOException Permission denied error when trying to write the file.
Can anyone spot something wrong in the code that would cause this problem?
I posted this again because after 24 hours no one seem to see my posts about it at its original locastion: Method to determine if an exe file has been compressed with UPX
Thank-you

A: @RRUZ's code doesn't close either the file mapping or the file handle used to create it.
After the end of the for.. loop in the code, add the following two three lines:
UnmapViewOfFile(pBaseAddress);
CloseHandle(hFileMap);
CloseHandle(hFile);

No need to test them first, as the prior code exited if either of the function calls to open the handles doesn't succeed. (There should probably be try..finally protection of the two opening calls, but I'll leave that to RRUZ to correct in his original post.)


text:
Q: How to move windows around and between screens?
Possible Duplicate:
Unity keyboard/mouse shortcuts

On MS Windows we can use Super + Arrow to move a window to the right and the left of the screen, maximize, minimize and even move it to another screen. Is there a way to configure this feature on Unity?

A: On Unity, you can press Ctrl + Alt + Numpad 1 to move the window to the bottom left of the screen.
You can also use Numpad 4 to move it left, Numpad 7 to move it top left, Numpad 8 to move it top, Numpad 2 to move it bottom, Numpad 9 to move it top right, Numpad 6 to move it right and Numpad 3 to move it bottom right.
I hope this helped you,
Daniel


text:
Q: how to decrease months in php? I want to separate 4 quarter months from current month.
$q1Start = date('Y-m-01',strtotime('-2 months'));
$q1End = date('Y-m-d');

$q2Start = date('Y-m-01',strtotime('-5 months'));
$q2End = date('Y-m-d',strtotime('-3 months'));

$q3Start = date('Y-m-01',strtotime('-8 months'));
$q3End = date('Y-m-t',strtotime('-6 months'));

$q4Start = date('Y-m-01',strtotime('-11 months'));
$q4End = date('Y-m-t',strtotime('-9 months'));

But its not showing the exact date.
I want like this.
2015-06-01
2015-08-31

2015-03-01
2015-05-31

2015-02-28
2014-12-01

2014-09-01
2014-11-30

How to decrease by current month? Thanks

A: Since the quarters should be based on the current month, it's easier to start with the first day of the month for calculations.
$dayOfMonth = date('d');
$firstDayOfCurrentMonth = strtotime(sprintf('-%d days + 1 day midnight', $dayOfMonth));

$q1Start = date('Y-m-d', strtotime('-2 months', $firstDayOfCurrentMonth));
$q1End = date('Y-m-d', strtotime('+1 month - 1 day', $firstDayOfCurrentMonth));

$q2Start = date('Y-m-d', strtotime('-5 months', $firstDayOfCurrentMonth));
$q2End = date('Y-m-d', strtotime('-2 month - 1 day', $firstDayOfCurrentMonth));

$q3Start = date('Y-m-d', strtotime('-8 months', $firstDayOfCurrentMonth));
$q3End = date('Y-m-d', strtotime('-5 month - 1 day', $firstDayOfCurrentMonth));

$q4Start = date('Y-m-d', strtotime('-11 months', $firstDayOfCurrentMonth));
$q4End = date('Y-m-d', strtotime('-8 month - 1 day', $firstDayOfCurrentMonth));

This sets all variables to the expected values.


text:
Q: Cannot cancel a task via CancellationTokenSource.Cancel() I am having trouble stopping a Task. Firstly, I just started using Tasks. Previously, I had been using delegate.BeginInvoke() to run things in background, but this time I need to stop background execution, if required. So I switched to Tasks. This is my code:
CancellationTokenSource token = new CancellationTokenSource();
Task posting = Task.Factory.StartNew(() => DoPosting(docs, session), token.Token);
HttpRuntime.Cache[session.ToString() + "_token"] = token;
HttpRuntime.Cache[session.ToString() + "_task"] = posting;

This is ASP.NET MVC, so I store long-lasting things in HttpRuntime.Cache. User can cancel operation via this action:
public JsonResult StopPosting(string session)
{
    CancellationTokenSource token = (CancellationTokenSource)HttpRuntime.Cache.Get(session.ToString() + "_token");
    Task posting = (Task)HttpRuntime.Cache[session.ToString() + "_task"];
    token.Cancel();

    return Json(new { Message = "Stopped!" });
}

Now, when this action gets hit for the first time, nothing happens. Then i request cancellation for the second time. Now, token.IsCancellationRequested says "true", so token.Cancel() must have done something. But posting.Status is still "Running". It will stay that way until it completes and then it is "RunToCompletion".
So, I requested cancellation of a Task, but it didt got cancelled.
Maybe I am doing something wrong or I am missing something obvious, but I just cant see/understand why it wont cancel.
Maybe somebody can shed some light?
Regards.

A: Cancelling the token won't immediately result in the task's delegate stopping execution right where it is.  Supporting that (as is done via Abort through threads) can cause all sorts of badness, ranging from objects not being cleaned up properly, invariants being violated due to execution stopping part way through an operation that ought to be logically observed to be atomic, etc.
What you need to do is have the actual function being executed look at the CancellationToken and periodically verify that it hasn't been cancelled.  In addition to passing the token to StartNew you need to pass it to the DoPosting method.  That method then needs to periodically call token.ThrowIfCancellationRequested(); at places in the method where it would be appropriate to stop if cancellation was indeed requested.
See How do I cancel non-cancelable async operations? for further reading.

A: I think you're probably expecting too much of CancellationToken. As regards Tasks, I think the CancellationToken is only used when determining whether to start the task when a slot is available for the task. Once the task is started, the task framework cannot simply abort the delegate call when the CancellationToken is cancelled. In order to fully cancel something like this, the code that is called by the Task framework (DoPosting) must be written to be aware of the CancellationToken and must check the state of that token directly at appropriate points in the code.


text:
Q: Destructor parameters The article Are destructors overloadable? talks about overloading the destructor.
This raised a question:  Can a destructor have parameters?
I've never used or seen a destructor with parameters.  I could not come up with an example of a reason to use parameters to the destructor.

A: No, is the simple answer. This would make automatic resource management a significant bitch, because you'd have to worry about what parameters the destructor took and where the hell you were going to get them from. What about in the case of exception- how would the compiler know what to pass your destructor?

A: Section §12.4 of C++0x draft n3290 has this to say about destructors:

Destructors
A special declarator syntax using an optional function-specifier (7.1.2) followed by ˜ followed by the destructor's class name followed by an empty parameter list is used to declare the destructor in a class definition.

(emphasis added)
So no, destructors do not take parameters. (The 2003 standard has the exact wording of the above paragraph.)

A: No. You hardly ever call them directly anyway, so what would be the use.
The destructor is supposed to destroy the object, nothing more.


text:
Q: LINQ .Cast() extension method fails but (type)object works To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs.  That way we can do the following:
DTOType MyDTO = (LinqToSQLType)MyLinq2SQLObj;

This works well.
However when you try to cast using the LINQ .Cast() extension method it trows an invalid cast exception saying cannot cast type Linq2SQLType to type DTOType.  i.e. the below does not work
List<DTO.Name> Names = dbContact.tNames.Cast<DTO.Name>()
                                               .ToList();

But the below works fine:
DAL.tName MyDalName = new DAL.tName();
DTO.Name MyDTOName = (DTO.Name)MyDalName;

and the below also works fine
List<DTO.Name> Names = dbContact.tNames.Select(name => (DTO.Name)name)
                                               .ToList();

Why does the .Cast() extension method throw an invalid cast exception?  I have used the .Cast() extension method in this way many times in the past and when you are casting something like a base type to a derived type it works fine, but falls over when the object has an explicit cast operator.

A: The Cast<> extension method does not apply user-defined conversions. It can only cast to interfaces or within the class heirarchy of the supplied type.
User defined conversions are identified at compile time based on the static types involved in the expression. They cannot be applied as runtime conversions, so the following is illegal:
public class SomeType
{
  public static implicit operator OtherType(SomeType s)
  {
    return new OtherType();
  }
}

public class OtherType { }

object x = new SomeType();
OtherType y = (OtherType)x; // will fail at runtime

It doesn't matter whether a UDC exists from SomeType to OtherType - it cannot be applied through a reference of type object. Trying to run the above code would fail at runtime, reporting something like:
System.InvalidCastException:
    Unable to cast object of type 'SomeType' to type 'OtherType'

Cast<>() can only perform representation preserving conversions ... that's why you can't use it to apply user-defined conversions.
Eric Lippert has a great article about the behavior of the cast operator in C# - always a worthwhile read.

A: If you decompile the Linq assembly you get code resembling the following.  The previous answer is correct, ultimately the cast is from 'object' to target-type which will always fail for custom types.
private static IEnumerable<TResult> CastIterator<TResult>( IEnumerable source )
{
    foreach(object current in source)
    {
        yield return (TResult)( (object)current );
    }
    yield break;
}

public static IEnumerable<TResult> DCast<TResult>( this IEnumerable source )
{
    IEnumerable<TResult> enumerable = source as IEnumerable<TResult>;
    if(enumerable != null)
    {
        return enumerable;
    }
    if(source == null)
    {
        throw new ArgumentNullException( "source" );
    }
    return CastIterator<TResult>( source );
}

TFish

A: For those that hit this question looking for a workaround...
Dim res = arrayOfStrings.Select(Function(__) CType( __, YourType ))

Not sure the exact semantics with C#, but i'm sure it's pretty easy.


text:
Q: Access denied ("java.util.PropertyPermission" "user.name" "read") Java Applet for 1.8.0_25 version I have this applet:
import java.applet.Applet;

public class UserNapplet extends Applet {
public void init() { }
public String getUser() {
    try {
    return System.getProperty("user.name");
    } catch (Exception e) {
    e.printStackTrace();
    return "error";
    }
}
}

and html tag:

<applet code="UserNapplet.class" height="0" width="0" id="uname" archive="UserNapplet.jar"/>
`

How to make it work?
What I did?
a bat file .....
del UserNapplet.jar
del UserNapplet.class
javac UserNapplet.java
jar cvf UserNapplet.jar UserNapplet.class
jar ufm UserNapplet.jar mymanifest.txt
jarsigner -verbose UserNapplet.jar SecGen

//(SecGen is my "certificate")...
mymanifest.txt says:
Permissions: all-permissions
Application-Name: SecGen
Codebase: http://172.31.31.4/MyAppDir `  (a folder in C.\inetpub\wwwroot)

The running policytools generates
/* AUTOMATICALLY GENERATED ON Wed Dec 10 08:29:52 PYST 2014*/
/* DO NOT EDIT */
grant codeBase "file:///C:/inetpub/wwwroot/MyAppDir/UserNapplet.jar" {
permission java.security.AllPermission;
permission java.util.PropertyPermission "*", "read";
};

With all of this.... the applet still throwing
java.security.accesscontrolexception: access denied ("java.util.propertypermission" "user.name" "read")

What more to do?