答:
Ctrl+H

Find what: ^\d+,\d+\K,(\d+),

Replace with: $1

check Wrap around

check Regular expression

Replace all

Explanation:

```<code>^           : begining of line
  \d+       : 1 or more digits
  ,         : a comma
  \d+       : 1 or more digits
  \K        : forget all we have seen until this position
  ,         : a comma
  (\d+)     : group 1, 1 or more digits
  ,         : a comma
</code>```

You may use [^,] instead of \d if you have other character than digits.

Replacement:

```<code>$1          : content of group 1 (ie. the digits between 2nd and 3rd comma)
</code>```

Result for given example:

```<code>8213201711,77429890,5d810ffc6
9801201711,103088818,5d810ffc
8113201711,102829857,5d810ffb
8113201711,104186726,5d810ffc
8101201711,86337068,5d810ffb1
8205201711,77137917,5d72788c9
</code>```

Title: Notepad++ - Remove second and third comma in a csv in one shot

Body:
i have a csv file having thousands of lines of data with comma delimited, i need to remove 2nd and 3rd commas from those lines

example below

8213201711,77,429,890,5d810ffc6
9801201711,103,088,818,5d810ffc
8113201711,102,829,857,5d810ffb
8113201711,104,186,726,5d810ffc
8101201711,86,337,068,5d810ffb1
8205201711,77,137,917,5d72788c9

I need

8213201711,77429890,5d810ffc6
9801201711,103088818,5d810ffc
8113201711,102829857,5d810ffb
8113201711,104186726,5d810ffc
8101201711,86337068,5d810ffb1
8205201711,77137917,5d72788c9

I tried to find

^([^,]*,[^,]*),(.*)$

and replace with

\1\2

but, its removing only 2 occurrence

Body:
Ctrl+H

Find what: ^\d+,\d+\K,(\d+),

Replace with: $1

check Wrap around

check Regular expression

Replace all

Explanation:

^           : begining of line
  \d+       : 1 or more digits
  ,         : a comma
  \d+       : 1 or more digits
  \K        : forget all we have seen until this position
  ,         : a comma
  (\d+)     : group 1, 1 or more digits
  ,         : a comma

You may use [^,] instead of \d if you have other character than digits.

Replacement:

$1          : content of group 1 (ie. the digits between 2nd and 3rd comma)

Result for given example:

8213201711,77429890,5d810ffc6
9801201711,103088818,5d810ffc
8113201711,102829857,5d810ffb
8113201711,104186726,5d810ffc
8101201711,86337068,5d810ffb1
8205201711,77137917,5d72788c9


来源: stackexchange

问:
php  how to pass value to another page when click the href? and how to retrieve the value from another page?
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

```<code>                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '<label class="label1">' . $row->name . '</label><br><br>';
                    echo '<a href="#"><img src="' . $row->image . '" class="poster"></a>';
                    echo '<div class = "section3"><a href="synopsis.php?id="' . $row->id . '" >asd</a>&nbsp &nbsp <a href="">Buy Now</a>';
                }
            }

            ?>
</code>```

答:
You can use _GET of php for this, however there are many methods exist.

First set value in href url as below :

```<code><a href="?key=my_value" .....
</code>```

Then you can acces value in target php as below:

```<code><?php echo  $_GET['key'];//displays my_value
</code>```

ContentLicense: CC BY-SA 3.0

Title: php <a href> how to pass value to another page when click the href? and how to retrieve the value from another page?

Body:
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '' . $row->name . '

';
                    echo 'image . '" class="poster">';
                    echo '
id . '" >asd&nbsp &nbsp Buy Now';
                }
            }

            ?>

Body:
You can use _GET of php for this, however there are many methods exist.

First set value in href url as below :

<a href="?key=my_value" .....

Then you can acces value in target php as below:

<?php echo  $_GET['key'];//displays my_value


问:
How do I display a ratio in Excel in the format A:B?
I have an Excel spreadsheet of data like:

```<code>ColumnA ColumnB
33        11
25        5
6         4
</code>```

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

```<code>ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2
</code>```

How can this be done?

答:
You are looking for the greatest common divisor (GCD).

You can calculate it recursively in VBA, like this:

```<code>Function GCD(numerator As Integer, denominator As Integer)
  If denominator = 0 Then
    GCD = numerator
  Else
    GCD = GCD(denominator, numerator Mod denominator)
  End If
End Function
</code>```

And use it in your sheet like this:

```<code>   ColumnA   ColumnB   ColumnC
1  33        11        =A1/GCD(A1; B1) & ":" & B1/GCD(A1; B1)
2  25         5        =A2/GCD(A2; B2) & ":" & B2/GCD(A2; B2)
</code>```

It is recommendable to store the result of the function call in a hidden column and use this result to avoid calling the function twice per row:

```<code>   ColumnA   ColumnB   ColumnC        ColumnD
1  33        11        =GCD(A1; B1)   =A1/C1 & ":" & B1/C1
2  25         5        =GCD(A2; B2)   =A2/C2 & ":" & B2/C2
</code>```

OwnerDisplayName: Vincent

ContentLicense: CC BY-SA 4.0

Body:
I have an Excel spreadsheet of data like:

ColumnA ColumnB
33        11
25        5
6         4

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2

How can this be done?

LastEditorDisplayName: Vincent

Body:
You are looking for the greatest common divisor (GCD).

You can calculate it recursively in VBA, like this:

Function GCD(numerator As Integer, denominator As Integer)
  If denominator = 0 Then
    GCD = numerator
  Else
    GCD = GCD(denominator, numerator Mod denominator)
  End If
End Function

And use it in your sheet like this:

   ColumnA   ColumnB   ColumnC
1  33        11        =A1/GCD(A1; B1) & ":" & B1/GCD(A1; B1)
2  25         5        =A2/GCD(A2; B2) & ":" & B2/GCD(A2; B2)

It is recommendable to store the result of the function call in a hidden column and use this result to avoid calling the function twice per row:

   ColumnA   ColumnB   ColumnC        ColumnD
1  33        11        =GCD(A1; B1)   =A1/C1 & ":" & B1/C1
2  25         5        =GCD(A2; B2)   =A2/C2 & ":" & B2/C2

OwnerDisplayName: Tomalak

ContentLicense: CC BY-SA 2.5


问:
ThreadFactory usage in Java
Can someone briefly explain on HOW and WHEN to use a ThreadFactory? An example with and without using ThreadFactory might be really helpful to understand the differences.

Thanks!

答:
Some inner workings

The topic is covered quite well except for some inner works that are not easily visible.
While creating a thread w/ the constructor the newly created thread inherits current threads:

ThreadGroup (unless supplied or System.getSecurityManager().getThreadGroup() returns arbitrary ThreadGroup) - The thread group on its right own can be important in some cases and can result in improper thread termination/interruption. The ThreadGroup will stand as default exception handler.

ContextClassLoader - in managed environment that should not be a great issue since the environment shall switch the CCL, but if you are to implement that - keep it mind. Leaking the caller's CCL is quite bad, so is the thread group (esp. if the threadGroup is some subclass and not direct java.lang.ThreadGroup - need to override ThreadGroup.uncaughtException)

AccessControlContext - here, there is virtually nothing to be done (except starting in a dedicated thread) since the field is for internal usage only, and few even suspect the existence of.

