text:
Q: Auto-mapper 3.2 throw error with Entity Framework core 2.1 I am working on .NET CORE application with Entity Framework Core 2.0 and automapper 3.2.0, recently updated Entity Framework Core from 2.0 to 2.1.2 and start getting an error for automapper.

I wonder if I need to update any other package along with that or entity framework core 2.1.2 is compatible with Automapper 3.2.0.


text:
Q: Serial Communnication over USB with a LIVE USB boot The application uses serial communication over USB and works fine when the PC boots from HDD.
I have created a liveUSB image (.iso) of the working OS.
Booted the same PC from USB drive which contains the .iso image.
Now, the DUT is connected and the application is run, which reports that there is Garbage on the Line most of the times. However, it does work on some attempts, it is very inconsistent.
I couldn't understand how does a boot from a Live USB is different from a HDD boot.
FYI, PC has Fedora Core 22 with 4.0.4 Linux kernel.
Serial communication: baudrate is 115200 with 1 stop bit.
Any help is much appreciated.
Thanks,
Shahab
Edit
I have checked dmesg and found a difference,
cdc_acm : failed to set dtr/rts on Live USB boot. It is not seen in the other case. Similar to this question on stackoverflow.
Another observation, the serial communication works fine when the device is connected and PC boots from the Live USB stick. If the USB cable to the device is unplugged and plugged in again, it reports the issue.

A: After reconnecting the USB cable your serial ports number will probably be incremented and you will have a dead /dev/ttyUSB0 and probably a new working /dev/ttyUSBX. As your application keeps the /dev/ttyUSB0 open it will not be removed until you restart your app. Keep reading the old ttyUSB0 and you will  get the garbage.
A second hint would be, that you probably have a read-only filesystem when booting from live so you are not able to create anything new in the /dev folder so the new device will not show up.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Triangle-style breadcrumbs without images I created arrow(triangle)-style breadcrumbs with CSS, no images.
jsFiddle
html:

Home

First item

Second item

Last item

css:
.breadcrumb {
    list-style: none;
    overflow: hidden;
}
.breadcrumb li {
    background: #F6F6F6;
    padding: 5px 0 5px 36px;
    background: #F6F6F6;
    position: relative;
    display: block;
    float: left;
}
.breadcrumb li:before {
    content:" ";
    display: block;
    width: 0;
    height: 0;
    border-top: 25px solid transparent;
    border-bottom: 25px solid transparent;
    border-left: 20px solid #DDDDDD;
    position: absolute;
    top: 50%;
    margin-top: -25px;
    margin-left: 1px;
    left: 100%;
    z-index: 1;
}
.breadcrumb li:after {
    content:" ";
    display: block;
    width: 0;
    height: 0;
    border-top: 25px solid transparent;
    border-bottom: 25px solid transparent;
    border-left: 20px solid #F6F6F6;
    position: absolute;
    top: 50%;
    margin-top: -25px;
    left: 100%;
    z-index: 2;
}

The problem is when parent's width is not enough to display breadcrumbs in 1 line and it takes 2 lines (or more), overflow:hidden stops working and unwanted parts of triangles get visible (http://screencloud.net/v/fQEq).
Is there a way to fix that?

A: Try with this style:
.breadcrumb {
    list-style: none;
    overflow: hidden;
}
.breadcrumb li:before {
    border-bottom: 15px solid transparent;
    border-left: 20px solid #dddddd;
    border-top: 15px solid transparent;
    content:" ";
    display: block;
    height: 0;
    left: 100%;
    margin-left: 1px;
    margin-top: -15px;
    position: absolute;
    top: 50%;
    width: 0;
    z-index: 1;
}
.breadcrumb li:after {
    border-bottom: 15px solid transparent;
    border-left: 20px solid #f6f6f6;
    border-top: 15px solid transparent;
    content:" ";
    display: block;
    height: 0;
    left: 100%;
    margin-top: -15px;
    position: absolute;
    top: 50%;
    width: 0;
    z-index: 2;
}
.breadcrumb li {
    background: none repeat scroll 0 0 #f6f6f6;
    display: block;
    float: left;
    height: 20px;
    padding: 5px 0 5px 33px;
    position: relative;
}

Hope it helps!


text:
Q: Analyzing traffic by tcpdump between HAProxy server and mariadb I was testing tcpdump too see the traffic between HAProxy server and mariadb server. These are the results:
23:07:22.328958 00:0c:29:a9:28:a8 > 00:50:56:b0:e0:ea, ethertype IPv4 (0x0800), length 66: (tos 0x0, ttl 64, id 62140, offset 0, flags [DF], proto TCP (6), length 52)
    172.24.2.51.46370 > 172.24.2.41.9200: Flags [.], cksum 0xcf6a (incorrect), seq 2091233458, ack 1346328093, win 229, options [nop,nop,TS val 2961588746 ecr 287872844], length 0
    0x0000:  4500 0034 f2bc 4000 4006 e966 ac18 033d  E..4..@.@..f...=
    0x0010:  ac18 0333 b522 23f0 7ca5 b0b2 503f 561d  ...3."#.|...P?V.
    0x0020:  8010 00e5 cf6a 0000 0101 080a b086 420a  .....j........B.
    0x0030:  1128 974c                                .(.L

23:07:22.328997 00:0c:29:a9:28:a8 > 00:50:56:b0:e0:ea, ethertype IPv4 (0x0800), length 88: (tos 0x0, ttl 64, id 62141, offset 0, flags [DF], proto TCP (6), length 74)
    172.24.2.51.46370 > 172.24.2.41.9200: Flags [P.], cksum 0x460a (correct), seq 0:22, ack 1, win 229, options [nop,nop,TS val 2961588746 ecr 287872844], length 22
        0x0000:  4500 004a f2bd 4000 4006 e94f ac18 033d  E..J..@.@..O...=
        0x0010:  ac18 0333 b522 23f0 7ca5 b0b2 503f 561d  ...3."#.|...P?V.
        0x0020:  8018 00e5 460a 0000 0101 080a b086 420a  ....F.........B.
        0x0030:  1128 974c 4f50 5449 4f4e 5320 2f20 4854  .(.LOPTIONS./.HT
        0x0040:  5450 2f31 2e30 0d0a 0d0a                 TP/1.0....

23:07:22.357592 00:0c:29:a9:28:a8 > 00:50:56:b0:e0:ea, ethertype IPv4 (0x0800), length 66: (tos 0x0, ttl 64, id 62142, offset 0, flags [DF], proto TCP (6), length 52)
    172.24.2.51.46370 > 172.24.2.41.9200: Flags [.], cksum 0xcf0a (correct), seq 22, ack 18, win 229, options [nop,nop,TS val 2961588774 ecr 287872873], length 0
        0x0000:  4500 0034 f2be 4000 4006 e964 ac18 033d  E..4..@.@..d...=
        0x0010:  ac18 0333 b522 23f0 7ca5 b0c8 503f 562e  ...3."#.|...P?V.
        0x0020:  8010 00e5 cf0a 0000 0101 080a b086 4226  ..............B&
        0x0030:  1128 9769                                .(.i

23:07:22.357641 00:0c:29:a9:28:a8 > 00:50:56:b0:e0:ea, ethertype IPv4 (0x0800), length 66: (tos 0x0, ttl 64, id 62143, offset 0, flags [DF], proto TCP (6), length 52)
    172.24.2.51.46370 > 172.24.2.41.9200: Flags [R.], cksum 0xc1b3 (incorrect), seq 22, ack 18, win 229, options [nop,nop,TS val 0 ecr 287872873], length 0
        0x0000:  4500 0034 f2bf 4000 4006 e963 ac18 033d  E..4..@.@..c...=
        0x0010:  ac18 0333 b522 23f0 7ca5 b0c8 503f 562e  ...3."#.|...P?V.
        0x0020:  8014 00e5 c1b3 0000 0101 080a 0000 0000  ................
        0x0030:  1128 9769

As you see as example, there are two packets or frame that shows (incorrect).
What does it mean with (incorrect)? Does the network packet contain errors?
How can hexa checksum value help the integrity? For example the first packet, the cksum shows 0xcf6a. How can this value help the data integrity?
Regards

A: IP protocol uses header checksum:
From wikipedia

The checksum field is the 16-bit one's complement of the one's
  complement sum of all 16-bit words in the header. For purposes of
  computing the checksum, the value of the checksum field is zero.

This field is used as a mechanism to see if something has changed in IP header during the transmission (errors or man in the middle)


text:
Q: Autofill BCC address I want to autofill the BCC field with a specific address on replies, forwards and new emails.
I have seen a similar function that performs "silently" - i.e., the BCC address is added once the 'Send' button has been pressed.
I want to be able to remove/change the address if necessary.
From the user's perspective: click reply/forward/new email, and the message window opens up with the BCC field filled.
My knowledge of VBA is somewhat limited, so I'd appreciate if you could be specific about where to place the code.

A: This code put in ThisOutlookSession module will fire when you click on the button New Email and when replying to an email. From there it's simple to insert whatever you need in the various fields. You need to restart Outlook or manually call Application_Startup() to have it activated the first time.
Option Explicit

Public WithEvents myInspectors As Outlook.Inspectors
Public WithEvents myExplorer As Outlook.Explorer

Private Sub Application_Startup()
  Set myInspectors = Application.Inspectors
  Set myExplorer = Application.ActiveExplorer
End Sub

Private Sub myInspectors_NewInspector(ByVal Inspector As Inspector)
  If TypeName(Inspector.CurrentItem) = "MailItem" Then
    'MsgBox "new mail"
    Inspector.CurrentItem.BCC = "joe.doe@domain.com"
  End If
End Sub

Private Sub myExplorer_InlineResponse(ByVal Item As Object)
    'MsgBox "reply"
    Item.BCC = "jane.dane@domain.com"
End Sub


text:
Q: Getting error #1221 - Incorrect usage of UNION and LIMIT I'm trying to make union query with this two queries using union between the queries but getting error #121 Incorrect usage of UNION and LIMIT. Please help me to make this union queries to get result both of this queries.
query1:
SELECT t1.TraineeID,
       t2.attnDate,
       MIN(t1.attnTime) AS inTime,
       (CASE WHEN MIN(t1.attnTime) < MAX(t1.attnTime) THEN MAX(t1.attnTime) else '' end) AS outTime,
       (CASE WHEN t5.Slot ='1' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '1')THEN 'P'
             WHEN t5.Slot ='2' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '2')THEN 'P'
             WHEN t5.Slot ='3' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '3')THEN 'P'
             WHEN t5.Slot ='4' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '4')THEN 'P'
             WHEN t5.Slot ='1' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '1')THEN 'Early Out'
             WHEN t5.Slot ='2' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '2')THEN 'Early Out'
             WHEN t5.Slot ='3' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '3')THEN 'Early Out'
             WHEN t5.Slot ='4' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '4')THEN 'Early Out'
             ELSE 'Late-In'
       END) AS Status

