答:
If you need to access a specific method from any part of your application, then that specific method must be part of your abstraction, or else there is no guarantee that you may use it when changing the concrete class.

I do not believe that your use of casting is a good idea at all, what is usually done in this case is to create a specific interface which defines any other method you could need to use:

```<code>public interface IFilaRepositorio : IRepositorio<Fila>
{
     void SomeCustomMethod();
}
</code>```

And than use and declare that specific interface in any part of your code where you believe you need to use it:

```<code>public class Processador
{
    private IFilaRepositorio _repoFila;
    public Processador(IFilaRepositorio  repoFila)
    {
        _repoFila = repoFila;
    }

    public void Processar()
    {
        _repoFila.SomeCustomMethod();
    }
}
</code>```

Title: Is it a good practice to cast from an interface to some concrete class when needed?

Body:
If you need to access a specific method from any part of your application, then that specific method must be part of your abstraction, or else there is no guarantee that you may use it when changing the concrete class.

I do not believe that your use of casting is a good idea at all, what is usually done in this case is to create a specific interface which defines any other method you could need to use:

public interface IFilaRepositorio : IRepositorio<Fila>
{
     void SomeCustomMethod();
}

And than use and declare that specific interface in any part of your code where you believe you need to use it:

public class Processador
{
    private IFilaRepositorio _repoFila;
    public Processador(IFilaRepositorio  repoFila)
    {
        _repoFila = repoFila;
    }

    public void Processar()
    {
        _repoFila.SomeCustomMethod();
    }
}


来源: stackexchange

问:
What would be the Go structs for this terse JSON document?
The document has minimal key/value pair metadata on purpose.  In a list of people, we could have something like "name":"joe" or we could have a key of joe.  It errs on having fewer keys.

Perhaps this document is just too dynamic for Go structs?  I've tried YAML as well, it's the structs that's the problem.  The structs remain empty because it's not mapping correctly.

Playground link: https://play.golang.org/p/PGSjoKvNja

Or do I need to roll my own UnmarshalJSON and have conditionals (or switch) for "actions"?  That's fine if so.  I could do coercion and validation in there, loop through the doc and detect what the problematic generic action bit is and then create a struct of the right type.

答:
It would be:

```<code>type AutoGenerated struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling,omitempty"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch,omitempty"`
    } `json:"frisbee"`
}
</code>```

Ofcourse you can define a separate type for each inline struct definition. You can use this online tool (which is used for generating the above data structure).

ContentLicense: CC BY-SA 3.0

Body:
It would be:

type AutoGenerated struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling,omitempty"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch,omitempty"`
    } `json:"frisbee"`
}

Ofcourse you can define a separate type for each inline struct definition. You can use this online tool (which is used for generating the above data structure).


问:
How can I convert an Object to Json in a Rabbit reply?
I have two applications communicating with each other using rabbit.

I need to send (from app1) an object to a listener (in app2) and after some process (on listener) it answer me with another object, now I am receiving this error:
ClassNotFound

I am using this config for rabbit in both applications:

```<code>@Configuration
public class RabbitConfiguration {

    public final static String EXCHANGE_NAME = "paymentExchange";

    public final static String EVENT_ROUTING_KEY = "eventRoute";
    public final static String PAYEMNT_ROUTING_KEY = "paymentRoute";

    public final static String QUEUE_EVENT = EXCHANGE_NAME + "." + "event";
    public final static String QUEUE_PAYMENT = EXCHANGE_NAME + "." + "payment";
    public final static String QUEUE_CAPTURE = EXCHANGE_NAME + "." + "capture";

    @Bean
    public List<Declarable> ds() {
        return queues(QUEUE_EVENT, QUEUE_PAYMENT);
    }

    @Autowired
    private ConnectionFactory rabbitConnectionFactory;

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(EXCHANGE_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate r = new RabbitTemplate(rabbitConnectionFactory);
        r.setExchange(EXCHANGE_NAME);
        r.setChannelTransacted(false);
        r.setConnectionFactory(rabbitConnectionFactory);
        r.setMessageConverter(jsonMessageConverter());
        return r;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    private List<Declarable> queues(String... nomes) {
        List<Declarable> result = new ArrayList<>();

        for (int i = 0; i < nomes.length; i++) {
            result.add(newQueue(nomes[i]));
            if (nomes[i].equals(QUEUE_EVENT))
                result.add(makeBindingToQueue(nomes[i], EVENT_ROUTING_KEY));
            else
                result.add(makeBindingToQueue(nomes[i], PAYEMNT_ROUTING_KEY));
        }
        return result;
    }

    private static Binding makeBindingToQueue(String queueName, String route) {
        return new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, route, null);
    }

    private static Queue newQueue(String nome) {
        return new Queue(nome);
    }

}
</code>```

I send the message using this:

```<code>String response = (String) rabbitTemplate.convertSendAndReceive(RabbitConfiguration.EXCHANGE_NAME,
            RabbitConfiguration.PAYEMNT_ROUTING_KEY, domainEvent);
</code>```

And await for a response using a cast to the object.

This communication is between two different applications using the same rabbit server.

How can I solve this?

I expected rabbit convert the message to a json in the send operation and the same in the reply, so I've created the object to correspond to a json of reply.

答:
Show, please, the configuration for the listener. You should be sure that ListenerContainer there is supplied with the Jackson2JsonMessageConverter as well to carry __TypeId__ header back with the reply.

Also see Spring AMQP JSON sample for some help.

Body:
I have two applications communicating with each other using rabbit.

I need to send (from app1) an object to a listener (in app2) and after some process (on listener) it answer me with another object, now I am receiving this error:
ClassNotFound

I am using this config for rabbit in both applications:

@Configuration
public class RabbitConfiguration {

    public final static String EXCHANGE_NAME = "paymentExchange";

    public final static String EVENT_ROUTING_KEY = "eventRoute";
    public final static String PAYEMNT_ROUTING_KEY = "paymentRoute";

    public final static String QUEUE_EVENT = EXCHANGE_NAME + "." + "event";
    public final static String QUEUE_PAYMENT = EXCHANGE_NAME + "." + "payment";
    public final static String QUEUE_CAPTURE = EXCHANGE_NAME + "." + "capture";

    @Bean
    public List<Declarable> ds() {
        return queues(QUEUE_EVENT, QUEUE_PAYMENT);
    }

    @Autowired
    private ConnectionFactory rabbitConnectionFactory;

    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(EXCHANGE_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate r = new RabbitTemplate(rabbitConnectionFactory);
        r.setExchange(EXCHANGE_NAME);
        r.setChannelTransacted(false);
        r.setConnectionFactory(rabbitConnectionFactory);
        r.setMessageConverter(jsonMessageConverter());
        return r;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    private List<Declarable> queues(String... nomes) {
        List<Declarable> result = new ArrayList<>();

        for (int i = 0; i < nomes.length; i++) {
            result.add(newQueue(nomes[i]));
            if (nomes[i].equals(QUEUE_EVENT))
                result.add(makeBindingToQueue(nomes[i], EVENT_ROUTING_KEY));
            else
                result.add(makeBindingToQueue(nomes[i], PAYEMNT_ROUTING_KEY));
        }
        return result;
    }

    private static Binding makeBindingToQueue(String queueName, String route) {
        return new Binding(queueName, DestinationType.QUEUE, EXCHANGE_NAME, route, null);
    }

    private static Queue newQueue(String nome) {
        return new Queue(nome);
    }

}

I send the message using this:

String response = (String) rabbitTemplate.convertSendAndReceive(RabbitConfiguration.EXCHANGE_NAME,
            RabbitConfiguration.PAYEMNT_ROUTING_KEY, domainEvent);

And await for a response using a cast to the object.

This communication is between two different applications using the same rabbit server.

How can I solve this?

I expected rabbit convert the message to a json in the send operation and the same in the reply, so I've created the object to correspond to a json of reply.


问:
Is it good idea to write multi level inline functions in C++?
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

```<code>inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}
</code>```

答:
If it helps readability of your code, then yes. You should almost always aim for readability of your code. Don't forget to properly name your functions so other people will easily understand what is that function doing. And by other people I mean you too in few weeks or months.  As they say you write code once but read it many times.<br>
As for the performance, modern compilers know when to inline the function and you should not worry about it. In cases where it really matters you will just use the profiler to find the hostspot and eventually change it. But it will happen much fewer times than you think. You will almost always find better ways to optimize your code. </p>

Body:
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}

Body:
If it helps readability of your code, then yes. You should almost always aim for readability of your code. Don't forget to properly name your functions so other people will easily understand what is that function doing. And by other people I mean you too in few weeks or months.  As they say you write code once but read it many times.