stack size (usually it's unspecified but it can a -fun- thing to get a thread w/ very narrow stack size, based on the caller)

priority - most people do know about and tend to set it (more or less)

daemon status - usually that's not very important and easily noticable (if the application just disappears)

Lastly: the thread inherits caller's InheritableThreadLocal - which may (or may not) lead to some implications. Again nothing can be done about, besides spawning the thread into a dedicated thread.

Depending on the application the points above may have no effect at all but in some cases, some of them can lead to Class/Resources leaks that are hard to detect and exhibit not deterministic behavior.

That would make an extra long post but so...

below is some (hopefully) reusable code for ThreadFactory implementation, it can be used in managed environments to ensure proper ThreadGroup (which can limit priority or interrupt threads), ContextClassLoader, stacksize and so on are set (and/or can be configured) and not leaked. If there is any interest I can show how to deal w/ inherited ThreadLocals or the inherited acc (which essentially can leak the calling classloader)

```<code>package bestsss.util;

import java.lang.Thread.UncaughtExceptionHandler;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadFactoryX implements ThreadFactory{
    //thread properties
    long stackSize;
    String pattern;
    ClassLoader ccl;
    ThreadGroup group;
    int priority;
    UncaughtExceptionHandler exceptionHandler;
    boolean daemon;

    private boolean configured;

    private boolean wrapRunnable;//if acc is present wrap or keep it
    protected final AccessControlContext acc;

    //thread creation counter
    protected final AtomicLong counter = new AtomicLong();

    public ThreadFactoryX(){
        final Thread t = Thread.currentThread();
        ClassLoader loader;
    AccessControlContext acc = null;
    try{
        loader =  t.getContextClassLoader();
        if (System.getSecurityManager()!=null){
            acc = AccessController.getContext();//keep current permissions
            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
        }
    }catch(SecurityException _skip){
        //no permission
        loader =null;
        acc = null;
    }

    this.ccl = loader;
    this.acc = acc;
    this.priority = t.getPriority();
    this.daemon = true;//Executors have it false by default

    this.wrapRunnable = true;//by default wrap if acc is present (+SecurityManager)

    //default pattern - caller className
    StackTraceElement[] stack =  new Exception().getStackTrace();
    pattern(stack.length>1?getOuterClassName(stack[1].getClassName()):"ThreadFactoryX", true);
    }

    public ThreadFactory finishConfig(){
        configured = true;
        counter.addAndGet(0);//write fence "w/o" volatile
        return this;
    }

    public long getCreatedThreadsCount(){
        return counter.get();
    }

    protected void assertConfigurable(){
        if (configured)
            throw new IllegalStateException("already configured");
    }

    private static String getOuterClassName(String className){
        int idx = className.lastIndexOf('.')+1;
        className = className.substring(idx);//remove package
        idx = className.indexOf('$');
        if (idx<=0){
            return className;//handle classes starting w/ $
        }
        return className.substring(0,idx);//assume inner class

    }

    @Override
    public Thread newThread(Runnable r) {
        configured = true;
        final Thread t = new Thread(group, wrapRunnable(r), composeName(r), stackSize);
        t.setPriority(priority);
        t.setDaemon(daemon);
        t.setUncaughtExceptionHandler(exceptionHandler);//securityException only if in the main group, shall be safe here
        //funny moment Thread.getUncaughtExceptionHandler() has a race.. badz (can throw NPE)

        applyCCL(t);
        return t;
    }

    private void applyCCL(final Thread t) {
        if (ccl!=null){//use factory creator ACC for setContextClassLoader
            AccessController.doPrivileged(new PrivilegedAction<Object>(){
                @Override
                public Object run() {
                    t.setContextClassLoader(ccl);
                    return null;
                }
            }, acc);
        }
    }
    private Runnable wrapRunnable(final Runnable r){
        if (acc==null || !wrapRunnable){
            return r;
        }
        Runnable result = new Runnable(){
            public void run(){
                AccessController.doPrivileged(new PrivilegedAction<Object>(){
                    @Override
                    public Object run() {
                        r.run();
                        return null;
                    }
                }, acc);
            }
        };
        return result;
    }

    protected String composeName(Runnable r) {
        return String.format(pattern, counter.incrementAndGet(), System.currentTimeMillis());
    }

    //standard setters allowing chaining, feel free to add normal setXXX
    public ThreadFactoryX pattern(String patten, boolean appendFormat){
        assertConfigurable();
        if (appendFormat){
            patten+=": %d @ %tF %<tT";//counter + creation time
        }
        this.pattern = patten;
        return this;
    }

    public ThreadFactoryX daemon(boolean daemon){
        assertConfigurable();
        this.daemon = daemon;
        return this;
    }

    public ThreadFactoryX priority(int priority){
        assertConfigurable();
        if (priority<Thread.MIN_PRIORITY || priority>Thread.MAX_PRIORITY){//check before actual creation
            throw new IllegalArgumentException("priority: "+priority);
        }
        this.priority = priority;
        return this;
    }

    public ThreadFactoryX stackSize(long stackSize){
        assertConfigurable();
        this.stackSize = stackSize;
        return this;
    }

    public ThreadFactoryX threadGroup(ThreadGroup group){
        assertConfigurable();
        this.group= group;
        return this;
    }

    public ThreadFactoryX exceptionHandler(UncaughtExceptionHandler exceptionHandler){
        assertConfigurable();
        this.exceptionHandler= exceptionHandler;
        return this;
    }

    public ThreadFactoryX wrapRunnable(boolean wrapRunnable){
        assertConfigurable();
        this.wrapRunnable= wrapRunnable;
        return this;
    }

    public ThreadFactoryX ccl(ClassLoader ccl){
        assertConfigurable();
        this.ccl = ccl;
        return this;
    }
}
</code>```

Also some very simple usage:

```<code>ThreadFactory factory = new TreadFactoryX().priority(3).stackSize(0).wrapRunnable(false).pattern("Socket workers", true).
daemon(false).finishConfig();
</code>```

Title: ThreadFactory usage in Java

Body:
Some inner workings

The topic is covered quite well except for some inner works that are not easily visible.
While creating a thread w/ the constructor the newly created thread inherits current threads:

ThreadGroup (unless supplied or System.getSecurityManager().getThreadGroup() returns arbitrary ThreadGroup) - The thread group on its right own can be important in some cases and can result in improper thread termination/interruption. The ThreadGroup will stand as default exception handler.

ContextClassLoader - in managed environment that should not be a great issue since the environment shall switch the CCL, but if you are to implement that - keep it mind. Leaking the caller's CCL is quite bad, so is the thread group (esp. if the threadGroup is some subclass and not direct java.lang.ThreadGroup - need to override ThreadGroup.uncaughtException)

AccessControlContext - here, there is virtually nothing to be done (except starting in a dedicated thread) since the field is for internal usage only, and few even suspect the existence of.

stack size (usually it's unspecified but it can a -fun- thing to get a thread w/ very narrow stack size, based on the caller)

priority - most people do know about and tend to set it (more or less)

daemon status - usually that's not very important and easily noticable (if the application just disappears)

Lastly: the thread inherits caller's InheritableThreadLocal - which may (or may not) lead to some implications. Again nothing can be done about, besides spawning the thread into a dedicated thread.

Depending on the application the points above may have no effect at all but in some cases, some of them can lead to Class/Resources leaks that are hard to detect and exhibit not deterministic behavior.

That would make an extra long post but so...

below is some (hopefully) reusable code for ThreadFactory implementation, it can be used in managed environments to ensure proper ThreadGroup (which can limit priority or interrupt threads), ContextClassLoader, stacksize and so on are set (and/or can be configured) and not leaked. If there is any interest I can show how to deal w/ inherited ThreadLocals or the inherited acc (which essentially can leak the calling classloader)

package bestsss.util;

import java.lang.Thread.UncaughtExceptionHandler;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadFactoryX implements ThreadFactory{
    //thread properties
    long stackSize;
    String pattern;
    ClassLoader ccl;
    ThreadGroup group;
    int priority;
    UncaughtExceptionHandler exceptionHandler;
    boolean daemon;

    private boolean configured;

    private boolean wrapRunnable;//if acc is present wrap or keep it
    protected final AccessControlContext acc;

    //thread creation counter
    protected final AtomicLong counter = new AtomicLong();

    public ThreadFactoryX(){
        final Thread t = Thread.currentThread();
        ClassLoader loader;
    AccessControlContext acc = null;
    try{
        loader =  t.getContextClassLoader();
        if (System.getSecurityManager()!=null){
            acc = AccessController.getContext();//keep current permissions
            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
        }
    }catch(SecurityException _skip){
        //no permission
        loader =null;
        acc = null;
    }

    this.ccl = loader;
    this.acc = acc;
    this.priority = t.getPriority();
    this.daemon = true;//Executors have it false by default

    this.wrapRunnable = true;//by default wrap if acc is present (+SecurityManager)

    //default pattern - caller className
    StackTraceElement[] stack =  new Exception().getStackTrace();
    pattern(stack.length>1?getOuterClassName(stack[1].getClassName()):"ThreadFactoryX", true);
    }

    public ThreadFactory finishConfig(){
        configured = true;
        counter.addAndGet(0);//write fence "w/o" volatile
        return this;
    }

    public long getCreatedThreadsCount(){
        return counter.get();
    }

    protected void assertConfigurable(){
        if (configured)
            throw new IllegalStateException("already configured");
    }

    private static String getOuterClassName(String className){
        int idx = className.lastIndexOf('.')+1;
        className = className.substring(idx);//remove package
        idx = className.indexOf('$');
        if (idx<=0){
            return className;//handle classes starting w/ $
        }
        return className.substring(0,idx);//assume inner class

    }

    @Override
    public Thread newThread(Runnable r) {
        configured = true;
        final Thread t = new Thread(group, wrapRunnable(r), composeName(r), stackSize);
        t.setPriority(priority);
        t.setDaemon(daemon);
        t.setUncaughtExceptionHandler(exceptionHandler);//securityException only if in the main group, shall be safe here
        //funny moment Thread.getUncaughtExceptionHandler() has a race.. badz (can throw NPE)

        applyCCL(t);
        return t;
    }

    private void applyCCL(final Thread t) {
        if (ccl!=null){//use factory creator ACC for setContextClassLoader
            AccessController.doPrivileged(new PrivilegedAction<Object>(){
                @Override
                public Object run() {
                    t.setContextClassLoader(ccl);
                    return null;
                }
            }, acc);
        }
    }
    private Runnable wrapRunnable(final Runnable r){
        if (acc==null || !wrapRunnable){
            return r;
        }
        Runnable result = new Runnable(){
            public void run(){
                AccessController.doPrivileged(new PrivilegedAction<Object>(){
                    @Override
                    public Object run() {
                        r.run();
                        return null;
                    }
                }, acc);
            }
        };
        return result;
    }

    protected String composeName(Runnable r) {
        return String.format(pattern, counter.incrementAndGet(), System.currentTimeMillis());
    }

    //standard setters allowing chaining, feel free to add normal setXXX
    public ThreadFactoryX pattern(String patten, boolean appendFormat){
        assertConfigurable();
        if (appendFormat){
            patten+=": %d @ %tF %<tT";//counter + creation time
        }
        this.pattern = patten;
        return this;
    }

    public ThreadFactoryX daemon(boolean daemon){
        assertConfigurable();
        this.daemon = daemon;
        return this;
    }

    public ThreadFactoryX priority(int priority){
        assertConfigurable();
        if (priority<Thread.MIN_PRIORITY || priority>Thread.MAX_PRIORITY){//check before actual creation
            throw new IllegalArgumentException("priority: "+priority);
        }
        this.priority = priority;
        return this;
    }

    public ThreadFactoryX stackSize(long stackSize){
        assertConfigurable();
        this.stackSize = stackSize;
        return this;
    }

    public ThreadFactoryX threadGroup(ThreadGroup group){
        assertConfigurable();
        this.group= group;
        return this;
    }

    public ThreadFactoryX exceptionHandler(UncaughtExceptionHandler exceptionHandler){
        assertConfigurable();
        this.exceptionHandler= exceptionHandler;
        return this;
    }

    public ThreadFactoryX wrapRunnable(boolean wrapRunnable){
        assertConfigurable();
        this.wrapRunnable= wrapRunnable;
        return this;
    }

    public ThreadFactoryX ccl(ClassLoader ccl){
        assertConfigurable();
        this.ccl = ccl;
        return this;
    }
}

Also some very simple usage:

ThreadFactory factory = new TreadFactoryX().priority(3).stackSize(0).wrapRunnable(false).pattern("Socket workers", true).
daemon(false).finishConfig();


问:
How to add a custom column in Tasks section on Pulse in Magnolia
Good morning, i am a fairly new person at Magnolia and i have the need to improve a web by showing more data at the Task section of Pulse in Magnolia, to be able to do that i need to create a couple of columns but after trying to find some information at Magnolia documentation y have only been able to find this "Add custom column to Inbox", but unfortunately is outdated and the Inbox class that makes reference is not used anymore in the newers versions of Magnolia.

Could somebody help me and explain to me how to create these columns at the Tasks section of Pulse in Magnolia?, or point me in the rigth direction?.

Im using the Magnolia version 5.3 with a Maven setup, thanks in advance for the help.

答:
If you want to add additional column to pulse tasks, you should be dealing with java code unfortunately.

Have a look at  info.magnolia.ui.admincentral.shellapp.pulse.task.TasksListViewImpl#constructTable and there you will see the following:

```<code>    table.addGeneratedColumn(NEW_PROPERTY_ID, new PulseNewItemColumnGenerator());
    table.setColumnWidth(NEW_PROPERTY_ID, 100);
    table.addGeneratedColumn(TASK_PROPERTY_ID, new TaskSubjectColumnGenerator());
    table.setColumnWidth(TASK_PROPERTY_ID, 220);
    table.addGeneratedColumn(STATUS_PROPERTY_ID, new TaskStatusColumnGenerator());
    table.setColumnWidth(STATUS_PROPERTY_ID, 80);
    table.addGeneratedColumn(SENT_TO_PROPERTY_ID, new SentToColumnGenerator());
    table.setColumnWidth(SENT_TO_PROPERTY_ID, 100);
    table.addGeneratedColumn(LAST_CHANGE_PROPERTY_ID, new DateColumnFormatter(null));
    table.setColumnWidth(LAST_CHANGE_PROPERTY_ID, 140);
</code>```

Just adjust it to your needs.

Cheers,

Body:
If you want to add additional column to pulse tasks, you should be dealing with java code unfortunately.

Have a look at  info.magnolia.ui.admincentral.shellapp.pulse.task.TasksListViewImpl#constructTable and there you will see the following:

    table.addGeneratedColumn(NEW_PROPERTY_ID, new PulseNewItemColumnGenerator());
    table.setColumnWidth(NEW_PROPERTY_ID, 100);
    table.addGeneratedColumn(TASK_PROPERTY_ID, new TaskSubjectColumnGenerator());
    table.setColumnWidth(TASK_PROPERTY_ID, 220);
    table.addGeneratedColumn(STATUS_PROPERTY_ID, new TaskStatusColumnGenerator());
    table.setColumnWidth(STATUS_PROPERTY_ID, 80);
    table.addGeneratedColumn(SENT_TO_PROPERTY_ID, new SentToColumnGenerator());
    table.setColumnWidth(SENT_TO_PROPERTY_ID, 100);
    table.addGeneratedColumn(LAST_CHANGE_PROPERTY_ID, new DateColumnFormatter(null));
    table.setColumnWidth(LAST_CHANGE_PROPERTY_ID, 140);

Just adjust it to your needs.

Cheers,


问:
Stuck with my query
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

```<code>select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;
</code>```

Where am I making the mistake?

Thanks in advance!

答:
No need to use where condition unnecessarily and also you can use subquery as shown below</p>

```<code>SELECT e.ename, e.sal, (select max(sal) from emp) - E.Sal as difference
FROM emp e
</code>```

Title: Stuck with my query

Body:
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;

Where am I making the mistake?

Thanks in advance!

Body:
No need to use where condition unnecessarily and also you can use subquery as shown below

SELECT e.ename, e.sal, (select max(sal) from emp) - E.Sal as difference
FROM emp e


问:
Defining the data structure for reading the XML Data
I am trying to read the data from XML File,but not able to proceed further.

Here is my XML File:

```<code><CollectionOfVehicles>
    <Vehicle>
        <Motors>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>300</Bolt>
            </Motor>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>45</Bolt>
            </Motor>
        </Motors>
        <GearBoxes>
            <GearBox>
                <gear>0</gear>
                <Shaft>1</Shaft>
                <Bearings>2</Bearings>
            </GearBox>
        </GearBoxes>
    </Vehicle>
</CollectionOfVehicles>
</code>```

My Data Structure is as follows:

```<code>   public class Motor
    {
       public double Screw {get; set; }
       public double Nut {get; set; }
       public double Bolt {get; set; }
       public Motor() {}
    }

    public class GearBox
    {
       public uint gear {get; set; }
       public uint Shaft {get; set; }
       public uint Bearings {get; set; }
       public GearBox() {}
    }

    public class Vehicle
    {
        public List<Motor> motors {get; set;}
        public List<GearBox> gearBoxes {get; set;}
        public Vehicle() {}
    };

   **I tried to write the following lines of code to feed the XML Data:**

   Vehicle cars = null;
   string path = @"C:\Users\Semantics\Desktop\New.xml";
   XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
   var reader = XmlReader.Create(path);
   cars = (Vehicle)serializer.Deserialize(reader);
   reader.Close();
</code>```

I basically,want to retrieve Vehicles as  and then loop over each vehicle,and retrieve the associated Motor and GearBox.I am not sure,how to retrieve the data like nut,screw and bolt using XMLAttributor (or) XMLElement in my data structure.

Thanks in Advance!

答:
If you are using XML a nice cleaner way to create your objects would be to copy the xml text, then in Visual Studio go to edit->paste special->Paste XML as Classes. That way if your structure changes, you can repeat the process to update your object classes. taking your current xml, and taking in consideration that there could be more than 1 Vehicle, Motor and Gearbox based on your xml structure, this is what I get, Object Models:

```<code>[Serializable]
public class CollectionOfVehicles
{
    private Vehicle[] vehicleList;

    [XmlElementAttribute("Vehicle")]
    public Vehicle[] Vehicle { get { return this.vehicleList; } set { this.vehicleList = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Vehicle
{
    private Motor[] motorList;
    private GearBox[] gearBoxList;

    [XmlArray("Motors")]
    public Motor[] Motors { get { return this.motorList; } set { this.motorList = value; } }
    [XmlArray("GearBoxes")]
    public GearBox[] GearBoxes { get { return this.gearBoxList; } set { this.gearBoxList = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Motor
{
    private double screwField;
    private double nutField;
    private double boltField;

    public double Screw { get { return this.screwField; } set { this.screwField = value; } }
    public double Nut { get { return this.nutField; } set { this.nutField = value; } }
    public double Bolt { get { return this.boltField; } set { this.boltField = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class GearBox
{
    private uint gearField;
    private uint shaftField;
    private uint bearingsField;

    public uint gear { get { return this.gearField; } set { this.gearField = value; } }
    public uint Shaft { get { return this.shaftField; } set { this.shaftField = value; } }
    public uint Bearings { get { return this.bearingsField; } set { this.bearingsField = value; } }
}
</code>```

then when reading the xml file you can do the following:

```<code>        CollectionOfVehicles cars = null;
        string path = @"test.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(CollectionOfVehicles));
        using (var reader = XmlReader.Create(path))
        {
            cars = (CollectionOfVehicles)serializer.Deserialize(reader);

            Console.WriteLine("Vehicles List Count: " + cars.Vehicle.Length.ToString());
            Console.WriteLine(" ");
            for (int i = 0; i < cars.Vehicle.Length; i++)
            {
                Console.WriteLine("Vehicle '" + i + "' Motors List Count: " + cars.Vehicle[i].Motors.Length.ToString());
                for (int ii = 0; ii < cars.Vehicle[i].Motors.Length; ii++)
                {
                    Console.WriteLine("Vehicle '" + i + "' Motor '" + ii + "' Data");
                    Console.WriteLine("Bolts: " + cars.Vehicle[i].Motors[ii].Bolt.ToString());
                    Console.WriteLine("Nut: " + cars.Vehicle[i].Motors[ii].Nut.ToString());
                    Console.WriteLine("Screws: " + cars.Vehicle[i].Motors[ii].Screw.ToString());
                }

                Console.WriteLine("Vehicle '" + i + "' GearBoxes List Count: " + cars.Vehicle[i].GearBoxes.Length.ToString());
                for (int ii = 0; ii < cars.Vehicle[i].GearBoxes.Length; ii++)
                {
                    Console.WriteLine("Vehicle '" + i + "' GearBox '" + ii + "' Data");
                    Console.WriteLine("Gear: " + cars.Vehicle[i].GearBoxes[ii].gear.ToString());
                    Console.WriteLine("Shaft: " + cars.Vehicle[i].GearBoxes[ii].Shaft.ToString());
                    Console.WriteLine("Bearings: " + cars.Vehicle[i].GearBoxes[ii].Bearings.ToString());
                }
            }
        }
</code>```

Body:
I am trying to read the data from XML File,but not able to proceed further.

Here is my XML File:

<CollectionOfVehicles>
    <Vehicle>
        <Motors>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>300</Bolt>
            </Motor>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>45</Bolt>
            </Motor>
        </Motors>
        <GearBoxes>
            <GearBox>
                <gear>0</gear>
                <Shaft>1</Shaft>
                <Bearings>2</Bearings>
            </GearBox>
        </GearBoxes>
    </Vehicle>
</CollectionOfVehicles>

My Data Structure is as follows:

   public class Motor
    {
       public double Screw {get; set; }
       public double Nut {get; set; }
       public double Bolt {get; set; }
       public Motor() {}
    }

    public class GearBox
    {
       public uint gear {get; set; }
       public uint Shaft {get; set; }
       public uint Bearings {get; set; }
       public GearBox() {}
    }

    public class Vehicle
    {
        public List<Motor> motors {get; set;}
        public List<GearBox> gearBoxes {get; set;}
        public Vehicle() {}
    };

   **I tried to write the following lines of code to feed the XML Data:**

   Vehicle cars = null;
   string path = @"C:\Users\Semantics\Desktop\New.xml";
   XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
   var reader = XmlReader.Create(path);
   cars = (Vehicle)serializer.Deserialize(reader);
   reader.Close();

I basically,want to retrieve Vehicles as  and then loop over each vehicle,and retrieve the associated Motor and GearBox.I am not sure,how to retrieve the data like nut,screw and bolt using XMLAttributor (or) XMLElement in my data structure.

Thanks in Advance!

Body:
If you are using XML a nice cleaner way to create your objects would be to copy the xml text, then in Visual Studio go to edit->paste special->Paste XML as Classes. That way if your structure changes, you can repeat the process to update your object classes. taking your current xml, and taking in consideration that there could be more than 1 Vehicle, Motor and Gearbox based on your xml structure, this is what I get, Object Models:

[Serializable]
public class CollectionOfVehicles
{
    private Vehicle[] vehicleList;

    [XmlElementAttribute("Vehicle")]
    public Vehicle[] Vehicle { get { return this.vehicleList; } set { this.vehicleList = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Vehicle
{
    private Motor[] motorList;
    private GearBox[] gearBoxList;

    [XmlArray("Motors")]
    public Motor[] Motors { get { return this.motorList; } set { this.motorList = value; } }
    [XmlArray("GearBoxes")]
    public GearBox[] GearBoxes { get { return this.gearBoxList; } set { this.gearBoxList = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Motor
{
    private double screwField;
    private double nutField;
    private double boltField;

    public double Screw { get { return this.screwField; } set { this.screwField = value; } }
    public double Nut { get { return this.nutField; } set { this.nutField = value; } }
    public double Bolt { get { return this.boltField; } set { this.boltField = value; } }
}

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class GearBox
{
    private uint gearField;
    private uint shaftField;
    private uint bearingsField;

    public uint gear { get { return this.gearField; } set { this.gearField = value; } }
    public uint Shaft { get { return this.shaftField; } set { this.shaftField = value; } }
    public uint Bearings { get { return this.bearingsField; } set { this.bearingsField = value; } }
}

then when reading the xml file you can do the following:

        CollectionOfVehicles cars = null;
        string path = @"test.xml";
        XmlSerializer serializer = new XmlSerializer(typeof(CollectionOfVehicles));
        using (var reader = XmlReader.Create(path))
        {
            cars = (CollectionOfVehicles)serializer.Deserialize(reader);

            Console.WriteLine("Vehicles List Count: " + cars.Vehicle.Length.ToString());
            Console.WriteLine(" ");
            for (int i = 0; i < cars.Vehicle.Length; i++)
            {
                Console.WriteLine("Vehicle '" + i + "' Motors List Count: " + cars.Vehicle[i].Motors.Length.ToString());
                for (int ii = 0; ii < cars.Vehicle[i].Motors.Length; ii++)
                {
                    Console.WriteLine("Vehicle '" + i + "' Motor '" + ii + "' Data");
                    Console.WriteLine("Bolts: " + cars.Vehicle[i].Motors[ii].Bolt.ToString());
                    Console.WriteLine("Nut: " + cars.Vehicle[i].Motors[ii].Nut.ToString());
                    Console.WriteLine("Screws: " + cars.Vehicle[i].Motors[ii].Screw.ToString());
                }

                Console.WriteLine("Vehicle '" + i + "' GearBoxes List Count: " + cars.Vehicle[i].GearBoxes.Length.ToString());
                for (int ii = 0; ii < cars.Vehicle[i].GearBoxes.Length; ii++)
                {
                    Console.WriteLine("Vehicle '" + i + "' GearBox '" + ii + "' Data");
                    Console.WriteLine("Gear: " + cars.Vehicle[i].GearBoxes[ii].gear.ToString());
                    Console.WriteLine("Shaft: " + cars.Vehicle[i].GearBoxes[ii].Shaft.ToString());
                    Console.WriteLine("Bearings: " + cars.Vehicle[i].GearBoxes[ii].Bearings.ToString());
                }
            }
        }


问:
What exactly Java EE6 and do I have choice not to include some of features?
When I looked into Java EE6 doc and some other articles, Java EE6 is a platform.

To me, platform is just Java with bunch of API/framework available like JSF, JPA, Web services  like REST. (more like bunch of jars maybe?)

So anyway I got Netbean6.9/Java EE6/GlassFish v3 bundle but figured I don't need JSF at all.

Is there a way to remove JSF from Java EE6 so that I can save some disc space on my server?

Sorry if my statement doesn't make sense because I'm not fully understand what exactly Java EE6 by reading documentation.. (or this JSF is bundled with Netbean6.9...)

Update:

I'm building REST web app so far using JAX-RS and JPA (toplink essential) and for UI side, JSF was going to be used but we decided not to, so wondering if things that won't get used can be removed. (after reading comments I think removing JSF is not good idea though)

答:
In order to be J2EE certified there are certain requirements that must be met, and removing some of the functionality may cause problems.

For a nice discussion on what it means to be certified, you can start with this:
http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition

A Java EE application server can
  handle transactions, security,
  scalability, concurrency and
  management of the components that are
  deployed to it, in order to enable
  developers to concentrate more on the
  business logic of the components
  rather than on infrastructure and
  integration tasks.

If you find that you don't want to use much of J2EE you can look at something like the Spring framework (http://www.springsource.org/) which will offer more capabilities than just tomcat/jetty, but you can add/remove the parts you don't need, though you will need to include the core.

If you just need JAX-WS for example, then you can just add that manually, but, depending on your application you may find that there are many parts you will eventually need to make your life easier.


问:
How to fetch API data to Graphql schema
I want to call to API, get json data and set it to resolvers Query in Graphql. So far I managed to working Graphql server and get call to API. This is my code so far

```<code>//resolvers.js
//var fetch = require('node-fetch');
var request = require("request");

var options = { method: 'GET',
    url: 'http://mydomain.con/index.php/rest/V1/products/24-MB01',
    headers:
        { 'postman-token': 'mytoken',
            'cache-control': 'no-cache',
            'content-type': 'application/json',
            authorization: 'Bearer mytoken' } };

const links = request(options, function (error, response, body) {
    if (error) throw new Error(error);
    //body = json data
    //console.log(body);

});

module.exports = {
    Query: {
        //set data to Query
        allLinks: () => links,
},
};
</code>```

I dont know how to set the body parameter which contain json data to Query. I have also same data on "http://localhost/src/apicall.php" but this is not working with node-fetch (or Im making mistakes). Api is from magento2.

答:
You were close !

What you are doing right now is sending the links request right when your application starts. You don't want that ; you want to send the request when the allLinks field is requested in GraphQL.

So what you need is to have in the allLinks field a function making the request to your API, and returning the response.

If you return a Promise within the allLinks field, it will wait upon completion to use the returned value as an answer.

So, putting it all together:

```<code>...

const getAllLinks = () => {
  return new Promise((resolve, reject) => {
    request(options, function (error, response, body) {
      if (error) reject(error);
      else resolve(body);
    });
  });
};

module.exports = {
  Query: {
    //set data to Query
    allLinks: getAllLinks,
  },
};
</code>```

Title: How to fetch API data to Graphql schema

Body:
I want to call to API, get json data and set it to resolvers Query in Graphql. So far I managed to working Graphql server and get call to API. This is my code so far

//resolvers.js
//var fetch = require('node-fetch');
var request = require("request");

var options = { method: 'GET',
    url: 'http://mydomain.con/index.php/rest/V1/products/24-MB01',
    headers:
        { 'postman-token': 'mytoken',
            'cache-control': 'no-cache',
            'content-type': 'application/json',
            authorization: 'Bearer mytoken' } };

const links = request(options, function (error, response, body) {
    if (error) throw new Error(error);
    //body = json data
    //console.log(body);

});

module.exports = {
    Query: {
        //set data to Query
        allLinks: () => links,
},
};

I dont know how to set the body parameter which contain json data to Query. I have also same data on "http://localhost/src/apicall.php" but this is not working with node-fetch (or Im making mistakes). Api is from magento2.

Body:
You were close !

What you are doing right now is sending the links request right when your application starts. You don't want that ; you want to send the request when the allLinks field is requested in GraphQL.

So what you need is to have in the allLinks field a function making the request to your API, and returning the response.

If you return a Promise within the allLinks field, it will wait upon completion to use the returned value as an answer.

So, putting it all together:

...

const getAllLinks = () => {
  return new Promise((resolve, reject) => {
    request(options, function (error, response, body) {
      if (error) reject(error);
      else resolve(body);
    });
  });
};

module.exports = {
  Query: {
    //set data to Query
    allLinks: getAllLinks,
  },
};


问:
IIS/ASP.NET responds with cache-control: private for all requests
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?

For dynamic content (that is, all MVC results) I would not like it to be cached by the browser, since it is dynamic and can change at any time. Static content is hosted on a CDN, so is not served by IIS.

Edit:

To clarify, I understand very well what Cache-Control: private is, the difference between private, public, no-store, etc and how/when to use them. The question I have is why Cache-Control: private is added by default by IIS/ASP.NET and how to prevent it from being added by default. I understand that it can be useful to cache dynamic pages, but in my application I don't want to cache dynamic pages/responses. For example, I don't want XHR JSON responses to be cached, since they contain dynamic content. Unfortunately the server adds Cache-Control: private to all responses automatically, so I have to manually override it everywhere.

How to reproduce: Open visual studio and create a new ASP.NET Framework (yes, framework, no not Core. We are not able to migrate our system to core yet) solution with an MVC project. Now start the project in IIS Express (just press the play button), and use F12 devtools in the browser to look at the http response. You will see that it contains Cache-Control: private. My question is, what adds this header, and how can I prevent it from being added by default?

答:
Adding my bit to the great answers, given by community;

1. http caching header attrubute Cache-Control: private is added by default by IIS/ASP.NET ?

Cache request directives

Standard Cache-Control directives that can be used by the client in an HTTP request.

```<code>    Cache-Control: max-age=<seconds>
    Cache-Control: max-stale[=<seconds>]
    Cache-Control: min-fresh=<seconds>
    Cache-Control: no-cache
    Cache-Control: no-store
    Cache-Control: no-transform
    Cache-Control: only-if-cached
</code>```

Cache response directives

Standard Cache-Control directives that can be used by the server in an HTTP response.

```<code>    Cache-Control: must-revalidate
    Cache-Control: no-cache
    Cache-Control: no-store
    Cache-Control: no-transform
    Cache-Control: public
    Cache-Control: private
    Cache-Control: proxy-revalidate
    Cache-Control: max-age=<seconds>
    Cache-Control: s-maxage=<seconds>
</code>```

IIS uses the secure and more obvious/useful one for default, which happens to be private

2. how to prevent it from being added by default?

IIS/asp.net allows this to be configured from the day it was introduced like this, ref1, ref2, ref3, ref4 and

System.Web Namespace

The System.Web namespace supplies classes and interfaces that enable browser-server communication. This namespace includes the System.Web.HttpRequest class, which provides extensive information about the current HTTP request; the System.Web.HttpResponse class, which manages HTTP output to the client; and the System.Web.HttpServerUtility class, which provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.

```<code>protected void Application_BeginRequest()
{
  Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
</code>```

Body:
Adding my bit to the great answers, given by community;

1. http caching header attrubute Cache-Control: private is added by default by IIS/ASP.NET ?

Cache request directives

Standard Cache-Control directives that can be used by the client in an HTTP request.

    Cache-Control: max-age=<seconds>
    Cache-Control: max-stale[=<seconds>]
    Cache-Control: min-fresh=<seconds>
    Cache-Control: no-cache
    Cache-Control: no-store
    Cache-Control: no-transform
    Cache-Control: only-if-cached

Cache response directives

Standard Cache-Control directives that can be used by the server in an HTTP response.

    Cache-Control: must-revalidate
    Cache-Control: no-cache
    Cache-Control: no-store
    Cache-Control: no-transform
    Cache-Control: public
    Cache-Control: private
    Cache-Control: proxy-revalidate
    Cache-Control: max-age=<seconds>
    Cache-Control: s-maxage=<seconds>

IIS uses the secure and more obvious/useful one for default, which happens to be private

2. how to prevent it from being added by default?

IIS/asp.net allows this to be configured from the day it was introduced like this, ref1, ref2, ref3, ref4 and

System.Web Namespace

The System.Web namespace supplies classes and interfaces that enable browser-server communication. This namespace includes the System.Web.HttpRequest class, which provides extensive information about the current HTTP request; the System.Web.HttpResponse class, which manages HTTP output to the client; and the System.Web.HttpServerUtility class, which provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.

protected void Application_BeginRequest()
{
  Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}


问:
Django: Why 'Class' object is not iterable
I built a dictionary list like this

```<code>lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]
</code>```

and I'm using

```<code>for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process
</code>```

The error message is like "Classname" object is not iterable.

答:
```<code>
for dic in lst:
   for k,v in dic.iteritems():   # just added a call to iteritems
       #process
```

You get the '<class obj> is not iterable' error because a dict yields its keys when iterating over it, so when you reach say Classobj1 the program expects Classobj1 to be an iterable object that will yield values for k,v.

Body:
I built a dictionary list like this

lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]

and I'm using

for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process

The error message is like "Classname" object is not iterable.

Body:
for dic in lst:
   for k,v in dic.iteritems():   # just added a call to iteritems
       #process

You get the '<class obj> is not iterable' error because a dict yields its keys when iterating over it, so when you reach say Classobj1 the program expects Classobj1 to be an iterable object that will yield values for k,v.


问:
Angular, how to make other elements false when one element is true
i need help to make other elements condition's false when one element's condition is true and if it is possible only one that can be true at a time. I'm not sure what i wrote is correct. Can anyone help me, please?

showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier: boolean = false;

if (showProduct = true) {
  this.showCustomer = false;
  this.showSupplier = false;
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<div *ngIf="showProduct" align="center">
  <app-product></app-product>
</div>

<div *ngIf="showCustomer" align="center">
  <app-customer></app-customer>
</div>

<div *ngIf="showSupplier" align="center">
  <app-supplier></app-supplier>
</div></code>```

Please let me know if more snippets are needed. Thank you in advance.

答:
Yes, you can do it like :

```<code>(click)="showProduct=!showProduct;showCustomer=false;showSupplier=false;"
</code>```

OR

Component side :

```<code>showStatus = {
    showProduct : true;
    showCustomer : false;
    showSupplier : false;
}

changeShowStatus(changeBlock) {
    for(let block in this.showStatus) {
        if(block === changeBlock) {
            this.showStatus[block] = !this.showStatus[block];
        } else {
            this.showStatus[block] = false;
        }
    }
}
</code>```

Template side :

```<code><a href="#" (click)="changeShowStatus('showProduct')"></a>
<a href="#" (click)="changeShowStatus('showCustomer')"></a>
<a href="#" (click)="changeShowStatus('showSupplier')"></a>

<div *ngIf="showStatus['showProduct']" align="center">
  <app-product></app-product>
</div>
<div *ngIf="showStatus['showCustomer']" align="center">
  <app-product></app-product>
</div>
<div *ngIf="showStatus['showSupplier']" align="center">
  <app-product></app-product>
</div>
</code>```

Body:
i need help to make other elements condition's false when one element's condition is true and if it is possible only one that can be true at a time. I'm not sure what i wrote is correct. Can anyone help me, please?

showProduct: boolean = false;
showCustomer: boolean = false;
showSupplier: boolean = false;

if (showProduct = true) {
  this.showCustomer = false;
  this.showSupplier = false;
}

  <app-product></app-product>

  <app-customer></app-customer>

  <app-supplier></app-supplier>

Please let me know if more snippets are needed. Thank you in advance.

Body:
Yes, you can do it like :

(click)="showProduct=!showProduct;showCustomer=false;showSupplier=false;"

OR

Component side :

showStatus = {
    showProduct : true;
    showCustomer : false;
    showSupplier : false;
}

changeShowStatus(changeBlock) {
    for(let block in this.showStatus) {
        if(block === changeBlock) {
            this.showStatus[block] = !this.showStatus[block];
        } else {
            this.showStatus[block] = false;
        }
    }
}

Template side :

<a href="#" (click)="changeShowStatus('showProduct')"></a>
<a href="#" (click)="changeShowStatus('showCustomer')"></a>
<a href="#" (click)="changeShowStatus('showSupplier')"></a>

<div *ngIf="showStatus['showProduct']" align="center">
  <app-product></app-product>
</div>
<div *ngIf="showStatus['showCustomer']" align="center">
  <app-product></app-product>
</div>
<div *ngIf="showStatus['showSupplier']" align="center">
  <app-product></app-product>
</div>


问:
Fluent Assertions: check if the collection contains the object, equivalent to the provided one?
I am using Fluent Assertions and willing to test if my collection contains some object using deep object graph comparison. I don't want to implement all that equality members. However, I can not find the way to do the test for equivalence containment of some object in the collection. For example, this test fails and I want it to pass:

```<code>class Student
{
    public string Name { get; set; }
}

[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }.Should()
        .Contain(new Student { Name = "Anna" });
}
</code>```

Is there some elegant way to do it? Something like this?

```<code>[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }.ShouldContainEquivalent(new Student { Name = "Anna" });
}
</code>```

答:
No elegant way, but you can use predicate:</p>

```<code>[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }
        .Should().Contain(s => s.Name == "Anna");
}
</code>```

Body:
I am using Fluent Assertions and willing to test if my collection contains some object using deep object graph comparison. I don't want to implement all that equality members. However, I can not find the way to do the test for equivalence containment of some object in the collection. For example, this test fails and I want it to pass:

class Student
{
    public string Name { get; set; }
}

[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }.Should()
        .Contain(new Student { Name = "Anna" });
}

Is there some elegant way to do it? Something like this?

[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }.ShouldContainEquivalent(new Student { Name = "Anna" });
}

Body:
No elegant way, but you can use predicate:

[Test]
public void ShouldContainStudent()
{
    new[] { new Student { Name = "George" }, new Student { Name = "Anna" } }
        .Should().Contain(s => s.Name == "Anna");
}


问:
Getting a message thread from a MySQL database based on USER and MESSAGE tables
I may be asking my SQL query to do a bit much in one hit. I'm writing a messaging script and want to display the summary list of conversation threads just like text messages work on phones; so the person the message thread is with, the date/time of the last message and the number of unread messages per user.

So consider this query, assuming the user id we're checking is 1:

```<code>SELECT u.id,
       u.name,
       u.image,
       m.message,
       m.sender,
       m.sent,
       sum(if(m.sender<>1,m.unread,0)) as unread
FROM   messages m
INNER JOIN members u ON u.id = m.sender OR u.id = m.receiver
WHERE (m.sender = 1 OR m.receiver = 1) AND u.id <> 1
GROUP BY IF(m.sender = 1, m.receiver, m.sender)
ORDER BY m.sent DESC
</code>```

In this the field types should be reasonably obvious. 'sender' is the id of the person who sent the message; 'receiver' the other user id; 'sent' the date/time the message was sent; and 'unread' a tinyint flag which is either 0 or 1.

For the most part this works - it gives me a list of unique conversation threads plus the correct number of unread messages, but, the message it's picking up as the last one sent always seems to be the first one, not the last one as if ORDER BY m.sent DESC is being overridden by the GROUP or JOIN. I'm obviously doing something dumb, but I just can't see it. Any pointers?

答:
Ok, I managed to solve this after much trial and error by adding another join to the messages table which simply grabbed the last unique message ID for each grouped conversation, i.e.:

```<code>SELECT u.id,
       u.name,
       u.image,
       m.message,
       m.sender,
       m.sent,
       sum(if(m.sender<>1,m.unread,0)) as unread
FROM   messages m
INNER JOIN members u ON u.id = m.sender OR u.id = m.receiver
JOIN (SELECT max(id) id FROM messages GROUP BY IF(sender=1, receiver, sender)) t ON m.id = t.id
WHERE (m.sender = 1 OR m.receiver = 1) AND u.id <> 1
GROUP BY IF(m.sender = 1, m.receiver, m.sender)
ORDER BY m.sent DESC
</code>```

I'm still a little confused as to why the original query wasn't picking up the last message as per the ORDER BY sent, but hey - a fix is a fix.

Body:
I may be asking my SQL query to do a bit much in one hit. I'm writing a messaging script and want to display the summary list of conversation threads just like text messages work on phones; so the person the message thread is with, the date/time of the last message and the number of unread messages per user.

So consider this query, assuming the user id we're checking is 1:

SELECT u.id,
       u.name,
       u.image,
       m.message,
       m.sender,
       m.sent,
       sum(if(m.sender<>1,m.unread,0)) as unread
FROM   messages m
INNER JOIN members u ON u.id = m.sender OR u.id = m.receiver
WHERE (m.sender = 1 OR m.receiver = 1) AND u.id <> 1
GROUP BY IF(m.sender = 1, m.receiver, m.sender)
ORDER BY m.sent DESC

In this the field types should be reasonably obvious. 'sender' is the id of the person who sent the message; 'receiver' the other user id; 'sent' the date/time the message was sent; and 'unread' a tinyint flag which is either 0 or 1.

For the most part this works - it gives me a list of unique conversation threads plus the correct number of unread messages, but, the message it's picking up as the last one sent always seems to be the first one, not the last one as if ORDER BY m.sent DESC is being overridden by the GROUP or JOIN. I'm obviously doing something dumb, but I just can't see it. Any pointers?

Body:
Ok, I managed to solve this after much trial and error by adding another join to the messages table which simply grabbed the last unique message ID for each grouped conversation, i.e.:

SELECT u.id,
       u.name,
       u.image,
       m.message,
       m.sender,
       m.sent,
       sum(if(m.sender<>1,m.unread,0)) as unread
FROM   messages m
INNER JOIN members u ON u.id = m.sender OR u.id = m.receiver
JOIN (SELECT max(id) id FROM messages GROUP BY IF(sender=1, receiver, sender)) t ON m.id = t.id
WHERE (m.sender = 1 OR m.receiver = 1) AND u.id <> 1
GROUP BY IF(m.sender = 1, m.receiver, m.sender)
ORDER BY m.sent DESC

I'm still a little confused as to why the original query wasn't picking up the last message as per the ORDER BY sent, but hey - a fix is a fix.


问:
Laravel and shared hosting CURL not working
I am deploying my Laravel application to shared hosting from Godaddy for testing purposes only (so that I can share it in a domain) for production I will be using a better solution.

In my localhost, everything works fine, but in hosting CURL is not working. Actually, this CURL

```<code>function setUrl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
}
</code>```

This does not work. When I check my cookies.txt file in the hosting it is always empty, actually I tried moving it to public, another folder and everywhere, but it does not get edited, it is always empty. It worked fine in my localhost, but for some reason it doesn't want to work in hosting.

Does anyone have some idea to tackle this issue?

This I my curinfo if it helps

```<code>"content_type" => null
  "http_code" => 0
  "header_size" => 0
  "request_size" => 0
  "filetime" => -1
  "ssl_verify_result" => 0
  "redirect_count" => 0
  "total_time" => 0.200232
  "namelookup_time" => 4.8E-5
  "connect_time" => 0.0
  "pretransfer_time" => 0.0
  "size_upload" => 0.0
  "size_download" => 0.0
  "speed_download" => 0.0
  "speed_upload" => 0.0
  "download_content_length" => -1.0
  "upload_content_length" => -1.0
  "starttransfer_time" => 0.0
  "redirect_time" => 0.0
  "redirect_url" => ""
  "primary_ip" => ""
  "certinfo" => []
  "primary_port" => 0
  "local_ip" => ""
  "local_port" => 0
]
</code>```

答:
most likely, you're being firewall-blocked by GoDaddy. i've seen same shit countless times on shared webhosts. you should probably invest in a VPS instead (they're like $3.5/month on ramnode..), but you're also doing some mistakes, namely you ignore any errors given by curl_setopt, it returns bool(false) on failure, which your code completely ignores. try using this instead:

```<code>function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' .  curl_errno ($ch) .' curl_error: '.curl_error($ch) );
    }
    return true;
}
</code>```

however, when debugging curl, you should always enable CURLOPT_VERBOSE and get the verbose log, it's usually super useful when debugging curl code, like

```<code>function setUrl($url) {
    $debugfileh=tmpfile();
    $ch = curl_init();
    try{
    ecurl_setopt($ch, CURLOPT_URL, $url);
    ecurl_setopt($ch, CURLOPT_VERBOSE, 1);
    ecurl_setopt($ch, CURLOPT_STDERR, $debugfileh);
    ecurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    ecurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    ecurl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    ecurl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    return $buffer;
    }finally{
    var_dump('curl verbose log:',file_get_contents(stream_get_meta_data($debugfileh)['uri']));
    fclose($debugfileh);
    curl_close($ch);
    }
}
</code>```

Body:
I am deploying my Laravel application to shared hosting from Godaddy for testing purposes only (so that I can share it in a domain) for production I will be using a better solution.

In my localhost, everything works fine, but in hosting CURL is not working. Actually, this CURL

function setUrl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
}

This does not work. When I check my cookies.txt file in the hosting it is always empty, actually I tried moving it to public, another folder and everywhere, but it does not get edited, it is always empty. It worked fine in my localhost, but for some reason it doesn't want to work in hosting.

Does anyone have some idea to tackle this issue?

This I my curinfo if it helps

"content_type" => null
  "http_code" => 0
  "header_size" => 0
  "request_size" => 0
  "filetime" => -1
  "ssl_verify_result" => 0
  "redirect_count" => 0
  "total_time" => 0.200232
  "namelookup_time" => 4.8E-5
  "connect_time" => 0.0
  "pretransfer_time" => 0.0
  "size_upload" => 0.0
  "size_download" => 0.0
  "speed_download" => 0.0
  "speed_upload" => 0.0
  "download_content_length" => -1.0
  "upload_content_length" => -1.0
  "starttransfer_time" => 0.0
  "redirect_time" => 0.0
  "redirect_url" => ""
  "primary_ip" => ""
  "certinfo" => []
  "primary_port" => 0
  "local_ip" => ""
  "local_port" => 0
]

Body:
most likely, you're being firewall-blocked by GoDaddy. i've seen same shit countless times on shared webhosts. you should probably invest in a VPS instead (they're like $3.5/month on ramnode..), but you're also doing some mistakes, namely you ignore any errors given by curl_setopt, it returns bool(false) on failure, which your code completely ignores. try using this instead:

function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' .  curl_errno ($ch) .' curl_error: '.curl_error($ch) );
    }
    return true;
}

however, when debugging curl, you should always enable CURLOPT_VERBOSE and get the verbose log, it's usually super useful when debugging curl code, like

function setUrl($url) {
    $debugfileh=tmpfile();
    $ch = curl_init();
    try{
    ecurl_setopt($ch, CURLOPT_URL, $url);
    ecurl_setopt($ch, CURLOPT_VERBOSE, 1);
    ecurl_setopt($ch, CURLOPT_STDERR, $debugfileh);
    ecurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    ecurl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    ecurl_setopt($ch, CURLOPT_COOKIEJAR, public_path().'/cookies/cookies.txt');
    ecurl_setopt($ch, CURLOPT_COOKIEFILE, public_path().'/cookies/cookies.txt');
    $buffer = curl_exec($ch);
    return $buffer;
    }finally{
    var_dump('curl verbose log:',file_get_contents(stream_get_meta_data($debugfileh)['uri']));
    fclose($debugfileh);
    curl_close($ch);
    }
}


问:
Segmentation fault (core dumped) with the strcpy-function in c
I am trying to write a function which will read two strings stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI" and popArr[MAX]="ABCDEFGHIJ" and generate an output like this:

```<code>A
B-F-D-A
C-F-D-A
D-A
E-G-C-F-D-A
F-D-A
G-C-F-D-A
H-C-F-D-A
I-J-H-C-F-D-A
J-H-C-F-D-A
</code>```

However I'm getting a Segmentation fault (core dumped) Error. Why? This is my code:

```<code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

#define MAX 100

size_t strlstchar(const char *str, const char ch)
{
    char *chptr = strrchr(str, ch);
    return chptr - str;
}

int main(){
    // Input strings
    char stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI";
    char popArr[MAX]="ABCDEFGHIJ";

    int index=2, lenpop, lentemp;
    char usedString[MAX]="";
    char tempChar;

    lenpop    = strlen(popArr);

    printf("%c\n", stringArray[0]);

    for(int i=1;i<lenpop;i++){
        strcpy(usedString, stringArray);
        printf("%c", popArr[i]);
        tempChar = popArr[i];

        while(tempChar!=stringArray[0]){
            while(index%2==0){
                index = strlstchar(usedString, tempChar);
                lentemp = strlen(usedString);
                usedString[lentemp-index-1]=0;
                }

            printf("-%c", usedString[index-1]);
            tempChar=usedString[index-1];
            index=2;
            }
            printf("\n");
        }

    return 0;
    }
</code>```

Thanks in advance!

答:
The segmentation violation occurs in this line:

```<code>    usedString[lentemp - index - 1] = 0;
</code>```

Here, you're trying to find the index from the end, but your strlstchar returns the index from the beginning, although it starts searching from the end. And you want truncate the string at the found character, of course.

Replace this line with just:

```<code>    usedString[index] = 0;
</code>```

and you get the desired output.

Body:
I am trying to write a function which will read two strings stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI" and popArr[MAX]="ABCDEFGHIJ" and generate an output like this:

A
B-F-D-A
C-F-D-A
D-A
E-G-C-F-D-A
F-D-A
G-C-F-D-A
H-C-F-D-A
I-J-H-C-F-D-A
J-H-C-F-D-A

However I'm getting a Segmentation fault (core dumped) Error. Why? This is my code:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

#define MAX 100

size_t strlstchar(const char *str, const char ch)
{
    char *chptr = strrchr(str, ch);
    return chptr - str;
}

int main(){
    // Input strings
    char stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI";
    char popArr[MAX]="ABCDEFGHIJ";

    int index=2, lenpop, lentemp;
    char usedString[MAX]="";
    char tempChar;

    lenpop    = strlen(popArr);

    printf("%c\n", stringArray[0]);

    for(int i=1;i<lenpop;i++){
        strcpy(usedString, stringArray);
        printf("%c", popArr[i]);
        tempChar = popArr[i];

        while(tempChar!=stringArray[0]){
            while(index%2==0){
                index = strlstchar(usedString, tempChar);
                lentemp = strlen(usedString);
                usedString[lentemp-index-1]=0;
                }

            printf("-%c", usedString[index-1]);
            tempChar=usedString[index-1];
            index=2;
            }
            printf("\n");
        }

    return 0;
    }

Thanks in advance!

Body:
The segmentation violation occurs in this line:

    usedString[lentemp - index - 1] = 0;

Here, you're trying to find the index from the end, but your strlstchar returns the index from the beginning, although it starts searching from the end. And you want truncate the string at the found character, of course.

Replace this line with just:

    usedString[index] = 0;

and you get the desired output.


问:
Retrieving data from local storage not working
I can save to local storage, but when I add code to retrieve the data it does not work. I can see the code has been saved as I have checked using F12 in chrome. Any guidance would be appreciated.

```<code> <!DOCTYPE html>
 <html>
 <head>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
 href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
 <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-
 1.4.5.min.js"></script>
 </head>
 <body>
 <form>
 <input type="text" id="task" placeholder="name">
 <input type="text" id="date" placeholder="dd/mm/yyyy">
 <input type="button" class="add-row" value="Add Row">

 </form>
 <table id="task_table">
 <thead>
    <tr>
        <th>Name</th>
        <th>Date</th>
    </tr>
 </thead>
 <tbody>
    <tr>
        <td>steve</td>
        <td>13/12/1956</td>
    </tr>

 </tbody>

 </table>
 <button id="saveAll">Save List</button>

 <script>$("#saveAll").click(function(e) {

 var listBirthdays = [];
 $("table td").each(function(){
   listBirthdays.push(this.innerHTML);
 })
 localStorage.setItem('birthdayList', JSON.stringify(listBirthdays));
 });

 </script>

 <script>
 $(document).ready(function(){
 $(".add-row").on('click',function(){
    var task = $("#task").val();
    var date = $("#date").val();
    var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
    $('table tbody').append(markup);

 });

            }
     );

;

</script>
</code>```

Below is shown the code that I tried to use to reload the data from storage.

```<code>loadList();

function loadList() {
if (localStorage.getItem('birthdayList')){
    var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));
    $("table td").each(function(i){
      this.innerHTML = listBirthdays [i];
    })
}
</code>```

}
   });

When i add code that should retrieve the data it does not add it back to the table.

答:
The problem lies in the .each loop in your loadList function.

Let's assume the stored value looks like this:

```<code>'["steve", "13/12/1956", "jane", "04/04/1987", "peter", "01/03/1999"]'
</code>```

It gets parsed and loaded into the listBirthdays array:

```<code>console.log(listBirthdays[0]) // -> "steve"
console.log(listBirthdays[1]) // -> "13/12/1956"
console.log(listBirthdays[2]) // -> "jane"
                              //     …etc.