FROM tbl_attn_temp t1, tbl_assigned t3, tbl_batch t5
JOIN (SELECT DISTINCT attnDate FROM tbl_attn_temp) t2
WHERE t1.attndate = t2.attnDate and t3.BatchID=t5.BatchID AND t1.TraineeID = t3.TraineeID
AND t1.attnDate='2016-01-13'
AND(CASE WHEN t5.Slot ='1' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '1') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '1')
         WHEN t5.Slot ='2' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '2') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '2')
         WHEN t5.Slot ='3' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '3') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '3')
         WHEN t5.Slot ='4' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '4') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '4')
    END)
GROUP BY t1.TraineeID, t2.attnDate

query2:
SELECT t1.TraineeID,
       t2.attnDate,
       MIN(t1.attnTime) AS inTime,
              (CASE WHEN MIN(t1.attnTime) < MAX(t1.attnTime) THEN MAX(t1.attnTime) else '' end) AS outTime,
       (CASE WHEN t4.Slot ='1' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '1')THEN 'P'
             WHEN t4.Slot ='2' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '2')THEN 'P'
             WHEN t4.Slot ='3' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '3')THEN 'P'
             WHEN t4.Slot ='4' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '4')THEN 'P'
             WHEN t4.Slot ='1' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '1')THEN 'Early Out'
             WHEN t4.Slot ='2' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '2')THEN 'Early Out'
             WHEN t4.Slot ='3' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '3')THEN 'Early Out'
             WHEN t4.Slot ='4' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '4')THEN 'Early Out'
             ELSE 'Late-In'
       END) AS Status

FROM tbl_attn_temp t1, tbl_assigned t3, tbl_instructor_info t4
JOIN (SELECT DISTINCT attnDate FROM tbl_attn_temp) t2
WHERE t1.attndate = t2.attnDate AND t1.TraineeID = t4.InstructorID
AND t1.attnDate='2016-01-13'
AND(CASE WHEN t4.Slot ='1' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '1') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '1')
         WHEN t4.Slot ='2' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '2') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '2')
         WHEN t4.Slot ='3' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '3') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '3')
         WHEN t4.Slot ='4' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '4') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '4')
    END)
GROUP BY t1.TraineeID, t2.attnDate

A: Just add parenthesis to those union statements. It works for me, for example:
(select ... limit 1)
union
(select ... limit 1)
union
(select ... limit 1)
union all with parenthesis works too.

A: It's caused by a change on MySQL 5.7. To solve this problem, you have to "nest" your SELECTS, as follow:
SELECT * FROM(

    SELECT t1.TraineeID,
           t2.attnDate,
           MIN(t1.attnTime) AS inTime,
           (CASE WHEN MIN(t1.attnTime) < MAX(t1.attnTime) THEN MAX(t1.attnTime) else '' end) AS outTime,
           (CASE WHEN t5.Slot ='1' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '1')THEN 'P'
                 WHEN t5.Slot ='2' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '2')THEN 'P'
                 WHEN t5.Slot ='3' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '3')THEN 'P'
                 WHEN t5.Slot ='4' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '4')THEN 'P'
                 WHEN t5.Slot ='1' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '1')THEN 'Early Out'
                 WHEN t5.Slot ='2' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '2')THEN 'Early Out'
                 WHEN t5.Slot ='3' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '3')THEN 'Early Out'
                 WHEN t5.Slot ='4' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '4')THEN 'Early Out'
                 ELSE 'Late-In'
           END) AS Status

    FROM tbl_attn_temp t1, tbl_assigned t3, tbl_batch t5
    JOIN (SELECT DISTINCT attnDate FROM tbl_attn_temp) t2
    WHERE t1.attndate = t2.attnDate and t3.BatchID=t5.BatchID AND t1.TraineeID = t3.TraineeID
    AND t1.attnDate='2016-01-13'
    AND(CASE WHEN t5.Slot ='1' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '1') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '1')
             WHEN t5.Slot ='2' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '2') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '2')
             WHEN t5.Slot ='3' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '3') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '3')
             WHEN t5.Slot ='4' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '4') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '4')
        END)
    GROUP BY t1.TraineeID, t2.attnDate
) AS query1

UNION
SELECT * FROM(
SELECT t1.TraineeID,
       t2.attnDate,
       MIN(t1.attnTime) AS inTime,
              (CASE WHEN MIN(t1.attnTime) < MAX(t1.attnTime) THEN MAX(t1.attnTime) else '' end) AS outTime,
       (CASE WHEN t4.Slot ='1' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '1')THEN 'P'
             WHEN t4.Slot ='2' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '2')THEN 'P'
             WHEN t4.Slot ='3' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '3')THEN 'P'
             WHEN t4.Slot ='4' AND t1.attnTime<=(SELECT inTime FROM tbl_threshold WHERE id = '4')THEN 'P'
             WHEN t4.Slot ='1' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '1')THEN 'Early Out'
             WHEN t4.Slot ='2' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '2')THEN 'Early Out'
             WHEN t4.Slot ='3' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '3')THEN 'Early Out'
             WHEN t4.Slot ='4' AND max(t1.attnTime)<(SELECT outTime FROM tbl_threshold WHERE id = '4')THEN 'Early Out'
             ELSE 'Late-In'
       END) AS Status

FROM tbl_attn_temp t1, tbl_assigned t3, tbl_instructor_info t4
JOIN (SELECT DISTINCT attnDate FROM tbl_attn_temp) t2
WHERE t1.attndate = t2.attnDate AND t1.TraineeID = t4.InstructorID
AND t1.attnDate='2016-01-13'
AND(CASE WHEN t4.Slot ='1' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '1') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '1')
         WHEN t4.Slot ='2' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '2') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '2')
         WHEN t4.Slot ='3' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '3') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '3')
         WHEN t4.Slot ='4' THEN t1.attnTime BETWEEN(SELECT minLimit FROM tbl_threshold WHERE id = '4') AND (SELECT maxLimit FROM tbl_threshold WHERE id = '4')
    END)
GROUP BY t1.TraineeID, t2.attnDate
) as query2

A: try keyword union all instead of union
try:
select * from (query 1)
union all
(query 2)


text:
Q: First of the The Ten Commandments for C++ Programmers by Steve Oualline correctly transcribed? I do not have the book "Practical C++ Programming" by Steve Oualline but I was reading his Ten Commandments for C++ programmers at The Ten Commandments for C++ Programmers and I was wondering if the first has been correctly transcribed? For reference the transcription is:

*

*Thou shalt not rely on the compiler default methods for construction, destruction, copy construction, or assignment for any but the simplest of classes. Thou shalt forget these "big four" methods for any nontrivial class.

He seems to be advocating manually defining copy construction and copy assignment. Is that a correct interpretation of his first commandment?
Edit: Although at present I am leaving Adrian's answer as the accepted one I would like anyone who views this question to read Jerry's. I did specifically ask whether the above text is accurately transcribed and not about its merit (which is probably a more interesting discussion). But Jerry does make some good points about its merit (or lack thereof) which are similar to my opinions of it. I just wanted to make sure I had the quote right before I constructed a thorough argument of why I disagree with it.

A: For "any nontrivial" class I am sure that is exactly what he is suggesting - and it would certainly be good practice to write an explicit copy constructor or overloaded assignment for such a non-trivial class.