As for the performance, modern compilers know when to inline the function and you should not worry about it. In cases where it really matters you will just use the profiler to find the hostspot and eventually change it. But it will happen much fewer times than you think. You will almost always find better ways to optimize your code.


问:
permission denied while running cronjob
I have a cronjob which is scheduled to run every 4 mins.Cron is running properly but it fails to execute the .sh file it supposed to run.Cron rule is following :

```<code>*/15 * * * * cd /var/www/html/etl_project && ./run_etl_incomplete.sh >> /var/www/html/etl_project/cron_log.txt 2>&1
</code>```

in cron_log.txt i am getting the following permission denied error :

```<code>/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
</code>```

答:
I presume its your own personal user that you are using for this cron, which does not have permission to execute the file. Perhaps the file was created as root user or as some other user and therefore the credentials are not set to allow your user to execute.

First - Try to check what permissions are set on the file

```<code>ls -l /var/www/html/etl_project/ | grep run_etl_incomplete.sh
</code>```

Check the output to see who is the owner and group and what permissions are set.

To make the file executable -

```<code>chmod +x /var/www/html/etl_project/run_etl_incomplete.sh
</code>```

This will work only if you have the correct permissions in the first place (if your user is part of the group for example) to modify the file.
Once the file is made executable your cron will run.

Title: permission denied while running cronjob

Body:
I have a cronjob which is scheduled to run every 4 mins.Cron is running properly but it fails to execute the .sh file it supposed to run.Cron rule is following :

*/15 * * * * cd /var/www/html/etl_project && ./run_etl_incomplete.sh >> /var/www/html/etl_project/cron_log.txt 2>&1

in cron_log.txt i am getting the following permission denied error :

/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied
/bin/sh: 1: ./run_etl_incomplete.sh: Permission denied

Body:
I presume its your own personal user that you are using for this cron, which does not have permission to execute the file. Perhaps the file was created as root user or as some other user and therefore the credentials are not set to allow your user to execute.

First - Try to check what permissions are set on the file

ls -l /var/www/html/etl_project/ | grep run_etl_incomplete.sh

Check the output to see who is the owner and group and what permissions are set.

To make the file executable -

chmod +x /var/www/html/etl_project/run_etl_incomplete.sh

This will work only if you have the correct permissions in the first place (if your user is part of the group for example) to modify the file.
Once the file is made executable your cron will run.


问:
Why is this form validation not working?

$("#addAlertForm").validate();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form id="addAlertForm" action="" method="post">
  <div class="form-group form-float">
    <div class="form-line">
      <input type="text" name="alertText" class="form-control" maxlength="200" required>
      <label class="form-label">Alert Text</label>
    </div>
  </div>
  <div class="form-group">
    <input type="checkbox" name="alertCheckbox" id="md_checkbox_10" class="chk-col-green" />
    <label for="md_checkbox_10">Alert can be dismissed</label>
  </div>
</form></code>```

and it doesn't work, I press on the submit button with the field empty and no error message appears under the input telling that it is empty.

答:
Your validate call should be written on ready like below:

```<code>$().ready(function() {
    $("#addAlertForm").validate();
});
</code>```

Remember, this is triggered on form submit or when you press return/enter on the respective field.

Body:
$("#addAlertForm").validate();

<form id="addAlertForm" action="" method="post">

      <input type="text" name="alertText" class="form-control" maxlength="200" required>
      Alert Text

    <input type="checkbox" name="alertCheckbox" id="md_checkbox_10" class="chk-col-green" />
    Alert can be dismissed

</form>

and it doesn't work, I press on the submit button with the field empty and no error message appears under the input telling that it is empty.

Body:
Your validate call should be written on ready like below:

$().ready(function() {
    $("#addAlertForm").validate();
});

Remember, this is triggered on form submit or when you press return/enter on the respective field.


问:
Tabbing visual selection
In many GUIs when I select a section of text and then hit the Tab or Shift+Tab button the selected section will indent in or out.

In VIM I can select a visual section and then hit the < or > key to change indenting, however once I hit the < key my selection is cleared so I am stuck selecting the section again and hitting < again. This gets really annoying when I am trying to indent something a few stops in and want visual feedback.

Is there anyway to indent stuff in and out in vim while keeping the current selected text selected?

Is there a trick to re-map Tab and Shift+Tab so they behave in this way in visual mode?

答:
```<code>vmap <Tab> >gv
vmap <S-Tab> <gv
</code>```

ContentLicense: CC BY-SA 4.0

Title: Tabbing visual selection

Body:
vmap <Tab> >gv
vmap <S-Tab> <gv

OwnerDisplayName: Brian C.

ContentLicense: CC BY-SA 2.5


问:
SMTP is not sending emails in gmail business account
This code is working well in gmail personal account, but when I try to use gmail business account, it is not working and keeps giving an error. 5.5.1 Authentication Required. </p>

```<code>void SendEmail()
{
    DataTable data = GetData();
    DataTable email_data = GetEmailData();
    data.TableName = "Employee_Data";

    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(data);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            String from = "seong@abcd.net";

            for (int i = 0; i < email_data.Rows.Count; i++)
            {
                String to = email_data.Rows[i][0].ToString();

                using (MailMessage mm = new MailMessage(from, to))
                {
                    mm.Subject = "Employees Attachment";
                    mm.Body = "Employees Exported Attachment";

                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Employees.xlsx"));
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                    credentials.UserName = "seong@abcd.net";
                    credentials.Password = "1234";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}
</code>```

答:
I solved this problem.
The account should not use 2nd verification in gmail if you want to use SMTP.

https://support.google.com/accounts/answer/1064203?hl=en&ref_topic=7189195

I can't control those things, I ask the administrator allow not to use 2nd verification.
So I can work with that account using SMTP.

Body:
This code is working well in gmail personal account, but when I try to use gmail business account, it is not working and keeps giving an error. 5.5.1 Authentication Required.

void SendEmail()
{
    DataTable data = GetData();
    DataTable email_data = GetEmailData();
    data.TableName = "Employee_Data";

    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(data);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            String from = "seong@abcd.net";

            for (int i = 0; i < email_data.Rows.Count; i++)
            {
                String to = email_data.Rows[i][0].ToString();

                using (MailMessage mm = new MailMessage(from, to))
                {
                    mm.Subject = "Employees Attachment";
                    mm.Body = "Employees Exported Attachment";

                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Employees.xlsx"));
                    mm.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                    credentials.UserName = "seong@abcd.net";
                    credentials.Password = "1234";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }
}


问:
How to compare RPM's between x2 different Jenkins VMs?
I installed two jenkins VMs and I would like to compare the RPMS between the two VMS.

Can this be done from putty? Or is there a way to export the results to an output file?

答: The rpm -q queries and you can get a specific format with --queryformat. To compare two versions you're on your own.


问:
Cursor Index Out of Bounds exception
I keep getting this error message:  "Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" in my code.

I have already referenced the following links, but none of them have worked:
Android cursor out of bounds exception

Cursor index out of bounds

Cursor Index Out Of Bounds Error Android?

cursor index out of bounds exception

```<code>  public Product getProduct(int id) {
    db = this.getReadableDatabase();

    Cursor cursor = db.query(
            TABLE_NAME,
            null,
            COLUMN_ID + " = ?",
            new String[] { Integer.toString(id)},
            null, null, null, null);

    Product product = new Product();

    cursor.moveToFirst();
    if (cursor != null) {
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
        cursor.close();
    }

    db.close();
    return product;
}
</code>```

And here are my constants:

```<code>private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";
</code>```

I would greatly appreciate any help.

Now, it won't go into the if-loop. I got that query model straight from another stack overflow question.

答:
It is very likely that the cursor is empty, as such you need to ascertain why. It could be that there is no underlying data or it could be that the cursor where clause is excluding all data. From what you have provided it is impossible to determine why.

I would suggest removing the where clause to see if this changes matters.

i.e. instead of

```<code>    Cursor cursor = db.query(
        TABLE_NAME,
        null,
        COLUMN_ID + " = ?",
        new String[] { Integer.toString(id)},
        null, null, null, null);
</code>```

use :-

```<code>    Cursor cursor = db.query(
        TABLE_NAME,
        null,
        null,
        null,
        null, null, null, null);
</code>```

This would return all rows from the cursor, if this works then the issue is with the where clause (3rd and 4th parameters passed to db.query). If it doesn't resolve the issue then it is likely that the table itself has no rows.

You could circumvent the CursorIndexOutOfBoundsException by using :-

```<code>    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
    } else {
        // setup to return a product not found
    }
    cursor.close();
</code>```

However, this won't fix the underlying issue that the cursor is not returning any rows.

You could use something like the following to get more information regarding the cursor (running with the cursor selecting all rows as per change above). This should work for any cursor :-

```<code>    int rowcount = cursor.getCount();
    String colnames = "";
    for (String columns : cursor.getColumnNames()) {
        colnames = colnames +
                "Column Index=" +
                Integer.toString(cursor.getColumnIndex(columns)) +
                " Name=>" +
                columns +
                "<  ";
    }
    Log.d("DBCHK","Table has " + Integer.toString(rowcount) + " rows. With columns:- " + colnames);
    String values;
    while (cursor.moveToNext()) {
        values = "";
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            values = values +
                    "Column = " +
                    cursor.getColumnName(i) +
                    " Index=" +
                    Integer.toString(i) +
                    " Value=" + cursor.getString(i) + ": ";
        }
        Log.d("DBCHK",values);
    }