</code>```

Then, the .each loop runs on your table cells:

```<code>$("table td").each(function(i){ … });
</code>```

…but the table body is still just one row with two cells:

```<code><td>steve</td>
<td>13/12/1956</td>
</code>```

So, the loop index (i) never gets past 1  – 0 for the cell with "steve", 1 for the cell with Steve's birth date. Then the loop ends, because there are no more cells:

```<code>// i = 0
this.innerHTML = listBirthdays[0]; // listBirthdays[0] = "steve"

// i = 1
this.innerHTML = listBirthdays[1]; // listBirthdays[1] = "13/12/1956"

// 'i' will never get to 2 as there are no more cells, listBirthdays[2] (and further) will never be used
</code>```

The cell content is replaced with the first two values from the listBirthdays array – steve is replaced with steve and 13/12/1956 is replaced with 13/12/1956. So it looks like nothing happened at all.

The simple solution is to just add the needed empty rows/cells before loading the data into table:

```<code>function loadList() {
  if (localStorage.getItem("birthdayList")) {
    var listBirthdays = JSON.parse(localStorage.getItem("birthdayList"));
    // calculate how many rows we need:
    var newRows = listBirthdays.length / 2; // for 2 columns
    // replace tbody content with the new rows:
    $("tbody").html("<tr><td></td><td></td></tr>".repeat(newRows));
    // table now has two cells for each name–date pair
    $("tbody td").each(function(i, cell) {
      cell.innerHTML = listBirthdays[i];
    });
  }
}
</code>```

Working example on Codepen (tried to post it here, but localStorage does not work in SO snippets)

However, a more logical approach would be to render the cells based on the data, not the other way around.

Body:
I can save to local storage, but when I add code to retrieve the data it does not work. I can see the code has been saved as I have checked using F12 in chrome. Any guidance would be appreciated.

 <!DOCTYPE html>

 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet"
 href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

 <form>
 <input type="text" id="task" placeholder="name">
 <input type="text" id="date" placeholder="dd/mm/yyyy">
 <input type="button" class="add-row" value="Add Row">

 </form>

        Name
        Date

        steve
        13/12/1956

 <button id="saveAll">Save List</button>

Below is shown the code that I tried to use to reload the data from storage.

loadList();

function loadList() {
if (localStorage.getItem('birthdayList')){
    var listBirthdays = JSON.parse(localStorage.getItem('birthdayList'));
    $("table td").each(function(i){
      this.innerHTML = listBirthdays [i];
    })
}

}
   });

When i add code that should retrieve the data it does not add it back to the table.

Body:
The problem lies in the .each loop in your loadList function.

Let's assume the stored value looks like this:

'["steve", "13/12/1956", "jane", "04/04/1987", "peter", "01/03/1999"]'

It gets parsed and loaded into the listBirthdays array:

console.log(listBirthdays[0]) // -> "steve"
console.log(listBirthdays[1]) // -> "13/12/1956"
console.log(listBirthdays[2]) // -> "jane"
                              //     …etc.

Then, the .each loop runs on your table cells:

$("table td").each(function(i){ … });

…but the table body is still just one row with two cells:

<td>steve</td>
<td>13/12/1956</td>

So, the loop index (i) never gets past 1  – 0 for the cell with "steve", 1 for the cell with Steve's birth date. Then the loop ends, because there are no more cells:

// i = 0
this.innerHTML = listBirthdays[0]; // listBirthdays[0] = "steve"

// i = 1
this.innerHTML = listBirthdays[1]; // listBirthdays[1] = "13/12/1956"

// 'i' will never get to 2 as there are no more cells, listBirthdays[2] (and further) will never be used

The cell content is replaced with the first two values from the listBirthdays array – steve is replaced with steve and 13/12/1956 is replaced with 13/12/1956. So it looks like nothing happened at all.

The simple solution is to just add the needed empty rows/cells before loading the data into table:

function loadList() {
  if (localStorage.getItem("birthdayList")) {
    var listBirthdays = JSON.parse(localStorage.getItem("birthdayList"));
    // calculate how many rows we need:
    var newRows = listBirthdays.length / 2; // for 2 columns
    // replace tbody content with the new rows:
    $("tbody").html("<tr><td></td><td></td></tr>".repeat(newRows));
    // table now has two cells for each name–date pair
    $("tbody td").each(function(i, cell) {
      cell.innerHTML = listBirthdays[i];
    });
  }
}

Working example on Codepen (tried to post it here, but localStorage does not work in SO snippets)

However, a more logical approach would be to render the cells based on the data, not the other way around.


问:
Python 2.7 build on Sublime Text 3 doesn't print the '\uFFFD' character

The problem.

I'm using Python 2.7 build on Sublime Text 3 and have an issue with printing out.

In some cases I get a pretty confusing output for '\uFFFD' - the 'REPLACEMENT CHARACTER'.

For example:

```<code>print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'
print u'\u0061' # should be 'a'
-----------------------------------------------------
[Finished in 0.1s]
</code>```

After inversion of the order:

```<code>print u'\u0061'
print u'\ufffd'
-----------------------------------------------------
a
�
[Finished in 0.1s]
</code>```

So, Sublime can printout the '�' character, but for some reason doesn't do it in the 1st case.

And the dependence of the output on the order of statements seems quite strange.

The problem with replacement char leads to very unpredictable printout behavior in general.

For example, I want to printout decoded bytes with error replacement:

```<code>cp1251_bytes = '\xe4\xe0' # 'да' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
��
[Finished in 0.1s]
</code>```

Let's replace the bytes:

```<code>cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
[Finished in 0.1s]
</code>```

And add one more print statement:

```<code>cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('cp1251')
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
нет
���
[Finished in 0.1s]
</code>```

Below is the illustration of implementation some other test cases:

Summarizing, there are the following patterns in the described printout behavior:

 it depends on the even/odd number of '\ufffd' chars in print statement

 it depends on the order of print statements

 it depends on the specific build run

My questions:

Why does this happen?

How to fix the problem?

My Python 2.7 sublime-build file:

```<code>{
    "cmd": ["C:\\_Anaconda3\\envs\\python27\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf-8"}
}
</code>```

With Python 2.7 installed separately from Anaconda the behavior is exactly the same.

答:
Edit-1 - Using UTF8 with BOM

Seems like BOM becomes important in case of windows. So you need to use below type build config

```<code>{
    "cmd": ["F:\\Python27-14\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {
        "PYTHONIOENCODING": "utf_8_sig"
    },
}
</code>```

After that it works correctly for me on windows also

Original Answer

I checked the issue and I didn't face the same on Python 2.7 with Sublime text. The only change being I had to add # -*- coding: utf-8 -*- to the top of the file. Which seems the missing part in this question

```<code># -*- coding: utf-8 -*-