A: I think this is probably inaccurately transcribed in one respect. The sentence: "Thou shalt forget these "big four" methods for any nontrivial class." is probably intended to read: "Thou shalt not forget these "big four" methods for any nontrivial class."
Other than that, it looks to me like it's probably accurately transcribed. Unfortunately, the advice is mostly out of date. The book in question was written in 1995 and updated in 1997. A lot has happened in the 15+ years since then that renders this advice obsolete.
The advice is based on the notion of a non-trivial class implementing "remote ownership" -- i.e., containing one or more pointers to data it owns (that will probably be allocated on the free store, but somewhere outside the object itself in any case). Obvious examples are things like std::string and std::vector, each of which normally allocates a block of memory to hold the data in the container (and the string or vector object itself contains only the pointer and a little bookkeeping data, such as the size of the allocated block and the number of items in that block that are currently in use).
The reason I say that's out of date is that in most cases,  you should not be using raw pointers for remote ownership at all. Instead, you should typically use a smart pointer (e.g., unique_ptr or shared_ptr) to manage the remote ownership. That smart pointer should implement the remote ownership "policy" (copying, assignment, destruction) of the data it owns.
Then the non-trivial class will simply aggregate an instance (or more than one, depending) to manage its remote data. In the process, it gets the correct ownership policy implemented by those smart pointers. As a result, it usually won't need to implement any of the above at all.
That typically leaves only construction to be handled by the non-trivial class. Even that will typically just "distribute" data out to the base class and/or aggregated objects, so the body of the ctor is often empty:
class foo {
    std::unique_ptr<T> data;
public:
    foo(T const &input) : data(std::make_unique(input)) : {}
};

Bottom line: a non-trivial class should present a logical view of an abstraction. It should deal almost exclusively with the logic of the abstraction it represents. It should rarely (if ever) directly deal directly with low-level, language-oriented issues such as allocation, deletion, and copying of memory needed to represent the abstraction it represents.
Those issues should nearly always be dealt with by lower-level classes also designed to represent an abstraction -- but in this case, a fairly simple abstraction of "remotely owned data", that knows how to handle things like copying, assigning, and destroying the data it owns, with little or no help from the class that owns it (e.g., the owning class passing some function arguments to tell how to destroy the owned data). At least in many (most?) typical cases, one of the pointer classes in the standard library (such as the aforementioned unique_ptr or shared_ptr) will be entirely adequate to this task.
As a result, you should rarely need to define your own copy constructor, copy assignment or destructor. These issues should typically be handled by lower-level classes devoted to providing remote ownership. There is, however, still a fair argument to be made that for non-trivial classes, these should still be defined (at least in most cases) but defined as = default; in most cases.

References and further reading:

*

*https://web.archive.org/web/20151006051620/http://flamingdangerzone.com/cxx11/rule-of-zero/

*http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/


text:
Q: React form not populating data I am working with some data and trying to populate a form dynamically. It works as I expected except when it comes to an array for one of the dropdowns. For some reason it will log to the console but not update the options.
import React, { useReducer} from 'react'
import { Container } from 'react-bootstrap';
import Products from '../data/Products';
import { v4 as uuidv4 } from 'uuid';

const ProductForm= () => {
const useReducerState = (initialState = {}) => {
    const reducer = (prev, next) => ({ ...prev, ...next });
    return useReducer(reducer, initialState);
};

const [state, setState] = useReducerState({
make: "",
model: "",
storage: "",
color: "",
});

 const handleChange = (e) => {
    let proToUpdate = e.target.name;
    let value = e.target.value;
    if (value){setState({ [proToUpdate]: value }); }
}

 const {
    make,
    model,
    storage,
    color,
} = state;

 return (
    <Container>
    <form autoComplete='off'>
        <div className="form-group">
            <select name="make" className="hardwear" id="make" value={make} required onChange={handleChange}>
                <option value="">Manufacturer</option>
               { Object.keys(Products["handset"]["hardwear"]).map(item => {
            return (<option value={item} key={uuidv4()}>{item}</option>);
          })}
            </select>
            <select name="model" id="model" className="hardwear" value={model} onChange={handleChange}>
                <option value="">Model</option>
                { make && ( Object.keys(Products["handset"]["hardwear"][state.make]).map(item => {
            return (<option value={item} key={uuidv4()}>{item}</option>);
          }))}
            </select>
            <select name="storage" className="hardwear" value={storage} onChange={handleChange}>
                <option value="">Storage</option>
                { model && (Products["handset"]["hardwear"][state.make][state.model]["storage"].forEach(item => {
                    console.log(item)
             return (<option value={item} key={uuidv4()}>{item}</option>);

          }))}
        </form>
</Container>
)
}

The issue is the storage option. As I said, it will log the value to the console but doesn't populate the dropdown. Here is the data I am using, which I cannot change for now.
const Products = {
  "handset" : {
    "hardwear":
       {
    "Apple": {

        "iPhone 13": {
            "color": ["Blue","Pink","Midnight","Red","Starlight"],
            "storage": ["128GB", "256GB", "512GB"],
        },
        "iPhone 13 Pro": {
            "color": ["Sierra Blue","Gold","Graphite","Silver"],
            "storage": ["128GB", "256GB", "512GB", "1 Terabyte"],
        },
}}}}

A: EDIT:
You should use map instead of forEach.
In your options for storage select you put your item as a string. Remove the double quotes around item:
    <select name="storage" className="hardwear" value={storage} onChange={handleChange}>
        <option value="">Storage</option>
        { model && (Products["handset"]["hardwear"][state.make][state.model]["storage"].map(item => {
              console.log(item)
              return (<option value={item} key={uuidv4()}>{item}</option>);

            })
        )
        }
  </select>

It might be a copy paste error but you are also missing a closing select in your code.


text:
Q: Shadow index for Sentinel 2 How is the shadow index calculated for Sentinel 2 imagery in Google Earth Engine? The following doesn't work:
var s2 = ee.Image('COPERNICUS/S2_SR/20200101T100319_20200101T100321_T32TQM')

var shadowIndex = s2
  .expression('(1 - blue) * (1 - green) * (1 - red)', {
    'blue': s2.select('B2'),
    'green': s2.select('B3'),
    'red': s2.select('B4'),
  })
  .pow(1/3)

Map.addLayer(s2, {bands: 'B4,B3,B2', max: 3000, gamma: 1.5}, 'rgb')
Map.addLayer(shadowIndex, {max: 10000}, 'shadowIndex')
Map.setCenter(12.492289, 41.890117, 14)

https://code.earthengine.google.com/3400a9c967ef320506632a8cc7d1499a

A: Sentinel 2 imagery in EE has been scaled by 10000, so 1 - bandName will not work. You either have to divide your image with 10000 before doing the calculation, giving you an index between 0 and 1:
var s2 = ee.Image('COPERNICUS/S2_SR/20200101T100319_20200101T100321_T32TQM')
  .divide(10000)

Or you do 10000 - bandName, giving you an index between 0 and 10000:
var shadowIndex = s2
  .expression('(10000 - blue) * (10000 - green) * (10000 - red)', {
    'blue': s2.select('B2'),
    'green': s2.select('B3'),
    'red': s2.select('B4'),
  })
  .pow(1/3)
  .uint16()

Here's a complete script without scaling the image: https://code.earthengine.google.com/f493e8cb7762d532ccdf69b15924469f


text:
Q: @Autowired not working in AuthenticationSuccessHandler of Spring-Security Hi I am unable to access spring bean in AuthenticationSuccessHandler of spring security.I saw many post in stackoverflow but no luck nothing works,
Spring-MVC-3.2.6
Spring Security - 3.2.0
Please find the below file for reference,
servlet-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
    <context:component-scan base-package="com.taskmanagement" />
    <security:global-method-security
        pre-post-annotations="enabled">
        <!--register security:expression-handler To use rights(hasPermission) along
            wih roles(hasRole) -->
        <security:expression-handler ref="TaskManagementExpressionHandler" />
    </security:global-method-security>
    <bean id="TaskManagementExpressionHandler"
        class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
        <property name="permissionEvaluator">
            <bean id="permissionEvaluator"
                class="com.taskmanagement.security.TaskManagementPermissionEvaluator">
                <property name="dataSource" ref="dataSource"></property>
            </bean>
        </property>
    </bean>
    <!--mvc:resources is used for static file location location is a folder
        underneath spring will look for static resources 2)Also we should configure
        this in web.xml.Because right now we configured only for .html not .pdf -->
    <mvc:resources location="pdfs" mapping="/pdfs/**" />
     <mvc:resources mapping="/resources/**" location="/resources/"/>
     <mvc:resources mapping="/webjars/**" location="/webjars/"/>
    <!-- p:basename :: Here we should give the property file name here the name
        is messages. This bean is simply used by spring for message resource -->
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="messages" />
    <!--This bean is simply used by spring for message resource for locale resolver
        it uses interceptor -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
        p:defaultLocale="en" />
    <!-- Now register locale interceptor.That's it for locale -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
            p:paramName="language"></bean>
    </mvc:interceptors>
    <import resource="hibernate-config.xml" />
    <!-- Method1 Long hand <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix"
        value=".jsp"></property> </bean> -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="3"></bean>
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
        p:order="2" />
    <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="contentNegotiationManager">
            <bean class="org.springframework.web.accept.ContentNegotiationManager">
                <constructor-arg>
                    <bean
                        class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                        <constructor-arg>
                            <map>
                                <entry key="json" value="applicaton/json"></entry>
                                <entry key="xml" value="applicaton/xml"></entry>
                            </map>
                        </constructor-arg>
                    </bean>
                </constructor-arg>
            </bean>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
                <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                    <constructor-arg>
                        <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
                            <property name="autodetectAnnotations" value="true"></property>
                        </bean>
                    </constructor-arg>
                </bean>
            </list>
        </property>
    </bean>
    <bean id="contentNegotiationManager"    class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
    <property name="favorPathExtension" value="false" />
    </bean>
    <bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"></property>
    <property name="order" value="0"></property>
    </bean>

    <!-- Helper class to configure Tiles 2.x for the Spring Framework -->
    <!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/view/tiles2/TilesConfigurer.html -->
    <!-- The actual tiles templates are in the tiles-definitions.xml -->
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/config/tiles-definitions.xml</value>
            </list>
        </property>
    </bean>