</code>```

This would write data to the log along the lines of :-

```<code>D/DBCHK: Table has 2 rows. With columns:- Column Index=0 Name=>_id<  Column Index=1 Name=>myfloat<
D/DBCHK: Column = _id Index=0 Value=null: Column = myfloat Index=1 Value=56.7897:
D/DBCHK: Column = _id Index=0 Value=null: Column = myfloat Index=1 Value=87.7655:
</code>```

There will be a line per row, these preceded with a line listing the number of rows and what the columns are.

Title: Cursor Index Out of Bounds exception

Body:
I keep getting this error message:  "Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" in my code.

I have already referenced the following links, but none of them have worked:
Android cursor out of bounds exception

Cursor index out of bounds

Cursor Index Out Of Bounds Error Android?

cursor index out of bounds exception

  public Product getProduct(int id) {
    db = this.getReadableDatabase();

    Cursor cursor = db.query(
            TABLE_NAME,
            null,
            COLUMN_ID + " = ?",
            new String[] { Integer.toString(id)},
            null, null, null, null);

    Product product = new Product();

    cursor.moveToFirst();
    if (cursor != null) {
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
        cursor.close();
    }

    db.close();
    return product;
}

And here are my constants:

private static final String TABLE_NAME = "Products";
private static final String COLUMN_ID = "'_id'";

I would greatly appreciate any help.

Now, it won't go into the if-loop. I got that query model straight from another stack overflow question.

Body:
It is very likely that the cursor is empty, as such you need to ascertain why. It could be that there is no underlying data or it could be that the cursor where clause is excluding all data. From what you have provided it is impossible to determine why.

I would suggest removing the where clause to see if this changes matters.

i.e. instead of

    Cursor cursor = db.query(
        TABLE_NAME,
        null,
        COLUMN_ID + " = ?",
        new String[] { Integer.toString(id)},
        null, null, null, null);

use :-

    Cursor cursor = db.query(
        TABLE_NAME,
        null,
        null,
        null,
        null, null, null, null);

This would return all rows from the cursor, if this works then the issue is with the where clause (3rd and 4th parameters passed to db.query). If it doesn't resolve the issue then it is likely that the table itself has no rows.

You could circumvent the CursorIndexOutOfBoundsException by using :-

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        product.setID(cursor.getInt(0));
        product.setName(cursor.getString(1));
        product.setSize(cursor.getDouble(2));
        product.setHp(cursor.getDouble(3));
        product.setCategory(cursor.getString(4));
        product.setPowerType(cursor.getString(5));
        product.setExplosionProof(cursor.getInt(6));
        product.setRPM(cursor.getInt(7));
        product.setBypassPSI(cursor.getInt(8));
        product.setGPM(cursor.getInt(9));
        product.setPrice(cursor.getDouble(10));
    } else {
        // setup to return a product not found
    }
    cursor.close();

However, this won't fix the underlying issue that the cursor is not returning any rows.

You could use something like the following to get more information regarding the cursor (running with the cursor selecting all rows as per change above). This should work for any cursor :-

    int rowcount = cursor.getCount();
    String colnames = "";
    for (String columns : cursor.getColumnNames()) {
        colnames = colnames +
                "Column Index=" +
                Integer.toString(cursor.getColumnIndex(columns)) +
                " Name=>" +
                columns +
                "<  ";
    }
    Log.d("DBCHK","Table has " + Integer.toString(rowcount) + " rows. With columns:- " + colnames);
    String values;
    while (cursor.moveToNext()) {
        values = "";
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            values = values +
                    "Column = " +
                    cursor.getColumnName(i) +
                    " Index=" +
                    Integer.toString(i) +
                    " Value=" + cursor.getString(i) + ": ";
        }
        Log.d("DBCHK",values);
    }

This would write data to the log along the lines of :-

D/DBCHK: Table has 2 rows. With columns:- Column Index=0 Name=>_id<  Column Index=1 Name=>myfloat<
D/DBCHK: Column = _id Index=0 Value=null: Column = myfloat Index=1 Value=56.7897:
D/DBCHK: Column = _id Index=0 Value=null: Column = myfloat Index=1 Value=87.7655:

There will be a line per row, these preceded with a line listing the number of rows and what the columns are.


问:
Stack Smashing Detected in GCC
I'm new to C and I've found a peculiar output from gcc that I'm having a hard time getting to the bottom of. The error upon running the application is:

```<code>*** stack smashing detected ***: /home/joshua/Research/cml/test terminated

Program received signal SIGABRT, Aborted.
0x00007ffff7a43428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
</code>```

I've done some research on this, and it appears that this is many times caused by tying to put too large a value into an array, for example; I'm not doing anything like that.

Here is my sample code for reference:

```<code> 1 #include <stdio.h>
  2 #include <string.h>
  3
  4 struct student
  5 {
  6      int id;
  7      char name[10];
  8      float percentage;
  9 };
 10
 11 int main()
 12 {
 13      int i;
 14      struct student record[2];
 15
 16      // 1st student's record
 17      record[0].id=1;
 18      strcpy(record[0].name, "Raju");
 19      record[0].percentage = 86.5;
 20
 21      // 2nd student's record
 22      record[1].id=2;
 23      strcpy(record[1].name, "Surendren");
 24      record[1].percentage = 90.5;
 25
 26      // 3rd student's record
 27      record[2].id=3;
 28      strcpy(record[2].name, "Thiyagu");
 29      record[2].percentage = 81.5;
 30
 31      for(i=0; i<3; i++)
 32      {
 33          printf("     Records of STUDENT : %d \n", i+1);
 34          printf(" Id is: %d \n", record[i].id);
 35          printf(" Name is: %s \n", record[i].name);
 36          printf(" Percentage is: %f\n\n",record[i].percentage);
 37      }
 38      return 0;
 39 }
</code>```

答: To keep a check on the integrity of the functions, next to the return statement Gcc adds protection variables (called canaries) which have known values.In your case when the uninitialized access is done on record[2] you have violated the stacks integrity and the canary values are overwritten which trigger the crash.</p>

Title: Stack Smashing Detected in GCC

Body:
I'm new to C and I've found a peculiar output from gcc that I'm having a hard time getting to the bottom of. The error upon running the application is:

*** stack smashing detected ***: /home/joshua/Research/cml/test terminated

Program received signal SIGABRT, Aborted.
0x00007ffff7a43428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.

I've done some research on this, and it appears that this is many times caused by tying to put too large a value into an array, for example; I'm not doing anything like that.

Here is my sample code for reference:

 1 #include <stdio.h>
  2 #include <string.h>
  3
  4 struct student
  5 {
  6      int id;
  7      char name[10];
  8      float percentage;
  9 };
 10
 11 int main()
 12 {
 13      int i;
 14      struct student record[2];
 15
 16      // 1st student's record
 17      record[0].id=1;
 18      strcpy(record[0].name, "Raju");
 19      record[0].percentage = 86.5;
 20
 21      // 2nd student's record
 22      record[1].id=2;
 23      strcpy(record[1].name, "Surendren");
 24      record[1].percentage = 90.5;
 25
 26      // 3rd student's record
 27      record[2].id=3;
 28      strcpy(record[2].name, "Thiyagu");
 29      record[2].percentage = 81.5;
 30
 31      for(i=0; i<3; i++)
 32      {
 33          printf("     Records of STUDENT : %d \n", i+1);
 34          printf(" Id is: %d \n", record[i].id);
 35          printf(" Name is: %s \n", record[i].name);
 36          printf(" Percentage is: %f\n\n",record[i].percentage);
 37      }
 38      return 0;
 39 }


问:
Stored procedure from Oracle doesn't work with Entity Framework database-first workflow
I have a problem when I try to call a stored procedure from Oracle. I could correctly import the stored procedure which was mapped to a function which I called AddVideo, but when running this function it throws a System.ArgumentException exception that I do not know why it can be.

This is my stored procedure in Oracle:

```<code>create or replace procedure SP_ADD_VIDEO
     (p_name in varchar2, p_release_date in date, p_genre in varchar2)