print u'\u0061' # should be 'a'
print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'
</code>```

After that the reversal has no impact

You can see more details about this required header on

Why declare unicode by string in python?

Below is summary of the above link

When you specify # -*- coding: utf-8 -*-, you're telling Python the source file you've saved is utf-8. The default for Python 2 is ASCII (for Python 3 it's utf-8). This just affects how the interpreter reads the characters in the file.

Body:
The problem.

I'm using Python 2.7 build on Sublime Text 3 and have an issue with printing out.

In some cases I get a pretty confusing output for '\uFFFD' - the 'REPLACEMENT CHARACTER'.

For example:

print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'
print u'\u0061' # should be 'a'
-----------------------------------------------------
[Finished in 0.1s]

After inversion of the order:

print u'\u0061'
print u'\ufffd'
-----------------------------------------------------
a
�
[Finished in 0.1s]

So, Sublime can printout the '�' character, but for some reason doesn't do it in the 1st case.

And the dependence of the output on the order of statements seems quite strange.

The problem with replacement char leads to very unpredictable printout behavior in general.

For example, I want to printout decoded bytes with error replacement:

cp1251_bytes = '\xe4\xe0' # 'да' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
��
[Finished in 0.1s]

Let's replace the bytes:

cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
[Finished in 0.1s]

And add one more print statement:

cp1251_bytes = '\xed\xe5\xf2' # 'нет' in cp1251
print cp1251_bytes.decode('cp1251')
print cp1251_bytes.decode('utf-8', errors='replace')
-----------------------------------------------------
нет
���
[Finished in 0.1s]

Below is the illustration of implementation some other test cases:

Summarizing, there are the following patterns in the described printout behavior:

 it depends on the even/odd number of '\ufffd' chars in print statement

 it depends on the order of print statements

 it depends on the specific build run

My questions:

Why does this happen?

How to fix the problem?

My Python 2.7 sublime-build file:

{
    "cmd": ["C:\\_Anaconda3\\envs\\python27\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf-8"}
}

With Python 2.7 installed separately from Anaconda the behavior is exactly the same.

Body:
Edit-1 - Using UTF8 with BOM

Seems like BOM becomes important in case of windows. So you need to use below type build config

{
    "cmd": ["F:\\Python27-14\\python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {
        "PYTHONIOENCODING": "utf_8_sig"
    },
}

After that it works correctly for me on windows also

Original Answer

I checked the issue and I didn't face the same on Python 2.7 with Sublime text. The only change being I had to add # -*- coding: utf-8 -*- to the top of the file. Which seems the missing part in this question

# -*- coding: utf-8 -*-

print u'\u0061' # should be 'a'
print u'\ufffd' # should be '�' - the 'REPLACEMENT CHARACTER'

After that the reversal has no impact

You can see more details about this required header on

Why declare unicode by string in python?

Below is summary of the above link

When you specify # -*- coding: utf-8 -*-, you're telling Python the source file you've saved is utf-8. The default for Python 2 is ASCII (for Python 3 it's utf-8). This just affects how the interpreter reads the characters in the file.


问:
C: How to find the day name for a given day of the year input by user
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

```<code>int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}
</code>```

答:
Taken from "Compilers: Principles, Techniques and Tools" from Aho, Sethi and Ullman.

```<code>day = (1461 * year) / 4 + (153 * month + 2) / 5 + month_day;
</code>```

(beware that / means integer division here, all numbers must be integers) This formula is attributed to Tanzen[1963] there. if you apply % 7 to that formula, after applying the proper offset, you'll get the day of week.

Body:
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}

Body:
Taken from "Compilers: Principles, Techniques and Tools" from Aho, Sethi and Ullman.

day = (1461 * year) / 4 + (153 * month + 2) / 5 + month_day;

(beware that / means integer division here, all numbers must be integers) This formula is attributed to Tanzen[1963] there. if you apply % 7 to that formula, after applying the proper offset, you'll get the day of week.


问:
json in flashvars
I want to use josn in my flashvars and I'm having trouble

here is my json

```<code>var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };
</code>```

here is what I have been trying

```<code>    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }
</code>```

error_txt returns "object Object" but I can't access any part of the json object

答:
I believe what is happening here is that Javascript calls .toString() on your flashvars variable and passes the resulting string to flash.  If my hunch is correct you will need to pass the JSON as a string such as this.</p>

```<code>var flashvars = "{xmlFile:'myFile.xml',
                  preface:'Preface',
                   {
                    'url': 'flash/someflash.swf',
                    'x': '375',
                    'y': '237'
                   }
                 }";