<import resource="classpath:/WEB-INF/config/security-config.xml" />
</beans>

security-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- We are making security as default bean instead of beans -->
    <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- This will activate the expressions in spring valid expr are : hasRole,hasAnyRole,hasPermission,PermitAll -->
    <http use-expressions="true" auto-config="true">
        <!-- Allow login only user must have ROLE_USER -->
        <!-- The below line is for spring basic authentication without using custom
            controller * jsp <http-basic/> -->
        <!-- For custom login use the below code -->
        <intercept-url pattern="/login*" access="permitAll" /> <!-- Without this it won't allow the access for login.html because in the
            above we restrained URL with ROLE_USER -->
        <intercept-url pattern="/resources/**" access="permitAll"/>
        <intercept-url pattern="/loginFailed.html" access="permitAll" />
        <intercept-url pattern="/logout.html" access="permitAll" />
        <intercept-url pattern="/signup.html" access="permitAll" />
        <intercept-url pattern="/signupSubmit.html" access="permitAll" />
        <intercept-url pattern="/session-expired.html" access="permitAll" />
        <intercept-url pattern="/updatepassword*" access="permitAll"/>
        <intercept-url pattern="/changePassword*" access="permitAll"/>
        <intercept-url pattern="/403.html" access="permitAll" />
        <!--<intercept-url pattern="/**" access="ROLE_USER"/> if we activate expression
            then we should use hasRole or hasAnyRole or hasPermission or PermitAll in
            access other wise it ill throw http status 500 failed to evaluate expr error -->
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
        <form-login login-page="/login.html"
            authentication-failure-url="/loginFailed.html" authentication-success-handler-ref="successAuthenticationHandler"/>
        <logout logout-success-url="/logout.html" delete-cookies="JSESSIONID"/>
        <access-denied-handler error-page="/403.html" />
        <remember-me key="myAppKey" user-service-ref="userDetailsService"/>
        <!-- This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated.
        Often you would prefer to prevent a second login, in which case you can use -->
         <session-management invalid-session-url="/session-expired.html">
           <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/session-expired.html"/>
         </session-management>
    </http>
    <!-- Password Hashing Bean -->
    <beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" >
         <beans:constructor-arg name="strength" value="12" />
    </beans:bean>
    <!-- After successfull login using the below handler we will map to corresponding screen -->
    <beans:bean id="successAuthenticationHandler"
        class="com.taskmanagement.authentication.handler.SuccessAuthenticationHandler"/>

    <authentication-manager>
        <!-- <authentication-provider user-service-ref="userDetailsService"/> -->
        <authentication-provider>
            <!-- The below code will configure md5 <password-encoder hash="md5"></password-encoder> -->
            <!-- The below code will configure bcrypt -->
            <password-encoder ref="passwordEncoder"></password-encoder>
            <!--<jdbc-user-service data-source-ref="dataSource" />  -->
            <jdbc-user-service data-source-ref="dataSource"
    users-by-username-query="select username,password, enabled from users where username=?"
    authorities-by-username-query="select username, authority from authorities where username =?  " />
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"></beans:property>
        <beans:property name="url"
            value="jdbc:mysql://localhost:3306/taskmgmt"></beans:property>
        <beans:property name="username" value="root"></beans:property>
        <beans:property name="password" value="root"></beans:property>
    </beans:bean>
    <beans:bean id="userDetailsService"
        class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
    </beans:bean>
<!-- Session Timeout & Concurrency control -->
</beans:beans>

SuccessAuthenticationHandler.java
package com.taskmanagement.authentication.handler;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import com.taskmanagement.dao.CommonDao;

@Service("authenticationSuccessHandler")
public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private CommonDao userDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        System.out.println("onAuthenticationSuccess::Entered");
        User user = (User)authentication.getPrincipal();
        String userName = user.getUsername();
        System.out.println("userName::"+user.getUsername());
        com.taskmanagement.model.User userBo = this.userDao.get(com.taskmanagement.model.User.class,userName);
        userBo.setLastLogggedIn(new Date());
        userDao.saveOrUpdate(user);
        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }
    protected void handle(HttpServletRequest request,
              HttpServletResponse response, Authentication authentication) throws IOException {
                String targetUrl = determineTargetUrl(authentication);

                if (response.isCommitted()) {
                    System.out.println("Response has already been committed. Unable to redirect to " + targetUrl);
                    return;
                }

                redirectStrategy.sendRedirect(request, response, targetUrl);
            }

            /** Builds the target URL according to the logic defined in the main class Javadoc. */
            protected String determineTargetUrl(Authentication authentication) {
                boolean isUser = false;
                boolean isAdmin = false;
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                for (GrantedAuthority grantedAuthority : authorities) {
                    if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                        isUser = true;
                        break;
                    } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                        isAdmin = true;
                        break;
                    }
                }
                System.out.println("isUser::"+isUser+"::isAdmin::"+isAdmin);
                if (isUser) {
                    return "/adminEntryAction.html";
                } else if (isAdmin) {
                    return "/addMinutes.html";
                } else {
                    throw new IllegalStateException();
                }
            }

            protected void clearAuthenticationAttributes(HttpServletRequest request) {
                HttpSession session = request.getSession(false);
                if (session == null) {
                    return;
                }
                session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
            }

            public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
                this.redirectStrategy = redirectStrategy;
            }
            protected RedirectStrategy getRedirectStrategy() {
                return redirectStrategy;
            }

}

In SuccessAuthenticationHandler.java while accessing this.userDao it throws nullPointerException could anyone please guide me to resolve this issue.
Kindly let me know for any queries.
CommonDao.java
public interface CommonDao {

    public <T> Integer save(final T obj);

    public <T> String saveRetString(final T obj);

    public <T> void delete(final Class<T> type,final String obj);

    public <T> T get(final Class<T> type, final String id);

    public <T> T merge(final T o);

    public <T> void saveOrUpdate(final T o);

    public <T> List<T> getAll(final Class<T> type);

    public List<UserBO> searchContacts(String name);
}

CommonDaoImpl.java
@Repository
public class CommonDaoImpl implements CommonDao {
    @Autowired
    HibernateSessionFactory hibernateSessionFactory;

    @SuppressWarnings("unchecked")
    public <T> Integer save(final T obj){
        //interact wth DB
     }

    public <T> String saveRetString(final T obj){
                    //interact wth DB
     }
    public <T> void delete(final Class<T> type,final String id){
                    //interact wth DB
      }

      @SuppressWarnings("unchecked")
    public <T> T get(final Class<T> type, final String id){
        return (T) hibernateSessionFactory.getSession().get(type, id);
      }

      @SuppressWarnings("unchecked")
    public <T> T merge(final T o){
                    //interact wth DB
      }

      /***/
      public <T> void saveOrUpdate(final T o){
                    //interact wth DB
      }

    @SuppressWarnings("unchecked")
    public <T> List<T> getAll(final Class<T> type) {
                //interact wth DB
      }
    @SuppressWarnings("unchecked")
    @Override
    public List<UserBO> searchContacts(String name) {
                    //interact wth DB
    }

}