is
    genreId number;
    maxVideoId number;
begin
  select G.ID into genreId
  from GENRES G
  where G.NAME = p_genre;

  insert into VIDEOS(ID, NAME, RELEASEDATE)
  values(SEQ_VIDEOS.NEXTVAL, p_name, p_release_date);

  select MAX(V.ID) into maxVideoId
  from VIDEOS V;

  insert into VIDEOGENRES(VIDEOID,GENREID)
  values(maxVideoId,genreId);
end SP_ADD_VIDEO;
</code>```

And this is my mapped function:

```<code>public virtual int AddVideo(string p_NAME, Nullable<System.DateTime> p_RELEASE_DATE, string p_GENRE)
{
    var p_NAMEParameter = p_NAME != null ?
        new ObjectParameter("P_NAME", p_NAME) :
        new ObjectParameter("P_NAME", typeof(string));

    var p_RELEASE_DATEParameter = p_RELEASE_DATE.HasValue ?
        new ObjectParameter("P_RELEASE_DATE", p_RELEASE_DATE) :
        new ObjectParameter("P_RELEASE_DATE", typeof(System.DateTime));

    var p_GENREParameter = p_GENRE != null ?
        new ObjectParameter("P_GENRE", p_GENRE) :
        new ObjectParameter("P_GENRE", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("AddVideo", p_NAMEParameter, p_RELEASE_DATEParameter, p_GENREParameter);
}
</code>```

And this is where I call the AddVideo function to insert the given values as parameters into the stored procedure:

```<code>class Program
{
    static void Main(string[] args)
    {
        var dbContext = new VidzyDbContext();
        dbContext.AddVideo("Gladiator", DateTime.Today, "Action");
    }
}
</code>```

I hope someone can help me solve this problem.

答:
I can't tell if it would work for Oracle, but in MSSQL, you'd have to do this:

```<code>return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction(
    "SP_ADD_VIDEO @P_NAME, @P_RELEASE_DATE, @P_GENRE",
    p_NAMEParameter, p_RELEASE_DATEParameter, p_GENREParameter);
</code>```

When you do create your parameters, continue not putting the @ when you do new ObjectParameter... though.

I always had my parameters names with the same casing in the code as in the database, so I'm not sure if you should adjust to lowercase in the code to match the database or not.

Body:
I have a problem when I try to call a stored procedure from Oracle. I could correctly import the stored procedure which was mapped to a function which I called AddVideo, but when running this function it throws a System.ArgumentException exception that I do not know why it can be.

This is my stored procedure in Oracle:

create or replace procedure SP_ADD_VIDEO
     (p_name in varchar2, p_release_date in date, p_genre in varchar2)
is
    genreId number;
    maxVideoId number;
begin
  select G.ID into genreId
  from GENRES G
  where G.NAME = p_genre;

  insert into VIDEOS(ID, NAME, RELEASEDATE)
  values(SEQ_VIDEOS.NEXTVAL, p_name, p_release_date);

  select MAX(V.ID) into maxVideoId
  from VIDEOS V;

  insert into VIDEOGENRES(VIDEOID,GENREID)
  values(maxVideoId,genreId);
end SP_ADD_VIDEO;

And this is my mapped function:

public virtual int AddVideo(string p_NAME, Nullable<System.DateTime> p_RELEASE_DATE, string p_GENRE)
{
    var p_NAMEParameter = p_NAME != null ?
        new ObjectParameter("P_NAME", p_NAME) :
        new ObjectParameter("P_NAME", typeof(string));

    var p_RELEASE_DATEParameter = p_RELEASE_DATE.HasValue ?
        new ObjectParameter("P_RELEASE_DATE", p_RELEASE_DATE) :
        new ObjectParameter("P_RELEASE_DATE", typeof(System.DateTime));

    var p_GENREParameter = p_GENRE != null ?
        new ObjectParameter("P_GENRE", p_GENRE) :
        new ObjectParameter("P_GENRE", typeof(string));

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("AddVideo", p_NAMEParameter, p_RELEASE_DATEParameter, p_GENREParameter);
}

And this is where I call the AddVideo function to insert the given values as parameters into the stored procedure:

class Program
{
    static void Main(string[] args)
    {
        var dbContext = new VidzyDbContext();
        dbContext.AddVideo("Gladiator", DateTime.Today, "Action");
    }
}

I hope someone can help me solve this problem.

Body:
I can't tell if it would work for Oracle, but in MSSQL, you'd have to do this:

return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction(
    "SP_ADD_VIDEO @P_NAME, @P_RELEASE_DATE, @P_GENRE",
    p_NAMEParameter, p_RELEASE_DATEParameter, p_GENREParameter);

When you do create your parameters, continue not putting the @ when you do new ObjectParameter... though.

I always had my parameters names with the same casing in the code as in the database, so I'm not sure if you should adjust to lowercase in the code to match the database or not.


问:
can't interpret PHP on RHEL + nginx
I'm doing the following steps and can't seem to have the PHP interpreted. I've done many variants of this, searched the web extensively and shown it to a friend: we don't understand what we do wrong. Could you help?

Launch RHEL 7.3 Amazon free tier instance

Connect in SSH with mac Terminal app

```sudo yum install wget
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo rpm -Uvh epel-release-latest-7*.rpm
sudo yum install nginx
sudo service nginx restart```

open port 80 in rehl instance inbound rules

check http://[my_instance_name].eu-central-1.compute.amazonaws.com/, it displays the welcome to nginx on Fedora page

install php and configure nginx

```sudo yum install php-fpm
sudo yum install nano
sudo nano /etc/php.ini, and in the file, set cgi.fix_pathinfo=0
sudo nano /etc/nginx/nginx.conf, and set the worker processes to 4 (value was: auto)
sudo nano /etc/nginx/conf.d/default.conf and have the following conf:

    server {
        listen       80;
        server_name localhost;

        location / {
            root   /usr/share/nginx/html;
            index index.php  index.html index.htm;
        }

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           /usr/share/nginx/html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
```

configure php

```sudo nano /etc/php-fpm.d/www.conf and confirm user and group are php-fpm
sudo service php-fpm restart
sudo nano /usr/share/nginx/html/info.php containing phpinfo(); (with the php tags, stackoverflow seems to hide it)
sudo service nginx restart
sudo chkconfig --levels 235 nginx on
sudo chkconfig --levels 235 php-fpm on
```

browse to http://[my_instance_name].eu-central-1.compute.amazonaws.com/info.php : it downloads the php file instead of interpreting it

change step /etc/php-fpm.d/www.conf and say that user and group are nginx, restart nginx, php file still downloaded instead of interpreted

change step /etc/nginx/conf.d/default.conf and say server_name = [IP of my instance], restart nginx, php file still downloaded instead of interpreted

What am I missing?

答:
First of all check logs at /var/log/nginx and /var/log/php-fpm

Second, Check using netstat -lnp that php-fpm do listen on port 9000

Third, This is the nginx configuration that works for me:

```<code>location ~ [^/]\.php(/|$) {
                fastcgi_split_path_info  ^(.+\.php)(/.*)$;
                try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param   PATH_INFO $fastcgi_path_info;
                include fastcgi_params;
    }
</code>```

Title: can't interpret PHP on RHEL + nginx

Body:
I'm doing the following steps and can't seem to have the PHP interpreted. I've done many variants of this, searched the web extensively and shown it to a friend: we don't understand what we do wrong. Could you help?

Launch RHEL 7.3 Amazon free tier instance

Connect in SSH with mac Terminal app

sudo yum install wget
wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo rpm -Uvh epel-release-latest-7*.rpm
sudo yum install nginx
sudo service nginx restart

open port 80 in rehl instance inbound rules

check http://[my_instance_name].eu-central-1.compute.amazonaws.com/, it displays the welcome to nginx on Fedora page

install php and configure nginx

sudo yum install php-fpm
sudo yum install nano
sudo nano /etc/php.ini, and in the file, set cgi.fix_pathinfo=0
sudo nano /etc/nginx/nginx.conf, and set the worker processes to 4 (value was: auto)
sudo nano /etc/nginx/conf.d/default.conf and have the following conf:

    server {
        listen       80;
        server_name localhost;

        location / {
            root   /usr/share/nginx/html;
            index index.php  index.html index.htm;
        }

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           /usr/share/nginx/html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }

configure php

sudo nano /etc/php-fpm.d/www.conf and confirm user and group are php-fpm
sudo service php-fpm restart
sudo nano /usr/share/nginx/html/info.php containing phpinfo(); (with the php tags, stackoverflow seems to hide it)
sudo service nginx restart
sudo chkconfig --levels 235 nginx on
sudo chkconfig --levels 235 php-fpm on

browse to http://[my_instance_name].eu-central-1.compute.amazonaws.com/info.php : it downloads the php file instead of interpreting it

change step /etc/php-fpm.d/www.conf and say that user and group are nginx, restart nginx, php file still downloaded instead of interpreted

change step /etc/nginx/conf.d/default.conf and say server_name = [IP of my instance], restart nginx, php file still downloaded instead of interpreted

What am I missing?

Body:
First of all check logs at /var/log/nginx and /var/log/php-fpm

Second, Check using netstat -lnp that php-fpm do listen on port 9000

Third, This is the nginx configuration that works for me:

location ~ [^/]\.php(/|$) {
                fastcgi_split_path_info  ^(.+\.php)(/.*)$;
                try_files $uri =404;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param   PATH_INFO $fastcgi_path_info;
                include fastcgi_params;
    }


问:
Page loading scrolled to bottom
Has anyone had the issue where some versions IE7 and 9beta will load a page scrolled to the bottom? This only happens when clicking from the main nav, not directly inputting the url. Here's an example

How would I add a scrollTop function to each main nav link via jQuery? Would that be an acceptable workaround?

答:
As a workaround, you could add this to each page:

```<code>$(document).ready(function() {
  $(document).scrollTop(0);
});
</code>```

You wouldn't be able to add this to the links, as the script needs to run after the page load.  This also feels hacky without knowing what is causing the problem, but with IE, I would rather hack sometimes than know...

Title: Page loading scrolled to bottom

Body:
As a workaround, you could add this to each page:

$(document).ready(function() {
  $(document).scrollTop(0);
});

You wouldn't be able to add this to the links, as the script needs to run after the page load.  This also feels hacky without knowing what is causing the problem, but with IE, I would rather hack sometimes than know...


问:
Call a js function from jsf code
How can i call a javascript function from jsf file.
I have an input text in xhtml page
And a js function that changes the text value, regrading some conditions.
I want to change its value  by call the js function from a java method in a jsf file

答: In JSF you never call Javascript from Java code. If you need to have Javascript to change text input value of the generated HTML then you need to have that JSF page define inline Javascript (or import Javascript file) that will be executed by some type of HTML DOM event such from onload or another HTML element.

Title: Call a js function from jsf code


问:
doesn't setup.py develop use wheel for install_requires?
I have the impression that (using setuptools):

```<code>python setup.py develop
</code>```

Won't use wheels when installing required packages (specified in install_requires).

Questions:

is my impression correct?

is there a way to force it to use wheel?

I am talking about this particular setup script.

答:
For whatever reason, setuptools simply wont use wheels. The likely explanation is that setuptools is older than wheels, and no one has updated it to use them.

Using pip install . works however, since pip is fine with wheels. In your case with python setup.py develop that would be pip install --editable ..

So, to answer your points:

Yes, setup.py/setuptools wont use wheels.

No, not at this time. But you could use pip instead of running setup.py directly.

Similar questions:

Can python setup.py install use wheels?

How to instrument setup.py to use wheel packages

Body:
I have the impression that (using setuptools):

python setup.py develop

Won't use wheels when installing required packages (specified in install_requires).

Questions:

is my impression correct?

is there a way to force it to use wheel?

I am talking about this particular setup script.


问:
Producing multiple full copies of an array based on a criterion in Matlab
I'm trying to figure out an array-indexing method to save the entire array for each value above a cutoff. The matrices I'm working with have ~10^9 elements, so writing a for loop is out of the question.

As an example, suppose there's a matrix

```<code>Vals=[96 92 97;83 90 95]
</code>```

and since my cutoff is 95 this corresponds to a matrix

```<code>ExceedsCutoff=[1 0 1;0 0 1]
</code>```

I would like to use ExceedsCutoff as a logical to produce a matrix WantedOutput with

```<code>WantedOutput(1,:,:)=Vals
WantedOutput(2,:,:)=zeros(2,3)
WantedOutput(3,:,:)=zeros(2,3)
WantedOutput(4,:,:)=zeros(2,3)
WantedOutput(5,:,:)=Vals
WantedOutput(6,:,:)=Vals
</code>```

since the 1st, 5th, and 6th elements of ExceedsCutoff are 1. Any ideas on how to do this? Thanks!!

答:
A simple multiplication with bsxfun() will do this for you:</p>

```<code>Vals=[96 92 97;83 90 95];
Vals=permute(Vals,[3,1,2]);
Cutoff = 95;
ExceedsCutoff=Vals >= Cutoff;

WantedOutput = bsxfun(@times,ExceedsCutoff(:),Vals);
% Or, for MATLAB2016b and older
WantedOutput = ExceedsCutoff(:).*Vals;
</code>```

Body:
I'm trying to figure out an array-indexing method to save the entire array for each value above a cutoff. The matrices I'm working with have ~10^9 elements, so writing a for loop is out of the question.

As an example, suppose there's a matrix

Vals=[96 92 97;83 90 95]

and since my cutoff is 95 this corresponds to a matrix

ExceedsCutoff=[1 0 1;0 0 1]

I would like to use ExceedsCutoff as a logical to produce a matrix WantedOutput with

WantedOutput(1,:,:)=Vals
WantedOutput(2,:,:)=zeros(2,3)
WantedOutput(3,:,:)=zeros(2,3)
WantedOutput(4,:,:)=zeros(2,3)
WantedOutput(5,:,:)=Vals
WantedOutput(6,:,:)=Vals

since the 1st, 5th, and 6th elements of ExceedsCutoff are 1. Any ideas on how to do this? Thanks!!

Body:
A simple multiplication with bsxfun() will do this for you:

Vals=[96 92 97;83 90 95];
Vals=permute(Vals,[3,1,2]);
Cutoff = 95;
ExceedsCutoff=Vals >= Cutoff;

WantedOutput = bsxfun(@times,ExceedsCutoff(:),Vals);
% Or, for MATLAB2016b and older
WantedOutput = ExceedsCutoff(:).*Vals;


问:
Should event listeners be inside document.ready function or does it not matter?
When I use:

```<code>$(document).ready(function(){

});
</code>```

Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?

答:
You should put anything in it that needs initialized AFTER the document object model is loaded. Including event listeners.

"Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?"

HTML is interpreted from top to bottom so if your JS file is located in your head and you do not place it inside the .ready event then it will not be able to find your buttons since they haven't been generated yet.

If you put it inside your .ready event though, it is basically telling js to wait until the full dom object has been generated so the btn would then be found and bound.

On the other hand, there are people who strongly believe in including their js files at the very bottom of the page. Since HTML is interpreted from top to bottom then the js file will be loaded after the "meat" of the dom has been generated and you would not need to encapsulate your event binding inside .ready

Body:
When I use:

$(document).ready(function(){

});

Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?


问:
Java object, interface
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class</p>

```<code>import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};
</code>```

答: If they are not needed at top level, you can place Operation, OperandEntry and ObservableState as children of your class CalcModel. If you do need them at top level, you  must put them in a .java file of their own.

Title: Java object, interface

Body:
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};


问:
representing infinity and NAN independent of implementation
Is there an implementation independent way of representing infinity or not a number (NAN) in Common Lisp? It would need to be a double float, and have both positive and negative values. In SBCL, the results of

```<code>(apropos "INFINITY")
</code>```

include

```<code>SB-EXT:DOUBLE-FLOAT-NEGATIVE-INFINITY (bound)
SB-EXT:DOUBLE-FLOAT-POSITIVE-INFINITY (bound)
</code>```

but I need it to be available in all implementations. I have an addendum to a package to write that runs on all platforms and it needs a representation of infinity and NAN. Even functions from another library would suffice.

I got iee-floats loaded and it's a part of my library now. I have a function that detects if a number is NaN and one that detects whether a number is infinity; I haven't tested NaN out but my infinity function needs the number to be a double-float. SBCL's SB-EXT:DOUBLE-FLOAT-POSITIVE-INFINITY works but I would need it to be implementation independent.

答:
The following requires that the float traps be disabled, but...since your are processing such values you need to disable traps anyway. I.e. consider this gem from the standard: "It is implementation-dependent whether floating point traps occur, and whether or how they may be enabled or disabled. Therefore, conforming code may establish handlers for this condition, but must not depend on its being signaled."</p>

```<code>(eval-when (:compile-toplevel :load-toplevel :execute)
  #+sbcl (sb-int:set-floating-point-modes :traps nil)
  #+cmucl (ext:set-floating-point-modes :traps nil)
  #+linux (cffi:foreign-funcall "fedisableexcept" :int -1))

(defconstant +double+inf+ (* 2 most-positive-double-float))
(defconstant +double-inf+ (* 2 most-negative-double-float))
(defconstant +double-nan+ (/ 0d0 0d0))
</code>```

Body:
Is there an implementation independent way of representing infinity or not a number (NAN) in Common Lisp? It would need to be a double float, and have both positive and negative values. In SBCL, the results of

(apropos "INFINITY")

include

SB-EXT:DOUBLE-FLOAT-NEGATIVE-INFINITY (bound)
SB-EXT:DOUBLE-FLOAT-POSITIVE-INFINITY (bound)

but I need it to be available in all implementations. I have an addendum to a package to write that runs on all platforms and it needs a representation of infinity and NAN. Even functions from another library would suffice.

I got iee-floats loaded and it's a part of my library now. I have a function that detects if a number is NaN and one that detects whether a number is infinity; I haven't tested NaN out but my infinity function needs the number to be a double-float. SBCL's SB-EXT:DOUBLE-FLOAT-POSITIVE-INFINITY works but I would need it to be implementation independent.

Body:
The following requires that the float traps be disabled, but...since your are processing such values you need to disable traps anyway. I.e. consider this gem from the standard: "It is implementation-dependent whether floating point traps occur, and whether or how they may be enabled or disabled. Therefore, conforming code may establish handlers for this condition, but must not depend on its being signaled."

(eval-when (:compile-toplevel :load-toplevel :execute)
  #+sbcl (sb-int:set-floating-point-modes :traps nil)
  #+cmucl (ext:set-floating-point-modes :traps nil)
  #+linux (cffi:foreign-funcall "fedisableexcept" :int -1))

(defconstant +double+inf+ (* 2 most-positive-double-float))
(defconstant +double-inf+ (* 2 most-negative-double-float))
(defconstant +double-nan+ (/ 0d0 0d0))


问:
Overwriting the default case class constructor (Scala)
If I have a case class:

```<code>case class NonNegativeInt(i: Int)
</code>```

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

```<code>def apply(n: Int) = new NonNegativeInt(Math.max(0, n))
</code>```

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

答:
There is no straight forward way to override case class constructor as far as I know. However, assuming that real data type won't be simple int, you could do some type which considers invalid state like below:

```<code>sealed abstract class NonNegativeInt { def isValid: Boolean }
final case class ValidNonNegativeInt(i: Int) extends NonNegativeInt { override def isValid: Boolean = true }
final case object InvalidNonNegativeInt extends NonNegativeInt { override def isValid: Boolean = false }
object NonNegativeInt {
  def apply(i: Int): NonNegativeInt = if (i < 0) InvalidNonNegativeInt else ValidNonNegativeInt(i)
}
</code>```

This works pretty simple:

```<code>scala>   NonNegativeInt(0)
res5: NonNegativeInt = ValidNonNegativeInt(0)

scala>   NonNegativeInt(-1)
res6: NonNegativeInt = InvalidNonNegativeInt
</code>```

Then you can even do pattern matching:

```<code>val ni = NonNegativeInt(10)
ni match {
    case ValidNonNegativeInt(i) => println(s"valid $i")
    case InvalidNonNegativeInt => println(s"invalid")
}
</code>```

Then you could further extend your functionality with map/flatMap etc.

Of course it still not protecting you from negative case:

```<code>scala>   ValidNonNegativeInt(-10)
res7: ValidNonNegativeInt = ValidNonNegativeInt(-10)
</code>```

But scala Option for instance also does not override constructor for Some() case allowing invalid value:

```<code>scala> Option(null)
res8: Option[Null] = None

scala> Some(null)
res9: Some[Null] = Some(null)
</code>```

Unless there is no critical use case, for simple Int I would leave it as it is, and ensure its correctness in usages. For more complex structures, above way is quite useful.

Note: I intentionally not used your Max(0, n) way, as in this case it
  will cause more problems than it would solve. Assuming something, and
  swapping data under the hood is bad practice. Imagine you will have a
  bug somewhere in other place of your code which will use your
  implementation with Max(0, n). If input data would be -10, most likely,
  problem was caused by some other problem in incoming data. When you
  change it to default 0, even through input was -10, later when you
  will analyze logs, dumps or debug output, you will miss the fact that it
  was -10.

Other solutions, in my point of view:

@flavian solution is most logical. Explicit functionality/validation

@Cyrille Corpet: very Java'ish

@jwvh solution will take double amount of memory footprint, since it will be two Ints in memory. And also will not protect from overriding:

```<code>scala>   case class NonNegativeInt1(private val x:Int)(implicit val i:Int = Math.max(0,x)) {
     |     override def toString: String = s"NonNegativeInt1($x, $i)"
     |   }
defined class NonNegativeInt1

scala>   NonNegativeInt1(5)
res10: NonNegativeInt1 = NonNegativeInt1(5, 5)

scala>   NonNegativeInt1(-5)
res11: NonNegativeInt1 = NonNegativeInt1(-5, 0)

scala>   NonNegativeInt1(-5)(-5)
res12: NonNegativeInt1 = NonNegativeInt1(-5, -5)
</code>```

Body:
If I have a case class:

case class NonNegativeInt(i: Int)

where the field i to be set to 0 if the parameter is negative. So I cannot just use the default constructor provided by the case class. If I define an apply() method in the companion object (or wherever):

def apply(n: Int) = new NonNegativeInt(Math.max(0, n))

Apparently they have the same signature. Is there a practical way/pattern to process the constraints on the fields?

Body:
There is no straight forward way to override case class constructor as far as I know. However, assuming that real data type won't be simple int, you could do some type which considers invalid state like below:

sealed abstract class NonNegativeInt { def isValid: Boolean }
final case class ValidNonNegativeInt(i: Int) extends NonNegativeInt { override def isValid: Boolean = true }
final case object InvalidNonNegativeInt extends NonNegativeInt { override def isValid: Boolean = false }
object NonNegativeInt {
  def apply(i: Int): NonNegativeInt = if (i < 0) InvalidNonNegativeInt else ValidNonNegativeInt(i)
}

This works pretty simple:

scala>   NonNegativeInt(0)
res5: NonNegativeInt = ValidNonNegativeInt(0)

scala>   NonNegativeInt(-1)
res6: NonNegativeInt = InvalidNonNegativeInt

Then you can even do pattern matching:

val ni = NonNegativeInt(10)
ni match {
    case ValidNonNegativeInt(i) => println(s"valid $i")
    case InvalidNonNegativeInt => println(s"invalid")
}

Then you could further extend your functionality with map/flatMap etc.

Of course it still not protecting you from negative case:

scala>   ValidNonNegativeInt(-10)
res7: ValidNonNegativeInt = ValidNonNegativeInt(-10)

But scala Option for instance also does not override constructor for Some() case allowing invalid value:

scala> Option(null)
res8: Option[Null] = None

scala> Some(null)
res9: Some[Null] = Some(null)

Unless there is no critical use case, for simple Int I would leave it as it is, and ensure its correctness in usages. For more complex structures, above way is quite useful.

Note: I intentionally not used your Max(0, n) way, as in this case it
  will cause more problems than it would solve. Assuming something, and
  swapping data under the hood is bad practice. Imagine you will have a
  bug somewhere in other place of your code which will use your
  implementation with Max(0, n). If input data would be -10, most likely,
  problem was caused by some other problem in incoming data. When you
  change it to default 0, even through input was -10, later when you
  will analyze logs, dumps or debug output, you will miss the fact that it
  was -10.

Other solutions, in my point of view:

@flavian solution is most logical. Explicit functionality/validation

@Cyrille Corpet: very Java'ish

@jwvh solution will take double amount of memory footprint, since it will be two Ints in memory. And also will not protect from overriding:

scala>   case class NonNegativeInt1(private val x:Int)(implicit val i:Int = Math.max(0,x)) {
     |     override def toString: String = s"NonNegativeInt1($x, $i)"
     |   }
defined class NonNegativeInt1

scala>   NonNegativeInt1(5)
res10: NonNegativeInt1 = NonNegativeInt1(5, 5)

scala>   NonNegativeInt1(-5)
res11: NonNegativeInt1 = NonNegativeInt1(-5, 0)

scala>   NonNegativeInt1(-5)(-5)
res12: NonNegativeInt1 = NonNegativeInt1(-5, -5)


问:
How to retrieve report figure between two dates
For implicity, I am going to say we have 5 tables for SQL

1) Client Accounts
2) Leads
3) Calls
4) Report

Below is a SQL example I made up to get an idea how it works. My question is, how can I retrieve records that received a business report from date of the phone calls and 5 days onwards.

Example

Today is 8.06.2017, I made a phone call to a Lead. This lead is ABC. ABC is interested in XYZ. I sent a report to XYZ on 12.06.17. This is within 5 days. So this record should be retrieved and counted as I potentially find more than 100 records within 5 days.

```<code>SELECT Id, Name, DateOfCall
FROM Lead, Call, ClientAccounts
ON Lead.id = Call.id AND Lead.id = ClientAccounts.id
WHERE DATEDIFF (DateOfReport, StartOfCall, getDate()) < 5
</code>```

If I execute this Sql statement, it should retrieve the above report, the name of ClientAccount and the Lead associated with that ClientAccount.

I hope this make sense and I am very beginner in SQL, but I am aware my syntaxes for SQL is wrong but the idea is understanding this and worry about syntax a little later as I do not have SQL server to execute this.

答:
You aren't far off from your goal.

You need to use proper JOIN syntax; what you have is a bit fractured.

```<code>SELECT ... some columns ...
  FROM Lead L
  JOIN Call C  ON L.id = C.id
  JOIN ClientAccounts CA ON L.id = CA.id
</code>```

That assigns the alias names L, C, and CA to your three tables.

You can try running this with SELECT * to see what you get. But using * in a finished query is a rookie mistake.

Next you need to give the names, with table aliases, of the columns you wish to SELECT.  I have to guess which table each column comes from, because you didn't show us your table definitions.  So, I guess...

```<code> SELECT L.id, L.Name, C.DateOfCall
  FROM Lead L
  JOIN Call C  ON L.id = C.id
  JOIN ClientAccounts CA ON L.id = CA.id
</code>```

Run that. See what you get. If my example has the table or column names wrong, fix them. (Please don't ask us to fix them here on SO; we don't know your table layouts.)

Finally you need to select the date range.  Try

```<code>WHERE C.StartOfCall >= CURDATE() - INTERVAL 5 DAY
</code>```

This will get all rows where the call started on or after midnight five days ago.

Body:
For implicity, I am going to say we have 5 tables for SQL

1) Client Accounts
2) Leads
3) Calls
4) Report

Below is a SQL example I made up to get an idea how it works. My question is, how can I retrieve records that received a business report from date of the phone calls and 5 days onwards.

Example

Today is 8.06.2017, I made a phone call to a Lead. This lead is ABC. ABC is interested in XYZ. I sent a report to XYZ on 12.06.17. This is within 5 days. So this record should be retrieved and counted as I potentially find more than 100 records within 5 days.

SELECT Id, Name, DateOfCall
FROM Lead, Call, ClientAccounts
ON Lead.id = Call.id AND Lead.id = ClientAccounts.id
WHERE DATEDIFF (DateOfReport, StartOfCall, getDate()) < 5

If I execute this Sql statement, it should retrieve the above report, the name of ClientAccount and the Lead associated with that ClientAccount.

I hope this make sense and I am very beginner in SQL, but I am aware my syntaxes for SQL is wrong but the idea is understanding this and worry about syntax a little later as I do not have SQL server to execute this.

Body:
You aren't far off from your goal.

You need to use proper JOIN syntax; what you have is a bit fractured.

SELECT ... some columns ...
  FROM Lead L
  JOIN Call C  ON L.id = C.id
  JOIN ClientAccounts CA ON L.id = CA.id

That assigns the alias names L, C, and CA to your three tables.

You can try running this with SELECT * to see what you get. But using * in a finished query is a rookie mistake.

Next you need to give the names, with table aliases, of the columns you wish to SELECT.  I have to guess which table each column comes from, because you didn't show us your table definitions.  So, I guess...

 SELECT L.id, L.Name, C.DateOfCall
  FROM Lead L
  JOIN Call C  ON L.id = C.id
  JOIN ClientAccounts CA ON L.id = CA.id

Run that. See what you get. If my example has the table or column names wrong, fix them. (Please don't ask us to fix them here on SO; we don't know your table layouts.)

Finally you need to select the date range.  Try

WHERE C.StartOfCall >= CURDATE() - INTERVAL 5 DAY

This will get all rows where the call started on or after midnight five days ago.


问:
How to extract indices of non-zero elements from ND array?
I need to label edges of a directed graph with 4 different labels, so I store it in a N*N*4 array. (Let's stick with 4, which is my actual third dimension.) N is the number of nodes in the graph. i.e. for entry M(i,j,1), I would label an edge from node i to node j with the first kind of label. Here is a toy example to play with.

M(2,1,1)=1 indicates I add label text 'first label' on the edge from node 2 to node 1. M(3,2,2)=1 indicates I add label text 'second label' on the edge from node 3 to node 2. Each 'page' in the 3D array is one kind of label.

```<code>M(:,:,1)= 0 0 0      M(:,:,2)= 0 0 1
          1 0 1                0 0 0
          0 0 0                0 1 0
</code>```

But I don't know how to convert  N*N*4 array M into s and t in labeledge(h,s,t,Labels). s is the indices of source nodes while t is the indices of target nodes.

Ideally, this is the plot:

```<code>s = [2 2 1 3];
t = [1 3 3 2];
G = digraph(s,t);
figure;
h = plot(G);
</code>```

the key question is how I can get s1, t1, s2 and t2 from M like this:

```<code>labeledge(h,[2 2], [1 3], 'first label');
labeledge(h,[1 3], [3 2], 'second label');
</code>```

FYI: M(:,:,1) and M(:,:,2) do not have the same non-zero entries.

答:
Some Background Insight:

In your problem, the order of s and t is inter-linked i.e. shuffling of s does not matter if the elements of t are also shuffled in the same order. e.g;  if

```<code>s = [2 2 1 3];
t = [1 3 3 2];
%The combination of s and t given by you
</code>```

The above will give the same result as that of the following:

```<code>s = [2 3 2 1];
t = [1 2 3 3];
% replaced column 2 with column 3, column 3 with column 2, and column 4 with column 3
</code>```

There are many such combinations.
The code I am going to show will give the following combination for the given M:

```<code>s = [2 2 3 1];    %named as snew in my code
t = [1 3 2 3];    %named as tnew in my code
%In this combination, column 3 and 4 are inter-changed (See the combination given by you)
</code>```

Code:

```<code>for k=1:size(M,3)           %Looping depending on the third dimension
    [r,c]= find(M(:,:,k));  %Finding non-zero elements
    %Storing the values in a cell since the number of non-zero elements in each
    %slice of M can be different
    s{k}=r;     t{k}=c;
end
</code>```

The above code gives s{1}=[2; 2], s{2}=[3; 1],  t{1}=[1; 3]  and t{2}=[2; 3].

Now you can find s and t as combined as given in your question by extracting them from the above code with:

```<code>snew=vertcat(s{:});   %Giving a different name to avoid confusion
tnew=vertcat(t{:});
</code>```

Now you can make digraph using snew and tnew and label edges with s{1}, s{2}, t{1} and t{2}.

For labeling the edges, you can use the following loop:

```<code>for k=1:length(s)
    labeledge(h,s{k}, t{k}, ['label ',num2str(k)]);
end
</code>```

This solves the issue of labeling if there are too many labels to make. Making the labels as first, second ,.... would be cumbersome and may be unnecessary.

Output:

With the above modifications, you get the following output:

Body:
I need to label edges of a directed graph with 4 different labels, so I store it in a N*N*4 array. (Let's stick with 4, which is my actual third dimension.) N is the number of nodes in the graph. i.e. for entry M(i,j,1), I would label an edge from node i to node j with the first kind of label. Here is a toy example to play with.

M(2,1,1)=1 indicates I add label text 'first label' on the edge from node 2 to node 1. M(3,2,2)=1 indicates I add label text 'second label' on the edge from node 3 to node 2. Each 'page' in the 3D array is one kind of label.

M(:,:,1)= 0 0 0      M(:,:,2)= 0 0 1
          1 0 1                0 0 0
          0 0 0                0 1 0

But I don't know how to convert  N*N*4 array M into s and t in labeledge(h,s,t,Labels). s is the indices of source nodes while t is the indices of target nodes.

Ideally, this is the plot:

s = [2 2 1 3];
t = [1 3 3 2];
G = digraph(s,t);
figure;
h = plot(G);

the key question is how I can get s1, t1, s2 and t2 from M like this:

labeledge(h,[2 2], [1 3], 'first label');
labeledge(h,[1 3], [3 2], 'second label');

FYI: M(:,:,1) and M(:,:,2) do not have the same non-zero entries.

Body:
Some Background Insight:

In your problem, the order of s and t is inter-linked i.e. shuffling of s does not matter if the elements of t are also shuffled in the same order. e.g;  if

s = [2 2 1 3];
t = [1 3 3 2];
%The combination of s and t given by you

The above will give the same result as that of the following:

s = [2 3 2 1];
t = [1 2 3 3];
% replaced column 2 with column 3, column 3 with column 2, and column 4 with column 3

There are many such combinations.
The code I am going to show will give the following combination for the given M:

s = [2 2 3 1];    %named as snew in my code
t = [1 3 2 3];    %named as tnew in my code
%In this combination, column 3 and 4 are inter-changed (See the combination given by you)

Code:

for k=1:size(M,3)           %Looping depending on the third dimension
    [r,c]= find(M(:,:,k));  %Finding non-zero elements
    %Storing the values in a cell since the number of non-zero elements in each
    %slice of M can be different
    s{k}=r;     t{k}=c;
end

The above code gives s{1}=[2; 2], s{2}=[3; 1],  t{1}=[1; 3]  and t{2}=[2; 3].

Now you can find s and t as combined as given in your question by extracting them from the above code with:

snew=vertcat(s{:});   %Giving a different name to avoid confusion
tnew=vertcat(t{:});

Now you can make digraph using snew and tnew and label edges with s{1}, s{2}, t{1} and t{2}.

For labeling the edges, you can use the following loop:

for k=1:length(s)
    labeledge(h,s{k}, t{k}, ['label ',num2str(k)]);
end

This solves the issue of labeling if there are too many labels to make. Making the labels as first, second ,.... would be cumbersome and may be unnecessary.

Output:

With the above modifications, you get the following output:


问:
Convert a Byte array to Image in c# after modifying the array
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

```<code> public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
</code>```

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

```<code>List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())
</code>```

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

```<code> private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }
</code>```

答:
Based on the question and the comments, I would guess that you are modifying the bytes associated with the image header.  You can not modify these bytes (with an encryption method) and still be able to load the image.

Be sure you are not changing the header bytes.

You can find out about header formats on google/wikipedia.

Body:
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

 public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

 private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }


问:
Spring-boot 2.0.0 M1 - Actuator not working
I have a Spring-boot project that uses spring-boot actuator to provide application statistics and metrics.

The actuator functionality is being provided by adding "spring-boot-starter-actuator" to the project.

At this point, security is disable, so the project does not import spring-security.

Using spring-boot 1.5.x, all actuator Endpoints (automatic provided, as the /info, as well as my specific defined endpoints), are working correctly.

After updating to Spring-boot 2.0.0 M1, the actuator endpoints are no longer exposed. Invoking the /info endpoint returns the following error:

```<code>{"timestamp":1496948526890,"status":404,"error":"Not Found","message":"No
message available","path":"/info"}
</code>```

A note regarding Tomcat: i'm redefining the tomcat.version property, in order to use version 9.

When using spring-boot 1.5.x, tomcat.version=9.0.0.M9

When using spring-boot 2.0.0.M1, tomcat.version=9.0.0.M21

答:
It look's like the endpoint is no longer mapped to /info

2017-06-08 13:11:57.817 [main] INFO  o.s.b.a.e.mvc.EndpointHandlerMapping - Mapped "{[/application/info || /application/info.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()

and according to the 2.0.0/SNAPSHOT documentation this is expected.

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready-endpoints

Try /application/info

Body:
I have a Spring-boot project that uses spring-boot actuator to provide application statistics and metrics.

The actuator functionality is being provided by adding "spring-boot-starter-actuator" to the project.

At this point, security is disable, so the project does not import spring-security.

Using spring-boot 1.5.x, all actuator Endpoints (automatic provided, as the /info, as well as my specific defined endpoints), are working correctly.

After updating to Spring-boot 2.0.0 M1, the actuator endpoints are no longer exposed. Invoking the /info endpoint returns the following error:

{"timestamp":1496948526890,"status":404,"error":"Not Found","message":"No
message available","path":"/info"}

A note regarding Tomcat: i'm redefining the tomcat.version property, in order to use version 9.

When using spring-boot 1.5.x, tomcat.version=9.0.0.M9

When using spring-boot 2.0.0.M1, tomcat.version=9.0.0.M21


问:
How do I fix "remote: fatal error in commit_refs" errors trying to push with Git?
When I try to push to master branch that is hosted on https://github.com I get:

remote: fatal error in commit_refs

How can I solve this?

答: In my case I suspect a hung git process was causing the problem; I killed it and retried and the problem went away.</p>


问:
Cannot print array slice
I'm playing around with Go language, using its online playground.

```<code>package main

import "fmt"

func main() {
    primes := [6]int{2, 3, 5, 7, 11, 13}

    var s []int = primes[1:6]
    fmt.Println(s)
}
</code>```

This code prints nothing. Changing slice range to something else, for instance to [2:6] works as expected. I have tried it only using Go playground. Check it here.

Why it doesn't print anything? Probably it can be a Go compiler or Go playground bug, however I don't know the language so I'm not sure.

答:
A few month later (June 2017), even the original example does work with the current iteration of the golang/playground.

That means the flushing issue after a fmt.Println as a last instruction of main() has been fixed.

Title: Cannot print array slice

Body:
I'm playing around with Go language, using its online playground.

package main

import "fmt"

func main() {
    primes := [6]int{2, 3, 5, 7, 11, 13}

    var s []int = primes[1:6]
    fmt.Println(s)
}

This code prints nothing. Changing slice range to something else, for instance to [2:6] works as expected. I have tried it only using Go playground. Check it here.

Why it doesn't print anything? Probably it can be a Go compiler or Go playground bug, however I don't know the language so I'm not sure.


问:
Qmake does not support build directories below the source directory
I have created an application that compiles and runs like a charm on OS-X.  I would now like to start getting it to work on Windows.  To start, I copied the project to a windows machine and just tried to compile, but got this error:

:: warning: Qmake does not support build directories below the source directory.

Any ideas?

答:
Right Click on a project: Set As Active Project

Click on the Projects button (The one with the spanner image)

Edit build configuration : Debug / Profile / Release / and change the default directories, OR just uncheck the Shadow build check box.

The Build directory path should now change to black, from red


问:
Is it possible to get the current html5 video timeframe with milliseconds?
I am trying to build a live video captioning editor and require that the JS/DOM returns the current video timeframe with milliseconds. According to the DOM, video.currentTime only returns the value in seconds. Is there anyway to get the value in/with milliseconds? </p>

答:
currentTime includes milliseconds.
Open a YouTube video, open your console, then enter
document.getElementsByTagName('video')[0].currentTime;

You'll see the time milliseconds and beyond:
24.530629


问:
Agile testing / traditional testing methods
What are the agile testing methods? And what are the traditional testing methods?</p>

答:
What are the agile testing methods? And what are the traditional testing methods?

There are no "Agile Testing Methods" by itself as such but only testing done in an Agile Environment. Even if they exist, you cannot use "Agile Testing Methods" successfully in a waterfall organisation - so you have your concepts a little wrong there.

Anyway to give you some constructive feedback, the testing functions may very well be the same like waterfall, but the following may be different in an Agile Environment:

atmosphere and culture would be more collaborative (more face to face interaction),

tester involvement would be early,

the Team would code to a test, rather than code first and then create a test plan,

you would be cross functional so you may have to write code or do requirements gathering, and you will work closely with the customer,

you would work in 2 - 4 week iterations,

you would continually improve your testing procedures

you will not have a QA/Testing department

your role will be a "Team member who has most Testing experience" rather than "Tester"

Traditional methods are mostly the exact opposites of the check list above, seriously.


问:
Can anyone explain why a section isn't centering on my page?
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div></code>```

Pen

答:
since you want to center your links horzontally and veritically I suggest to go with the flexbox layout. otherwise vertical alignment would only be possible using display: table-cell; vertical-align: middle; or setting margins for fixed heights.

here is a codepen that illustrates the use of the flexbox layout.
https://codepen.io/anon/pen/KqVwJp

Body:
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}

Pen