</code>```

Title: json in flashvars

Body:
I want to use josn in my flashvars and I'm having trouble

here is my json

var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };

here is what I have been trying

    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }

error_txt returns "object Object" but I can't access any part of the json object

Body:
I believe what is happening here is that Javascript calls .toString() on your flashvars variable and passes the resulting string to flash.  If my hunch is correct you will need to pass the JSON as a string such as this.

var flashvars = "{xmlFile:'myFile.xml',
                  preface:'Preface',
                   {
                    'url': 'flash/someflash.swf',
                    'x': '375',
                    'y': '237'
                   }
                 }";


问:
Consuming locally hosted SOAP service via ANDROID APP
I'm currently working on a project where I want to consume a soap web service which is written in C# running on http://localhost:9063/WebService1.asmx via a android application. My database is in wampserver(mysql). I am exposing my database via soap web service written in C# to android application.

currently my android app and the localhost is on the same network(wifi). I want to invoke the soap service http://localhost:9063/WebService1.asmx via android application. I'm trying to communicate with the locally hosted web service from another machine via postmen while in the same network. But it fails to communicate with each other.

when i try access the soap service locally via postman i am getting this error too

Any tips on how to get this done would be appreciated.

答:
As the error says Data at the root level is invalid. Line 1, position 1 you should check your web service if you have implemented the data read part correctly.

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document.


问:
Error "syntax error near unexpected token '('" in Bash script when selecting files
Running this script, bash ./cleanup.bash,

```<code>#!/bin/bash
## Going to directory-moving stuff
rm -rf !(composer.json|.git)
</code>```

Gives the error:

cleanup.bash: line 10: syntax error near unexpected token '('
cleanup.bash: line 10: 'rm -rf !(composer.json|.git)'

But if I run in in the terminal directly, there aren't any problems:

```<code>rm -rf !(composer.json|.git)
</code>```

I tried stripping out all other lines, but I still get the error.

How do I enter this correctly in the Bash script?

I'm on Ubuntu, and this was all done locally, not on a remote.

答:
I guess your problem is due to the shell extended glob option not set when run from the script. When you claim it works in the command line, you have somehow set the extglob flag which allow to !() globs.

Since the Bash script, whenever started with a #!/bin/bash, starts a new sub-shell, the extended options set in the parent shell may not be reflected in the new shell. To make it take effect, set it in the script after the shebang:

```<code>#!/bin/bash