web.xml
   <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <!-- It is need for spring security to intercept URL -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern> <!-- We are going to send every rquest to this filter -->
    </filter-mapping>
    <!-- It will tell where the spring security configuration xml is -->

    <!-- Bootstraps the root web application context before servlet initialization -->
    <!-- It will bootstrap our spring security -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
    <listener-class>
      org.springframework.security.web.session.HttpSessionEventPublisher
    </listener-class>
  </listener>
    <servlet>
        <servlet-name>taskManagementServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/servlet-config.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>taskManagementServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>taskManagementServlet</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>taskManagementServlet</servlet-name>
        <url-pattern>/pdfs/**</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>1</session-timeout> <!-- THis specify timeout in minutes -->
    </session-config>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

After added the following load on startup(refer below code),
<servlet>
        <servlet-name>taskManagementServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/servlet-config.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>

Getting the following exception,
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) ~[spring-context-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) [spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765) [catalina.jar:7.0.23]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260) [catalina.jar:7.0.23]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.23]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525) [catalina.jar:7.0.23]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515) [catalina.jar:7.0.23]
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_18]
    at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_18]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_18]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_18]
    at java.lang.Thread.run(Thread.java:619) [na:1.6.0_18]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140) ~[spring-web-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ~[spring-beans-3.2.6.RELEASE.jar:3.2.6.RELEASE]
    ... 22 common frames omitted
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/config/security-config.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/security-config.xml]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:140)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
    ... 22 more
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/TaskManagement] startup failed due to previous errors
Aug 22, 2015 12:40:19 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext

Aug 22, 2015 12:40:19 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext


text:
Q: What kind of data should never go into session? What kinds of data should never be kept in a session?

A: I really wish it was clearer what kind of session you mean. Depending on the answer, I can come up with a couple:

*

*Passwords of any sort

*Large amounts of data, especially 4 GB+ on a 32-bit OS (guaranteed out of memory if it has to be loaded into RAM)

*Executable code

*Raw SQL

*Swear words

*Things likely to get government agencies angry ("Free Tibet" in China, threats to the president in the US)

*Your bank account PIN or credit card number

*A rabid badger.  Actually, ANY kind of badger.

A: If possible, store nothing in the Session.  It is an unreliable way to maintain state, especially if you need to move to a web farm.  Also, I believe it encourages poor design.  HTTP is stateless, and web sites should be designed in a way where you assume that for any request, you could be starting over from scratch.

A: COM or complex objects.
This link can also be useful: ASP.NET 2.0 Performance Inspection Questions - Session State

A: This answer is for PHP Sessions.
If you mean $_SESSION, well it is stored on the hard drive, so it is not immediately available in anything like the cookies.
However, on a shared host, it can sometimes be trivial to access session files from other websites.
I would not store anything in the session you wouldn't want anyone else on your shared host to see.

A: This can be a pretty subjective question. Anything that's serializable can be stored in session, technically. But there are definitely scenarios where you don't want to add things to session. Complex objects, objects that have large collections as properties, etc. All these things are serialized into byte arrays and kept in memory (for InProc Session State) and then deserialized when needed in code again. The more complex the object, the more resource intensive it can get to go back and forth.
Depending on how many users you have, you may wish to limit the number of items that go into session and perhaps use ViewState or other means of persistence. If it's truly something meant for multiple pages, then it's probably a good candidate for session. If it's only used in a page or two, then ViewState, QueryString, etc. may be better.

A: I would not put the session inside the session also!

A: You can store anything in Session as long as you keep the SessionMode="InProc" in the web.config. This stores any session data in the web server's memory in a user specific context.
However, if you want to scale up one day and run your web app in a farm, you will have to use another SessionMode. Then you can't any longer store objects of complex types that are not serializable (unfortunately, dictionaries are a common candidate) and you will have to change your design.

A: *

*DataSets: Serialising a dataset to store in session can take up an order of magnitude more memory than the dataset itself (i.e. a 1MB dataset can need 20MB to serialise/deserialise, and it does that on every request).

*Controls: Storing controls (and their collections) in session means that ASP.NET can't clean them up properly at the end of the page request, leading to memory leaks.

See Tess Ferrandez's blog for other examples of things you should never put in session, along with reasons why.

A: Stock tips, pirated CDs, full-length movies (except "Clerks", that movie was awesome), analog information, ...
This question seems kind of vague -- I can think of countless kinds of information that shouldn't be stored in the session!


text:
Q: Start up script generated by Gradle can't find main java class The start up script generated by Gradle can't find the main class when I run it:
./ApplicationName.bat
Error: Could not find or load main class packageName.NameOfMainClass

My build.gradle file looks something like this:
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.8.2/userguide/building_java_projects.html
 */

plugins {
    // Create jar file
    id 'java'

    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use JCenter for resolving dependencies.
    jcenter()
    // Maven
    mavenCentral()
}

def jmockitVersion = '1.49'

dependencies {
    // JMockit
    testImplementation "org.jmockit:jmockit:$jmockitVersion"

    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:29.0-jre'

    //other dependencies not shown
    .
    .
    .
}

test {
    jvmArgs "-javaagent:${classpath.find { it.name.contains("jmockit") }.absolutePath}"
}

application {
    // Define the main class for the application.
    mainClass = 'packageName.NameOfMainClass'
}

jar {
   archivesBaseName = 'ApplicationName'
   archiveVersion = '0.0.1-SNAPSHOT'
   manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version,
                   'Main-Class': 'packageName.NameOfMainClass'
    }
}

run {
   standardInput(System.in)
}

The generated jar's MANIFEST.MF looks like this:
Manifest-Version: 1.0
Implementation-Title: Gradle Quickstart
Implementation-Version: 0.0.1-SNAPSHOT
Main-Class: packageName.NameOfMainClass

The file structure is something like this:
applicationName\
    gradlew
    gradlew.bat
    settings.gradle
    README.md
    .gradle\
    gradle\
    applicationName\
        build.gradle
        build\
        src\
            main\
                java\
                    packageName\
                        NameOfMainClass.java
                        OtherClass.java
                        .
                        .
                        .
                resources\
            test\
                java\
                    packageName\
                        SomeTest.java
                        .
                        .
                        .
                resources\

I'm new to Gradle. I've tried a number things in other posts, that may or may not be similar, but with no success.


text: Q: How to print to pdf multiple sheets for tableau workbook saved in a local drive programatically I have a tableau workbook saved in my local drive and i manually open the workbook and select multiple sheets from it and print the sheets as pdf from file menu. I want to automate that task. checked tabcmd but it only works with tableau server.


text:
Q: How to join a VAR with a table from the model? I have a VAR (named VarTable), which is just a transformation of an original table in the model.
Then I want to return it as:
RETURN ADDCOLUMNS(VarTable,  LOOKUPVALUE(Employee[Name],Employee[Key], VarTable[Key])
But it doesn't work... neither does using 'RELATED'.
My question is: how do you join two tables, (one from the model and the other one being just a VAR created inside the measure/calculated table)?


text:
Q: How to setup visitor variables in Google Analytics I don't quite get how to use the visitor level variables. Do I need to put them in some sort of condition to determine if the visitor is a repeat visitor, or do I just use the _SetCustomVar method like I would the page or session variables?

A: Google Analytics will determine if someone is the same visitor based on the presence of its cookies. So, to the extent that GA is able to differentiate Visitors (ie, same computer, same browser as past visits without having removed cookies), the custom variable will persist.
All you need to do to set a variable as 'visitor' is to set the fourth parameter (scope) to 1.
Just be sure to set the custom variable before your page-view call, otherwise the custom variable data doesn't get sent to Google.


text:
Q: Alarm created thru AlarmManager is not running after 25days (= 2^31 - 1 = 2147483647 milli seconds) Background:
I have an Android application running on Android 7.1. A reccurring task is set using AlarmManage to perform a task every day at a specific time. code is like below:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
long startInMs = getComing9AM();
Intent intent = ...; //an intent to be run when alarm time is up.
PendingIntent ScheduledIntent = PendingIntent.getBroadcast(context, id, intent, 0);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startInMs, ScheduledIntent);

private long getComing9AM(){
    long now = System.currentTimeMillis();
    long today = getToday9AM();
    return (now < today? today:getTomorrow9AM());
}

private long getToday9AM(){
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    return calendar.getTimeInMillis();
}

private long getTomorrow9AM(){
    return getToday9AM() + 7 * 24 * 3600 * 1000;
}

*The android device is not a mobile phone, but a small box. Under normal operation, only power cable is plugged with WIFI connectivity.

Problem Description:

*

*The scheduled task works pretty well every day. After three weeks or more, the task no longer running.

*All other functionality still working, including MQTT client communication, IO operations.

Analysis result:

*

*After checking the pattern of the problem, it is found that around 25 days from last boot up the task will not work. Being a math-geek who is sensitive to number, "25 days" = 2,160,000 second = 2,160,000,000 ms. And this value is very closed to 2^31-1 (Integer.MAX_VALUE), which is equivalent to 24.85 days.

*HDMI cable is plugged to the device, the screen shows no input.

*Even a new scheduled task is assigned after 25days (thru HTTPS), the task will not be executed.

*After a USB device (i tried a mouse) is plugged to the device, Android is wake up (the screen has a display). And the Android has been awakened, the task can be run normally every day until the next 25 days.

*using ADB to check the Android setting, I can only find one parameter value is met with Integer.MAX_VALUE. That is (adb shell dumpsys power):
mMaximumScreenOffTimeoutFromDeviceAdmin=2147483647 (enforced=false)
Screen off timeout: 2147483647 ms

*Based on finding #5, I have tried to set the screen off timeout to 60000 trying to reproduce the problem. But the task can still be run as usual.

*It should not be related to Doze mode as the device is always charged and no battery with it.

*(New finding) The value of "mWakefulness" in dumpsys power is Asleep after 24.85days. Before 24.85days this value should be Awake.

*(New finding) Given that wWakefulness=Asleep arelay, the "mLastSleepTime"=now - (startupTimestamp + 24.85day).
Seek for advice:

*

*I would like to have some direction to further investigate the problem.

*I would like to know if there is a way to simulate the waking up event within the application? (as a workaround before finding the root cause).

A:
I would like to have some direction to further investigate the problem.