shopt -s extglob

## Going to directory-moving stuff
rm -rf !(composer.json|.git)
</code>```

Body:
Running this script, bash ./cleanup.bash,

#!/bin/bash
## Going to directory-moving stuff
rm -rf !(composer.json|.git)

Gives the error:

cleanup.bash: line 10: syntax error near unexpected token '('
cleanup.bash: line 10: 'rm -rf !(composer.json|.git)'

But if I run in in the terminal directly, there aren't any problems:

rm -rf !(composer.json|.git)

I tried stripping out all other lines, but I still get the error.

How do I enter this correctly in the Bash script?

I'm on Ubuntu, and this was all done locally, not on a remote.

Body:
I guess your problem is due to the shell extended glob option not set when run from the script. When you claim it works in the command line, you have somehow set the extglob flag which allow to !() globs.

Since the Bash script, whenever started with a #!/bin/bash, starts a new sub-shell, the extended options set in the parent shell may not be reflected in the new shell. To make it take effect, set it in the script after the shebang:

#!/bin/bash

shopt -s extglob

## Going to directory-moving stuff
rm -rf !(composer.json|.git)


问:
How to check if list contains all the same values?
I have a List[<DataType>] as input. I want to check if the list contains all the same values(not datatype).

Is there inbuilt method or intuitive way in Scala to do this instead of iterating over list and checking.

答:
One (inefficient but elegant) way is

```<code>List(1, 2, 2, 1, 1).distinct.length == 1 // returns false
List(1, 1, 1, 1, 1).distinct.length == 1 // returns true
List().distinct.length == 1 // empty list returns false
</code>```

Note that they must be of the same type

```<code>List(4, 4.0, "4").distinct.length == 1 // returns false
</code>```

Body:
One (inefficient but elegant) way is

List(1, 2, 2, 1, 1).distinct.length == 1 // returns false
List(1, 1, 1, 1, 1).distinct.length == 1 // returns true
List().distinct.length == 1 // empty list returns false

Note that they must be of the same type

List(4, 4.0, "4").distinct.length == 1 // returns false


问:
jQuery datepicker confirm dialog
I have this weird requirement with jQuery datepicker. I have a datepicker attached to an input, which already has dates fetched in from database. Now what I am looking to achieve is once I click on the input box the datepicker appears (default functionality of datepicker) and when I click on any other dates, it want a simple JavaScript confirm box with OK and Cancel, so clicking OK will change the dates and clicking Cancel will not.

Any idea how to do that?. I was able to create the confirm box and attach it to onSelect event from the datepicker. But the datepicker still changed dates even after clicking Cancel.

```<code>$('.date').datepicker({
        changeYear: true,
        changeMonth: true,
        onSelect: function (e) {
               var popup = confirm("Do you want to change dates?");
               if (popup == true) {

               } else {
                  return false
               }
           }
        }
    });