I would find ways to unit test your code to ensure it works fine. You can fire intents regularly and try that. Either in a Unit test or via adb. You mentioned "via https" but perhaps you need to go straight to the "metal" and trigger the methods yourself to test.

I would like to know if there is a way to simulate the waking up event within the application? (as a workaround before finding the root cause).

Your device is not a phone, so I'm not sure if it's capable of receiving Firebase Push Notifications (or any form of), since you'd need Google Play services for this, and that comes with another bag of things, but I would try to manually control these events (externally) to make sure your code is not causing issues. Does making a "beep" (or printing to logcat) every day at 9am still work?
If AlarmManager somehow breaks periodically after NN days, then something is either really broken (it would be strange to be honest, 7.1 is rather old and has been in use for a long time, someone would have said something about this, I hope(?)), or your code is misbehaving.
Start isolating things, can you create a simple app that ALL it does is print a log ever day at 9:30 am. Does it still work?
Or would work manager help you here or would there be other dependencies that you cannot use/have? There are tradeoffs of course, for WorkManager is not the same as AlarmManager and is way more constrained.

Even a new scheduled task is assigned after 25days (thru HTTPS), the task will not be executed.

This is also puzzling, since it appears the AlarmManager stopped working and receiving work altogether. Does the job work if you broadcast the intent manually via adb at that point? Do you have more than one device of these? does it happen with all?
This is a very interesting problem, I wish I had more concrete stuff, but very few people will know the inner workings of the AlarmManager in relation to all the new ways google is trying to "save battery" on phones.
setExactAndAllowWhenIdle is described as:

Unlike other alarms, the system is free to reschedule this type of alarm to happen out of order with any other alarms, even those from the same app.  This will clearly happen when the device is idle (since this alarm can go off while idle, when any other alarms from the app will be held until later), but may also happen even when not idle. Note that the OS will allow itself more flexibility for scheduling these alarms than regular exact alarms, since the application has opted into this behavior.  When the device is idle it may take even more liberties with scheduling in order to optimize for battery life.

Could the OS allowing itself to be flexible in some form and ignoring your alarm? hmmm not sure.
Final comment, have you taken a look at the AlarmManager's source code? Perhaps there's a hint in there.
In the end, this long post (that should have been a comment) doesn't really give you a solution, just an open place for me to dump ideas. :) I'll update if need; please let us know what you find :)
As a side-comment: I'd test if you can use Gradle 4.x and have access to Java 8 APIs for java.time (much better than calendar and even util.Date), or try to leverage the (now archived/deprecated but still usable for some time until Gradle 4.x is "streamlined") ThreeTenABP abstraction from Wharthon to use the same Java8 APIs (the migration from ThreeTen to java.time is really a 10 minute find/replace to change the imports).
In short, you can replace all that calendar nonsense with
val tomorrowAt9Am = ZonedDateTime.now().plusDays(1).withHour(9).withMinute(0).withSecond(0).toEpochSecond()
EDIT: the last two points you found out (mWakefulness) are very interesting, i'll keep looking. In the meantime, I found a few instances of said variable in the Android codebase. The most interesting one is this one from the AttentionDetector (what a name); feel free to browse all the results

A: I have studied the source code of PowerManagerService.java in Android 7.1.2. I could see the "sleep mode" due to "idle screen timeout" can be skipped by setting "mStayOn" to a non-zero value.
So, I tried to set this value to 1 (skip if AC power is connected) on a device that is going to "asleep" in 3 days. Tada, the scheduled intent can now be executed upon the task time up. However, I still could not find the reason why time-up task not being executed when Android is in asleep mode. Maybe just understand that as a rule and that's it.
====
For item 6 I have mentioned, the value could not be modified as the PowerManagerService.java used in my embedded system has already been modified since day one I got the source code. The modification is to return MAX integer value all the time regardless of the parameters I have assigned thru adb.


text:
Q: Programmatically find the region of an azure function I have a service that invokes the azure function API using the Managed Service Identity authentication token. I want to be able to invoke the correct regional azure function based on the region from code. So for example, if the region I pass is useast2, I need to invoke the azure function that resides in useast2 region programmatically using C#. How can I do this?
Thanks

A: You can use this line of code for find the regions name. REGION_NAME regions name of the app.
Environment.GetEnvironmentVariable("REGION_NAME")

In my case, I am create a webjob for find the region using below code.
using System;
using System.Threading;

namespace CheckErrorOrLog
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Azure web job Start");
            for(int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(2 * 60 * 1000);
                Console.WriteLine(Environment.GetEnvironmentVariable("REGION_NAME"));
            }
        }
    }
}

Output

You can find other environment variable on these Microsoft Document App Environment


text:
Q: Angular 2 Multiple modules with names that only differ in casing The following warning occurs during compilation:

WARNING in ./src/app/state/actions/userClass.ts There are multiple
  modules with names that only differ in casing. This can lead to
  unexpected behavior when compiling on a filesystem with other
  case-semantic. Use equal casing. Compare these module identifiers:
  * /Users/smp/Projects/training3/node_modules/@angularclass/hmr-loader/index.js!/Users/smp/Projects/training3/node_modules/awesome-typescript-loader/dist/entry.js?{configFileName:
  "tsconfig.webpack.json"}!/Users/smp/Projects/training3/node_modules/angular2-template-loader/index.js!/Users/smp/Projects/training3/node_modules/angular-router-loader/src/index.js?loader=system&genDir=compiled&aot=false!/Users/smp/Projects/training3/src/app/state/actions/UserClass.ts
      Used by 1 module(s), i. e.
      /Users/smp/Projects/training3/node_modules/@angularclass/hmr-loader/index.js!/Users/smp/Projects/training3/node_modules/awesome-typescript-loader/dist/entry.js?{configFileName:
  "tsconfig.webpack.json"}!/Users/smp/Projects/training3/node_modules/angular2-template-loader/index.js!/Users/smp/Projects/training3/node_modules/angular-router-loader/src/index.js?loader=system&genDir=compiled&aot=false!/Users/smp/Projects/training3/src/app/features/portal/content/tabs/userclasses/userclasses.component.ts
  * /Users/smp/Projects/training3/node_modules/@angularclass/hmr-loader/index.js!/Users/smp/Projects/training3/node_modules/awesome-typescript-loader/dist/entry.js?{configFileName:
  "tsconfig.webpack.json"}!/Users/smp/Projects/training3/node_modules/angular2-template-loader/index.js!/Users/smp/Projects/training3/node_modules/angular-router-loader/src/index.js?loader=system&genDir=compiled&aot=false!/Users/smp/Projects/training3/src/app/state/actions/userClass.ts
      Used by 3 module(s), i. e.
      /Users/smp/Projects/training3/node_modules/@angularclass/hmr-loader/index.js!/Users/smp/Projects/training3/node_modules/awesome-typescript-loader/dist/entry.js?{configFileName:
  "tsconfig.webpack.json"}!/Users/smp/Projects/training3/node_modules/angular2-template-loader/index.js!/Users/smp/Projects/training3/node_modules/angular-router-loader/src/index.js?loader=system&genDir=compiled&aot=false!/Users/smp/Projects/training3/src/app/state/effects/userClass.ts

A: The names of my files where fine.  This issue popped up because in one of my imports I capitalized UserClass:
import * as userClassActions from '../../../../../state/actions/UserClass';

After changing the import to the following the error went away:
import * as userClassActions from '../../../../../state/actions/userClass';

A: If you are coding with Visual Studio Code, it may happen that it will sometimes add path with capital letter and other times with a lower letter.
In my case I was getting the error because of Angular Material components were imported from '@angular/material' in some files and in (at least 2) other files from '@angular/Material'.
Lower-casing '@angular/Material' removed the warning.
Hope this helps.

A: I was getting the same error because of a mistake I did while writing import.
Check if you've written somewhere --> import { RouterModule } from '@angular/Router';
Now, change it to --> import { RouterModule } from '@angular/router';
This solved my problem. Hope it works for you too.
See the images below for more clarity

*

*https://i.stack.imgur.com/wS1nh.png

*https://i.stack.imgur.com/GyDGs.png

A: I was facing this issue while implementing angular 4 App with asp.net core 2.0 and web pack.
This issue can occur if you import service or class with two different "./" or "../" relative path notation.
Import code in NavMenuComponent.
import { SampleService } from '../../services/sample.service';

Changing with following code the error was resolved
import { SampleService } from './../../services/sample.service';

Learn more about GitHub discussion

A: check if you have imported twice.

A: This can also be caused by entries in your webpack config:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'development'
  , entry: {
    crm: './Scripts/app/crm/crm.router.js'
    , labels: './Scripts/app/labels/labels.router.js'
    , admin: './scripts/app/crm/admin/admin.router.js'
  }
  , output: {
    filename: '[name]Bundle.js'
    , path: path.resolve(__dirname, 'dist')
  }
///...
};

Notice the casing of scripts vs Scripts in the entry section.

A: I got that warning after renaming the file to upper case intentionally.
After moving the specific file into another folder and back to the original the warning was gone.
(I use VSC with some angular extensions that do the updating of imports when moving files)

A: I had a problem like that, and the solution was to create one subfolder in which you put your problem component.
So instead of:
import {EventsComponent} from './Shared/Components/events/events.component';

Do something like:
import {EventsComponent} from './Shared/Components/About Event/events/events.component';

A: One of annoying possible cause of the problem: mixed upper and lowercases in components path - make it same. For example,
import {EventsComponent} from './events/events.component';
import {OtherComponent} from './Events/other.component';


text:
Q: Android how to store a "string" on a webpage? So I want to store a string on my website and then have my app download it, so I could use it in a layout. How could I do that? I there a way I can take html files and have android read that text? or can I store a .txt and have android convert that to a string?
Thanks

A: If I understand you correctly, you could just put the string inside of a file that your web server will serve up for you (maybe omit the extension altogether).  You can then download it from an android app using the file's url.
It seems like you might want to look into JSON, it will facilitate storing structured data instead of just a string.
Here is an example of downloading a url from an Android program.


text:
Q: Best ways to kill shielded wallers as a demonhunter I am playing a Demonhunter and can kite a lot of the champion combos. Shielded Wallers however, are my gordian knot. I have no idea how to kill them and usually just try to walk around them. What is the most effective Skill combo to kill them? Kiting seems to be impossible...

A: Using the Templar companion will have the champions focusing on him while you kill at range. Even if the shields are up, you can wait it out at range while the Templar sits there and takes a beating.
As far as a skill set, kiting is possible.
Hungering arrow is your friend because you don't really need to aim, but if you do have better aim, then bola shot can be more beneficial because it will damage more targets at a time.
Elemental Arrow + Frost rune will slow them down a lot as well. (This pairs really well if you have the Cull the Weak skill). You can also use rapid fire or chakrams here as well, depending on skill level.
Caltrops with either Torturous Ground (stun), or Hooked spines (increased slow) will keep them at a distance from you so you have more time to kite. An alternative would be to use shadow power (self heal on damage done) and pop that when you do get trapped for the few seconds the wall is up. Pump out as many shots as you can to keep your health up and drink a potion if you have to.
Vault is also very useful, not to get away after the walls have been casted, but through them. Yes, you'll take a hit or two, but it's better than dying. If you have elective mode on, you can also take smoke screen to help you not take this damage while jumping through them.
Sentry or spike trap will help as a third skill as they will do damage to them when the shields are down and you're busy kiting.
Rain of vengance + stampede is a very nice combo to use when their shields are down, you don't have to focus on running away, but to just stand there and fire away.
Edit:
After a bit more playing around, smoke screen is also a very useful tool to make use of. You can use it in place of vault to run through the enemies after you've been trapped.

A: Smoke screen is your weapon of choice in all champion/elite encounters act 3 nightmare and above. as a demon hunter the game is relatively easy mode up to this point with your incredible snares and stuns, but against enemies such as you mention im sure youre finding it just doesnt cut it. (i actually found by the way that most enemies -excluding story bosses- up until late hell difficulty were succeptable to your 40% fear chance on elemental arrow for a bit of fun watching non shielded enemies flee in terror) equip your SS with the lingering fog rune and get prepareation with the focussed mind rune, this will allow you to go invisble roughly 6 times, for 3 seconds at a time, with 1 second cd interals - usually sufficient to extend your kiting distance as they will stop running after you and engage your templar while you are invisible (i use elemental ball lightining as something i dont have to aim particularly well and effectively dmaages whichever of the champions arent shielded, but any weapon would technically work with this)
this strat is tried and tested to inferno difficulty, im currently farming nightmare because im sure no matter the strat im just gonna need better gear to survive.

A: Here is my aproach, it is somewhat an abuse but it works fine so far.
Assuming you have a kiting path that is long and free of other mobs. You use the following abilities:

*

*Hungering Arrow - Devouring Arrow

*Elemental Arrow - Nether Tentacles

*Smoke Screen - Special Recipe

*Preperation - Backup Plan

*Caltrops - Torurous Ground

*Shadow Power - Shadow Glide

As passive abilities I use Tactical Advantage, Sharpshooter, Archery. It is important to use something similar because you cannot switch your abilities otherwise you loose your buff. These allow you to kill a huge variant of Elites.
Here is my strategy:
Buy boots that increase your walking / running speed at least by 10%.

*

*Place a Caltrops, wait for regeneration. Spam Nether Tentacles for about 5-6 times, run away.

*Repeat until Elites close in OR you hit a wall then SS.

*Place Caltrops again and repeat.

*If your hatred is low use Hungering Arrow or run away 2 times with SS, so you are out of range of the Elites. Regenerate everything, but do not take mare than about 10 seconds.

*Use Preperation if your Discipline is low.

*If you know that you have only Discipline for 2 SS try to run away shooting only once every 5 seconds to remain in combat. Should the Elites close in too fast then use 2 SS to get away and regenerate about 15 seconds. This way Preperation is about 1/3 - 2/3 done with you having some Dicipline.

This strategy relies on you being faster than usual so you can outrun or at least keep the Elites on distance without shooting. Furthermore you keep on having enough Dicipline all the time, so you do not run out of juice.
Wallers do not wall full screen, this ability has a range (about 2/3 of the screen). So if you stay out of range running away to regenerate you should have no problem.
Should you run out of space invest in SS to change direction and run towards and past the Elites, this way you have about the same kiting path again. Usually the wallers will place walls behind you as you run towards them.


text:
Q: Is it better to use select or loop through an array of records in Rails? My goal is to write the query below in the cleanest, most efficient way possible and minimize hitting the DB. Appreciate any guidance in advance.
I have retrieved some records that belong to a user, like below:
english_shows = @user.shows.where(language: 'english')

Let's say the shows belong to different categories (using a foreign key), so it looks like below:
<ActiveRecord::Relation [
  <Show id: 1, category_id: 1, title: 'Rick and Morty'>,
  <Show id: 2, category_id: 2, title: 'Black Mirror'>,
  <Show id: 3, category_id: 3, title: 'Stranger Things'>,
  <Show id: 4, category_id: 3, title: 'Game of Thrones'>,
  ...
]

If I want to get the titles of the shows for each category, I know I can use select like this. The same thing can be done with where, but this would cause an additional DB call. ([Edit] Actually, both would hit the DB twice).
# Using select
cartoons = english_shows.select { |show| show.category_id == Category.find_by(name: 'cartoon').id}.pluck(:title)

# Using where
cartoons = english_shows.where(category_id: Category.find_by(name: 'cartoon').id)pluck(:title)

However, the select method would still result in multiple lines of long code (in my actual use case I have more category types). Is it cleaner to loop through the records like this (taken from this SO answer)?
cartoons, science_fiction, fantasy = [], [], []
@cartoon_id = Category.find_by(name: 'cartoon')
@science_fiction_id = Category.find_by(name: 'cartoon')
@fantasy_id = Category.find_by(name: 'cartoon')

english_shows.each do |show|
  cartoons << show if show.category_id == @cartoon_id
  science_fiction << show if show.category_id == @science_fiction_id
  fantasy << show if show.category_id == @fantasy_id
end

A: Try this:
english_shows
  .joins(:category)
  .select('shows.*, categories.name as category')
  .group_by(&:category)


text:
Q: Google Translation API V3 not supporting language pair other then Russian Supporting : English to Russian
Not supporting : English to Japanese
Not supporting : English to Hindi
Not supporting : English to french
Request :
{
"sourceLanguageCode": "en",
"targetLanguageCode": "ar",
"contents" : "Medical Clothing Market by Drug Class ",
"glossaryConfig": {
"glossary" : "projects/XXXXXXXXXXXX/locations/us-central1/glossaries/G7L"
}
}
curl -X POST -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" -H "Content-Type: application/json; charset=utf-8" -d @request-with-glossary.json "https://translation.googleapis.com/v3/projects/XXXXXXXXXXXX/locations/us-central1:translateText"
{
"error": {
"code": 400,
"message": "Unsupported language pair.; Failed to initialize a glossary.",
"status": "INVALID_ARGUMENT"
}
}
Any Idea why does this happens, am I missing anything in the service settings?
I've checked with the doc bu there is no solution.
Other API are working fine, all roles, permissions, key has been set successfully, Tried with multiple language pairs which support translation API's but not working with my case.


text:
Q: Bounded (from below) harmonic functions from $\mathbb R^2 \setminus \{0\}$
Let $M \in \mathbb R$ be a real number and $u\colon \mathbb R^2 \setminus \{0\} \to [M, +\infty)$ be an harmonic function. Then it is constant. Show that this is no longer true in higher dimensions.

The second part is easy: if $n\ge 3$ it suffices to take
$$
u(x)=\frac{1}{\vert x \vert^{n-2}} \ge 0
$$
which is known to be harmonic, since it is - up to multiplicative constants - the fundamental solution.
I do not know how to solve the first part of the problem. There is a hint: "Use the logarithm" but I do not understand it. Can you help me, please? Thanks.