</code>```

答:
Store the previous value in data attribute and when canceled set the previous value. Try this</p>

```<code>$( document ).ready(function() {
    $('.date').data("prev", $(this).val());
    $('.date').datepicker({
        changeYear: true,
        changeMonth: true,
        onSelect: function (e) {
           var prevDate = $(this).data("prev");
           var popup = confirm("Do you want to change dates?");
           if (popup == true) {
                $('.date').data("prev", $(this).val());
           } else {
              $( ".date" ).datepicker('setDate',prevDate);
           }
       }
    });
});
</code>```

Title: jQuery datepicker confirm dialog

Body:
I have this weird requirement with jQuery datepicker. I have a datepicker attached to an input, which already has dates fetched in from database. Now what I am looking to achieve is once I click on the input box the datepicker appears (default functionality of datepicker) and when I click on any other dates, it want a simple JavaScript confirm box with OK and Cancel, so clicking OK will change the dates and clicking Cancel will not.

Any idea how to do that?. I was able to create the confirm box and attach it to onSelect event from the datepicker. But the datepicker still changed dates even after clicking Cancel.

$('.date').datepicker({
        changeYear: true,
        changeMonth: true,
        onSelect: function (e) {
               var popup = confirm("Do you want to change dates?");
               if (popup == true) {

               } else {
                  return false
               }
           }
        }
    });

Body:
Store the previous value in data attribute and when canceled set the previous value. Try this

$( document ).ready(function() {
    $('.date').data("prev", $(this).val());
    $('.date').datepicker({
        changeYear: true,
        changeMonth: true,
        onSelect: function (e) {
           var prevDate = $(this).data("prev");
           var popup = confirm("Do you want to change dates?");
           if (popup == true) {
                $('.date').data("prev", $(this).val());
           } else {
              $( ".date" ).datepicker('setDate',prevDate);
           }
       }
    });
});