A: It depends highly on how much you know about Harmonic functions and its relation with Complex Analysis. For example, are you familiar with Liouville's theorem, that states that every Harmonic function that is defined on all of $R^{n}$ and is bounded from above or below is constant.
Defining the function $v = u - M$, we have a positive function that is harmonic if and only if $u$ is. Considering with $R^{2}$ $C$, we can consider the function $z \mapsto v(e^{z})$ that is defined on all of $C$. If you want to avoid complex numbers, consider the function $(x_{1},x_{2}) \mapsto v(e^{x_{1}} \cos(x_{2}),e^{x_{1}} \sin(x_{2}))$. This function is positive and Harmonic on $R^{2}$ and therefore constant, due to Liouville's theorem.


text:
Q: Appropriateness of ANOVA after k-means cluster analysis The notification after the ANOVA table after K-means analysis indicates that significance levels should not be looked at as the test of equal means, as the cluster solution has been derived based on Euclidean distance to maximize the distance.
What test should I use to show whether the means of the clustering variables differ among the clusters? I have seen this warning in k-means outputs' provided ANOVA table, but in some references I see that post-hoc ANOVA tests are run. Should I ignore k-mean ANOVA outputs and run one-way ANOVA with post-hoc tests and interpret them in a traditional way? Or can I only imply about magnitude of F value and which variables contributed more to difference?
Another confusion is that clustering variables are not normally distributed violating assumption of ANOVA, then I could use Kruskal-Wallis non-parametric test, but it has assumption about the same distributions. The inter-cluster distributions for the specific variables do not seem the same, some are positively skewed, some are negatively...
I have 1275 large sample, 5 clusters, 10 clustering variables measured in PCA scores.

A: Your real problem is data snooping. You can't apply ANOVA or KW if the observations were assigned to groups (clusters) based on the input data set itself. What you can do is to use something like Gap statistic to estimate the number of clusters.
On the other hand, the snooped p-values are biased downward, so if ANOVA or KW test result is insignificant, then the "true" p-value is even larger and you may decide to merge the clusters.

A: I think you could apply such an approach (i.e. using the statistics, such as F-statistics or t-statistics or whatever), if you toss out the usual null distributions.
What you'd need to do is simulate from the situation in which your null is true, apply the whole procedure (clustering, etc), and then calculate whichever statistic each time. Applied over many simulations, you would get a distribution for the statistic under the null against which your sample value could be compared. By incorporating the data-snooping into the calculation you account for its effect.
[Alternatively one could perhaps develop a resampling-based test (whether based on permutation/randomization or bootstrapping).]

A: No!
You must not use the same data to 1) perform clustering and 2) hunt for significant differences between the points in the clusters. Even if there's no actual structure in the data, the clustering will impose one by grouping together points which are nearby. This shrinks the within-group variance and grows the across-group variance, which biases you towards false positives.
This effect is surprisingly strong. Here are the results of a simulation that draws a 1000 data points from a standard normal distribution. If we assign the points to one of five groups at random before running the ANOVA, we find that the p-values are uniformly distributed: 5% of the runs are significant at the (uncorrected) 0.05 level, 1% at the 0.01 level, etc. In other words, there is no effect. However, if $k$-means is used to cluster the data into 5 groups, we find a significant effect virtually every time, even though the data has no actual structure.

There is nothing special about a k-means or an ANOVA here--you would see similar effects using non-parametric tests or logistic regression and a decision tree, even just taking the min/max.
After you impose some kind of structure on the data, you cannot to test whether some structure exists, since it obvious does!.  As a result, validating clustering algorithms' performance is tricky, particularly if the data are not labelled. However, there are a few approaches to "internal validation", or measuring the clusters' quality without using external data sources. They generally focus on the compactness and separability of the clusters. This review by Lui et al. (2010) might be a good place to start.

A: Not exactly an answer, but a proposal on how one would find the solution.
I was thinking about that cluster problem. The test would require sampling from the full dataset and deriving kmeans and seeing if the same kmeans occurs within a distribution (example with clustergram) from various samples (normally kmeans itself produces different kmeans depending on it's starting point.  An algorithm that hones in on the same kmeans over multiple iterations like clustergram might be more apt). Just as a mean is derived from samples in statistics. But k means has various proportion sizes for its clusters but the point is do the same means appear within a distribution.
But how would one compare the distributions of the various vars in the cluster? Normally coefficients are derived from a covariance matrix (or predictor matrix?) which is based on a given y. This has no y. So im wondering if each cluster could be whitened using zca (or even pca). Something w eigenvalues. Use this to derive some type of meaningful means or coefficients. Else one has a set of means. Then one needs to derive the standard error. The standard error is definately based on the covariance matrix (again substitute pca or zca)? But I'd have to brush up on standard error. I believe standard error is a function of standard deviation but instead of a variance of a sample its a variance of a mean
Edit:
For statistical significance
Use the gap statistic method as discussed here
http://www.datanovia.com/en/lessons/determining-the-optimal-number-of-clusters-3-must-know-methods/#at_pco=wnm-1.0&at_si=609664423560aa01&at_ab=per-2&at_pos=0&at_tot=1
I also recommend this article for a discussion of other related measures
https://medium.com/@haataa/how-to-measure-clustering-performances-when-there-are-no-ground-truth-db027e9a871c


text:
Q: php replace group of double backslash how to replace group of double backslash in a string to *
for example:
\\\\a ->  **a
\\\a  ->  *\a
\\a   ->  *a
\a    ->  \a

I try use both str_replace and preg_replace but it failed at the second case
str_replace('\\', '*', $str);
preg_replace('/\\\\/', '*', $str);

=> `\\\a` -> `**a`

the reason i want to do this is i want something same as Split string by delimiter, but not if it is escaped but
$str = '1|2\|2|3\\|4\\\|4';
$r   = preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $str);
var_dump($r);

give me.
  0 => string '1' (length=1)
  1 => string '2\|2' (length=4)
  2 => string '3\|4\\' (length=6)
  3 => string '4' (length=1)

i expect something like
  [0] => 1
  [1] => 2\|2
  [2] => 3\\
  [3] => 4\\\|4

php 5.4.45-2

A: A literal backslash in PHP single-quoted strings must be declared with 2 backslashes: to print 1|2\|2|3\\|4\\\|4 you need $str = '1|2\\|2|3\\\\|4\\\\\\|4';.
In a regex, the literal backslash can be matched with 4 backslashes.
Here is an updated PHP code:
$str = '1|2\\|2|3\\\\|4\\\\\\|4';
// echo $str . PHP_EOL; => 1|2\|2|3\\|4\\\|4
$r   = preg_split('~\\\\.(*SKIP)(*FAIL)|\\|~s', $str);
var_dump($r);

Result:
array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(4) "2\|2"
  [2]=>
  string(3) "3\\"
  [3]=>
  string(6) "4\\\|4"
}

And to obtain **a from \\a you can thus use
$str = '\\\\a';
$r   = preg_replace('~\\\\~s', '*', $str);

See another demo


text:
Q: How to modify domain in AWS Amplify with rewrite rule? How can I rewrite a URL in AWS Amplify from:
https://a.example.com/path

to:
https://a.b.example.com/path

Given that the domain example.com is variable because the Amplify app uses multiple domains.
That means that the same rule should rewrite from:
https://a.example2.org/path

to:
https://a.b.example2.org/path

A: you can use Amplify's Rewrites and redirects and write your own regex rule. This is explained in here


text:
Q: When to use TCP hole punching technique and why to use it? I am studying the TCP hole punching technique and have got some knowledge from this article: TCP_hole_punching. But I don't understand below part:
      Network Drawing
      Peer A ←→ Gateway A ← .. Network .. → Gateway B ←→ Peer B

      Types of NAT
      The availability of the TCP-hole-punching technique depends
      on the type ofcomputer port allocation used by the NAT. When
      two peers, A and B, instantiate TCP   connections by binding
      to local ports Pa and Pb, respectively, **they need to know
      the remote  endpoint NAT port in order to make the connection**.

Here are some questions, could somebody help explain? Any help or suggestion will be greatly appreciated!!
Q1. Suppose we have a client app running behind NAT1 and a server app
    running behind NAT2. They will have messaging and file transfer communication.
    The pattern will be the server listens and accepts connection
    from the client. Do they need to use the TCP hole punching to keep the tcp
    connection work?
Q2. Is the TCP hole punching technique necessary only when it's peer to peer
    communication and both parties are connecting to each other (e.g., 2x CONNECT(), no LISTEN(), ACCEPT(), etc.)?
Q3. In the above text, what does it mean of "they need to know the remote  endpoint NAT port in order to make the connection"? Why do they need to know the remote endpoint NAT port?Don't they only need to know the local port of the other machine?
For example, suppose the pair are (ClientA, publicIPA, LocalPortA), (ClientB, publicIPB, LocalPortB). If the ClientA wants to communicate with ClientB via TCP, it may do something like this:
         clientBAddr.port = LocalPortB;
         clientBAddr.ip = inet_addr(publicIPB);
         connect(fdA, clientBAddr,...);

why would it need to know information such as NATPortA and NATPortB? Is there any problem if the clientA and clientB don't care about the NATA and NATB?

A: Since this post is reopened and nobody leaves an answer until this moment, I would like to answer it myself based on this article: Peer-to-Peer Communication Across Network Address Translators
About Q1, yes. Without mechanism like hole-punching, the packets one side use to sync with the other side will be dropped by the routers.
About Q2, no exactly. Listening sockets won't work directly. You need other tricks.