问:
how to save a wav file that plays two tracks at the same time? at different volumes
I'm coding in python and using the "wave" library.
I've managed to save new wave files with this library, but not with two sound files overlapping - they will be played one after another when saved.
if anyone could help with how to save a file where two tracks play at the same time at different volumes would be great.
thanks.

答:
You can use the pydub library (a light wrapper I wrote around the python wave module in the std lib) to do it pretty simply:

```<code>from pydub import AudioSegment

sound1 = AudioSegment.from_file("/path/to/my_sound.wav")
sound2 = AudioSegment.from_file("/path/to/another_sound.wav")

combined = sound1.overlay(sound2)

combined.export("/path/to/combined.wav", format='wav')
</code>```

but if you really want to do it using wave:

this is very dependent of the format these are in. Here's an example of how to do it assuming 2 byte wide, little-endian samples:

```<code>import wave

w1 = wave.open("/path/to/wav/1")
w2 = wave.open("/path/to/wav/2")

#get samples formatted as a string.
samples1 = w1.readframes(w1.getnframes())
samples2 = w2.readframes(w2.getnframes())

#takes every 2 bytes and groups them together as 1 sample. ("123456" -> ["12", "34", "56"])
samples1 = [samples1[i:i+2] for i in xrange(0, len(samples1), 2)]
samples2 = [samples2[i:i+2] for i in xrange(0, len(samples2), 2)]

#convert samples from strings to ints
def bin_to_int(bin):
    as_int = 0
    for char in bin[::-1]: #iterate over each char in reverse (because little-endian)
        #get the integer value of char and assign to the lowest byte of as_int, shifting the rest up
        as_int <<= 8
        as_int += ord(char)
    return as_int

samples1 = [bin_to_int(s) for s in samples1] #['\x04\x08'] -> [0x0804]
samples2 = [bin_to_int(s) for s in samples2]

#average the samples:
samples_avg = [(s1+s2)/2 for (s1, s2) in zip(samples1, samples2)]
</code>```

And now all that's left to do is convert samples_avg back to a binary string and write that to a file using wave.writeframes. That's just the inverse of what we just did, so it shouldn't be too hard to figure out. For your int_to_bin function, you'll probably what to make use of the function chr(code), which returns the character with the character code of code (opposite of ord)

Body:
You can use the pydub library (a light wrapper I wrote around the python wave module in the std lib) to do it pretty simply:

from pydub import AudioSegment

sound1 = AudioSegment.from_file("/path/to/my_sound.wav")
sound2 = AudioSegment.from_file("/path/to/another_sound.wav")

combined = sound1.overlay(sound2)

combined.export("/path/to/combined.wav", format='wav')

but if you really want to do it using wave:

this is very dependent of the format these are in. Here's an example of how to do it assuming 2 byte wide, little-endian samples:

import wave

w1 = wave.open("/path/to/wav/1")
w2 = wave.open("/path/to/wav/2")

#get samples formatted as a string.
samples1 = w1.readframes(w1.getnframes())
samples2 = w2.readframes(w2.getnframes())

#takes every 2 bytes and groups them together as 1 sample. ("123456" -> ["12", "34", "56"])
samples1 = [samples1[i:i+2] for i in xrange(0, len(samples1), 2)]
samples2 = [samples2[i:i+2] for i in xrange(0, len(samples2), 2)]

#convert samples from strings to ints
def bin_to_int(bin):
    as_int = 0
    for char in bin[::-1]: #iterate over each char in reverse (because little-endian)
        #get the integer value of char and assign to the lowest byte of as_int, shifting the rest up
        as_int <<= 8
        as_int += ord(char)
    return as_int

samples1 = [bin_to_int(s) for s in samples1] #['\x04\x08'] -> [0x0804]
samples2 = [bin_to_int(s) for s in samples2]

#average the samples:
samples_avg = [(s1+s2)/2 for (s1, s2) in zip(samples1, samples2)]

And now all that's left to do is convert samples_avg back to a binary string and write that to a file using wave.writeframes. That's just the inverse of what we just did, so it shouldn't be too hard to figure out. For your int_to_bin function, you'll probably what to make use of the function chr(code), which returns the character with the character code of code (opposite of ord)


来源: stackexchange

问:
How to check if the name is in a list that is recognized by its similar term in a predicate?
Suppose, I have a prolog predicate such as:

```<code>name(music,[jazz,blues,classical]).
</code>```

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

```<code>ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).
</code>```

But it isn't working.

```<code>?- ismember(jazz,music).
false.
</code>```

And it isn't writing the write(Z) part.

答:
The problem is that the name(Y,Z) that you pass in imember/2 predicate isn't a list. You could simply write:

```<code>ismember(X,Y):-name(Y,Z),imember(X,Z),write(Z).

imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).
</code>```

Example:

```<code>?- ismember(jazz,music).
[jazz,blues,classical]
true.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose, I have a prolog predicate such as:

name(music,[jazz,blues,classical]).

and what I want is to check membership of say jazz and return me true if in music?

So far, I did this:

ismember(X,Y):-imember(X,name(Y,Z)),write(Z).
imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).

But it isn't working.

?- ismember(jazz,music).
false.

And it isn't writing the write(Z) part.

Body:
The problem is that the name(Y,Z) that you pass in imember/2 predicate isn't a list. You could simply write:

ismember(X,Y):-name(Y,Z),imember(X,Z),write(Z).

imember(X,[_|Tail]):-imember(X,Tail).
imember(X,[X|_]).

Example:

?- ismember(jazz,music).
[jazz,blues,classical]
true.


问:
Trim Java String and use in Sql Where Clause
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

```<code>String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}
</code>```

Result Query:

```<code>SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);
</code>```

I want to get rid of the last comma after 'Broken'

答:
try
    String app = "WHERE status in ("+sb.substring(0, sb.length()-2)+")";</p>

Body:
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}

Result Query:

SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);

I want to get rid of the last comma after 'Broken'


问:
How to get the src of a clicked image with prototype
I am struggling to get the image src of a image when its clicked. I just need the jQuery(this).attr("src") but in prototype, this.readAttribute doesn't work. I get: “this.readAttribute is not a function”

```<code>$$('.more-views > ul > li > img').invoke('observe', 'click',  this.updateImage.bind(this));

updateImage: function (){
 //var src = jQuery(this).attr("src").replace("thumbnail/66x66", "image");//changes src from thumbnail to large image
 Needs the above but in prototype.

 //jQuery('#image').attr("src", src);//updates large image
 this.imageEl.writeAttribute("src","http://www.timelapseme.com/images/logonew.png");

 val_scale = !this.showFull ? this.slider.value : 1;
       this.scale(val_scale);

},
</code>```

答:
You're binding an event, so the click-handler should be:</p>

```<code>...
updateImage: function(event)
   {
      var img = Event.findElement(event, 'IMG');
      var src = img.src;
   }
...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am struggling to get the image src of a image when its clicked. I just need the jQuery(this).attr("src") but in prototype, this.readAttribute doesn't work. I get: “this.readAttribute is not a function”

$$('.more-views > ul > li > img').invoke('observe', 'click',  this.updateImage.bind(this));

updateImage: function (){
 //var src = jQuery(this).attr("src").replace("thumbnail/66x66", "image");//changes src from thumbnail to large image
 Needs the above but in prototype.

 //jQuery('#image').attr("src", src);//updates large image
 this.imageEl.writeAttribute("src","http://www.timelapseme.com/images/logonew.png");

 val_scale = !this.showFull ? this.slider.value : 1;
       this.scale(val_scale);

},

Body:
You're binding an event, so the click-handler should be:

...
updateImage: function(event)
   {
      var img = Event.findElement(event, 'IMG');
      var src = img.src;
   }
...


答:
Your problem is with comma in the end, you can append your Strings like this :

```<code>String del = "";
for (int i = 0; i < stat.length; i++) {
    sb.append(del).append("'" + stat[i] + "'");
    del = ",";
}
</code>```

But in fact this is not really good idea to use this way, because it can cause SQL Injection or syntax error, you have to use PreparedStatement for example :

```<code>for (int i = 0; i < stat.length; i++) {
    sb.append(del).append("?");
    del = ",";
}

try (PreparedStatement ps = connection.prepareStatement(sb) {
    for (int i = 0; i < stat.length; i++) {
       ps.setString(i, stat[i]);
    }
    ResultSet result = preparedStatement.executeQuery();//get results
    ...
}
</code>```

Title: Trim Java String and use in Sql Where Clause

Body:
Your problem is with comma in the end, you can append your Strings like this :

String del = "";
for (int i = 0; i < stat.length; i++) {
    sb.append(del).append("'" + stat[i] + "'");
    del = ",";
}

But in fact this is not really good idea to use this way, because it can cause SQL Injection or syntax error, you have to use PreparedStatement for example :

for (int i = 0; i < stat.length; i++) {
    sb.append(del).append("?");
    del = ",";
}

try (PreparedStatement ps = connection.prepareStatement(sb) {
    for (int i = 0; i < stat.length; i++) {
       ps.setString(i, stat[i]);
    }
    ResultSet result = preparedStatement.executeQuery();//get results
    ...
}


问:
adding to a nested xml element
I have the below code and wondering how to get "sold-product" element and add product to it.</p>

```<code>XDocument xmlDoc = new XDocument();
xmlDoc.Add(new XElement("users"));
var xml = xmlDoc.Root;

foreach (var user in users)
{
    xml.Add(new XElement("user", new XAttribute("first-name", user.FirstName?? ""), new XAttribute("last-name", user.LastName?? ""),
    new XElement("sold-products")));

    foreach (var product in user.Products)
    {
        .Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}
</code>```

答:
Try following :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            XDocument xmlDoc = new XDocument();
            XElement users = new XElement("users");
            xmlDoc.Add(users);

            foreach (var user in cUser.users)
            {
               XElement newUser =  new XElement("user",
                   new XAttribute("first-name", user.FirstName?? ""),
                   new XAttribute("last-name", user.LastName?? ""),
                   new XElement("sold-products")
               );
               users.Add(newUser);

               foreach (Product product in user.products)
               {
                  newUser.Add(new XElement("Product",
                     new XElement("name", product.Name),
                     new XElement("price", product.Price)
                  ));
               }
            }
        }
    }
    public class cUser
    {
        public static List<cUser> users { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Product> products { get; set; }
    }
    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
</code>```

Title: adding to a nested xml element

Body:
I have the below code and wondering how to get "sold-product" element and add product to it.

XDocument xmlDoc = new XDocument();
xmlDoc.Add(new XElement("users"));
var xml = xmlDoc.Root;

foreach (var user in users)
{
    xml.Add(new XElement("user", new XAttribute("first-name", user.FirstName?? ""), new XAttribute("last-name", user.LastName?? ""),
    new XElement("sold-products")));

    foreach (var product in user.Products)
    {
        .Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            XDocument xmlDoc = new XDocument();
            XElement users = new XElement("users");
            xmlDoc.Add(users);

            foreach (var user in cUser.users)
            {
               XElement newUser =  new XElement("user",
                   new XAttribute("first-name", user.FirstName?? ""),
                   new XAttribute("last-name", user.LastName?? ""),
                   new XElement("sold-products")
               );
               users.Add(newUser);

               foreach (Product product in user.products)
               {
                  newUser.Add(new XElement("Product",
                     new XElement("name", product.Name),
                     new XElement("price", product.Price)
                  ));
               }
            }
        }
    }
    public class cUser
    {
        public static List<cUser> users { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Product> products { get; set; }
    }
    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}


问:
load part of the html page when filtering results with ajax
I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results

```<code>   <div class="checkbox">
      <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> val1 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id2" class="typePost" value="En groupe"> val2 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id3" class="typePost"  value="A domicile"> val3</label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4</label>
   </div>

  <div id="posts_results">

            {% include 'posts/posts_results.html' %}

   </div>

    <script>
        $('.typePost').change(function (request, response) {

        var v1=$('#id1').is(":checked")? 1:0;
        var V2=$('#id2').is(":checked")? 1:0;
        var V3=$('#id3').is(":checked")? 1:0;
        var v4=$('#id4').is(":checked")? 1:0;
        $.ajax({

            url: '/posts/type_lesson/',
            dataType: 'json',
            type: "GET",
            data: {
                group: groupChecked,
                webcam: webcamChecked,
                home: homeChecked,
                move: moveChecked,
                distance: distance,
            },
            success: function (object_list) {

                $('#posts_results').load("my_page.html", object_list);
                alert('after')
            }

        });

    });
   <script>
</code>```

this is my url:

```<code>url(r'^filter/$', views.filter, name='filter_type_lesson'),
</code>```

and this is my view:

```<code>def filter(request):
if request.method=='GET':

    #as an exemple I'll send all posts
    data= PostFullSerializer(Post.objects.all(), many=True)
    return JsonResponse(data.data, safe=False)
</code>```

The filter function excute some filters according to the json sent data, serialize the filtered posts and send them back (in this case I send all the posts as an example).

The results are displayed using a forloop in the div with id "posts_results" and the html is in the file posts_results.html.

The json data are sent but the ajax success function does not update or load the div

and it is also possible to stay

答:
maybe you could try to render the template in your view and then load the rendered data in your div.

Supposing your posts/posts_results.html is some as:

```<code><ul>
{% for post in posts %}
    <li> Post: {{post.name }} / Author: {{post.author}} / Date: {{post.created_at}}</li>
{% endid %}
<ul>
</code>```

In your view, at the moment when you do respective actions, you can render the template and add the html content to the response, ie (based un your current code):

```<code>def filter(request):
    if request.method=='GET':
        json_data = {
            "success": False,
            "message": "Some message",
            "result": "some result",
        }
        posts = Post.object.all()
        template = "posts/posts_results.html"

        things_to_render_in_your_template = {
            "posts": posts, # you can add other objects that you need to render in your template
        }

        my_html = get_template(template)
        html_content = my_html.render(things_to_render_in_your_template)

        # here the html content rendered is added to your response
        json_data["html_content"] = html_content
        json_data["success"] = True
        return JsonResponse(json_data)
</code>```

Then in your JS, at the momento to check ajsx response, you can add the rendered content into your div

```<code>$.ajax({

        url: '/posts/type_lesson/',
        dataType: 'json',
        type: "GET",
        data: {
            group: groupChecked,
            webcam: webcamChecked,
            home: homeChecked,
            move: moveChecked,
            distance: distance,
        },
        success: function (response) {
            # response is the json returned from the view, each key defined in your json_data dict in the view, is a key here too

            # now insert the rendered content in the div
            $('#posts_results').html(response["html_content"]);
            alert('after');
        }

    });
</code>```

I suggest you instead of create one by one data to your ajax request, use serialize method of jquery or create a FormData object, also instead of GET, use POST to do your request more safe

Body:
I want to filter a search results using 3 checkboxs. The results are presented in the div with the id=posts_results

      <input type="checkbox" id="id1" class="typePost" value="En groupe"> val1

      <input type="checkbox" id="id2" class="typePost" value="En groupe"> val2

      <input type="checkbox" id="id3" class="typePost"  value="A domicile"> val3

      <input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4

            {% include 'posts/posts_results.html' %}

Body:
maybe you could try to render the template in your view and then load the rendered data in your div.

Supposing your posts/posts_results.html is some as:

<ul>
{% for post in posts %}
    <li> Post: {{post.name }} / Author: {{post.author}} / Date: {{post.created_at}}</li>
{% endid %}
<ul>

In your view, at the moment when you do respective actions, you can render the template and add the html content to the response, ie (based un your current code):

def filter(request):
    if request.method=='GET':
        json_data = {
            "success": False,
            "message": "Some message",
            "result": "some result",
        }
        posts = Post.object.all()
        template = "posts/posts_results.html"

        things_to_render_in_your_template = {
            "posts": posts, # you can add other objects that you need to render in your template
        }

        my_html = get_template(template)
        html_content = my_html.render(things_to_render_in_your_template)

        # here the html content rendered is added to your response
        json_data["html_content"] = html_content
        json_data["success"] = True
        return JsonResponse(json_data)

Then in your JS, at the momento to check ajsx response, you can add the rendered content into your div

$.ajax({

        url: '/posts/type_lesson/',
        dataType: 'json',
        type: "GET",
        data: {
            group: groupChecked,
            webcam: webcamChecked,
            home: homeChecked,
            move: moveChecked,
            distance: distance,
        },
        success: function (response) {
            # response is the json returned from the view, each key defined in your json_data dict in the view, is a key here too

            # now insert the rendered content in the div
            $('#posts_results').html(response["html_content"]);
            alert('after');
        }

    });

I suggest you instead of create one by one data to your ajax request, use serialize method of jquery or create a FormData object, also instead of GET, use POST to do your request more safe


问:
VS2010 Upgrade Edition - is 'upgrading' from express ligitimate?
I've read from a non reliable source that purchasing VS2010 Upgrade Edition (As opposed to full retail) is a valid licensing route when 'upgrading' from VS Express (free) - Can anyone confirm or refute this?

Thank you

答: I sell software and didn't want to violate the license agreement.  So, I chatted with a MS rep (and have the chat log), then called the licensing number and was told the same thing from both.  The upgrade license is valid from ANY prior version (including express).  I asked about express specifically and more than once and was told this was just fine.


问:
How does index.php file stop viewing of folder structure in WordPress?
I read that the file placed in wp-contents stops users from viewing the directory structure of WordPress. But the file is empty. How does it work?</p>

```<code><?php
// Silence is golden.
?>
</code>```

答: When you go to a directory, by default, most of the webservers first look for index file, be it php or html or anything else. In this specific case, when you go to that folder, index.php gets executed, even though it doesn't really have any code. It returns an empty page and request to load the folder is 'satisfied', thus preventing any further handling of said request.

Body:
I read that the file placed in wp-contents stops users from viewing the directory structure of WordPress. But the file is empty. How does it work?

<?php
// Silence is golden.
?>


问:
Raise async event in EF's DbContext.SaveChangesAsync()
I'm using EF Core, in an ASP.NET Core environment. My context is registered in my DI container as per-request.

I need to perform extra work before the context's SaveChanges() or SaveChangesAsync(), such as validation, auditing, dispatching notifications, etc. Some of that work is sync, and some is async.

So I want to raise a sync or async event to allow listeners do extra work, block until they are done (!), and then call the DbContext base class to actually save.

```<code>public class MyContext : DbContext
{

  // sync: ------------------------------

  // define sync event handler
  public event EventHandler<EventArgs> SavingChanges;

  // sync save
  public override int SaveChanges(bool acceptAllChangesOnSuccess)
  {
    // raise event for sync handlers to do work BEFORE the save
    var handler = SavingChanges;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // all work done, now save
    return base.SaveChanges(acceptAllChangesOnSuccess);
  }

  // async: ------------------------------

  // define async event handler
  //public event /* ??? */ SavingChangesAsync;

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    // raise event for async handlers to do work BEFORE the save (block until they are done!)
    //await ???
    // all work done, now save
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

}
</code>```

As you can see, it's easy for SaveChanges(), but how do I do it for SaveChangesAsync()?

答:
I'd suggest a modification of this async event handler

```<code>public AsyncEvent SavingChangesAsync;
</code>```

usage

```<code>  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    await SavingChangesAsync?.InvokeAsync(cancellationToken);
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }
</code>```

where

```<code>public class AsyncEvent
{
    private readonly List<Func<CancellationToken, Task>> invocationList;
    private readonly object locker;

    private AsyncEvent()
    {
        invocationList = new List<Func<CancellationToken, Task>>();
        locker = new object();
    }

    public static AsyncEvent operator +(
        AsyncEvent e, Func<CancellationToken, Task> callback)
    {
        if (callback == null) throw new NullReferenceException("callback is null");

        //Note: Thread safety issue- if two threads register to the same event (on the first time, i.e when it is null)
        //they could get a different instance, so whoever was first will be overridden.
        //A solution for that would be to switch to a public constructor and use it, but then we'll 'lose' the similar syntax to c# events
        if (e == null) e = new AsyncEvent();

        lock (e.locker)
        {
            e.invocationList.Add(callback);
        }
        return e;
    }

    public static AsyncEvent operator -(
        AsyncEvent e, Func<CancellationToken, Task> callback)
    {
        if (callback == null) throw new NullReferenceException("callback is null");
        if (e == null) return null;

        lock (e.locker)
        {
            e.invocationList.Remove(callback);
        }
        return e;
    }

    public async Task InvokeAsync(CancellationToken cancellation)
    {
        List<Func<CancellationToken, Task>> tmpInvocationList;
        lock (locker)
        {
            tmpInvocationList = new List<Func<CancellationToken, Task>>(invocationList);
        }

        foreach (var callback in tmpInvocationList)
        {
            //Assuming we want a serial invocation, for a parallel invocation we can use Task.WhenAll instead
            await callback(cancellation);
        }
    }
}
</code>```

Body:
I'm using EF Core, in an ASP.NET Core environment. My context is registered in my DI container as per-request.

I need to perform extra work before the context's SaveChanges() or SaveChangesAsync(), such as validation, auditing, dispatching notifications, etc. Some of that work is sync, and some is async.

So I want to raise a sync or async event to allow listeners do extra work, block until they are done (!), and then call the DbContext base class to actually save.

public class MyContext : DbContext
{

  // sync: ------------------------------

  // define sync event handler
  public event EventHandler<EventArgs> SavingChanges;

  // sync save
  public override int SaveChanges(bool acceptAllChangesOnSuccess)
  {
    // raise event for sync handlers to do work BEFORE the save
    var handler = SavingChanges;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // all work done, now save
    return base.SaveChanges(acceptAllChangesOnSuccess);
  }

  // async: ------------------------------

  // define async event handler
  //public event /* ??? */ SavingChangesAsync;

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    // raise event for async handlers to do work BEFORE the save (block until they are done!)
    //await ???
    // all work done, now save
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

}

As you can see, it's easy for SaveChanges(), but how do I do it for SaveChangesAsync()?

Body:
I'd suggest a modification of this async event handler

public AsyncEvent SavingChangesAsync;

usage

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    await SavingChangesAsync?.InvokeAsync(cancellationToken);
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

where

public class AsyncEvent
{
    private readonly List<Func<CancellationToken, Task>> invocationList;
    private readonly object locker;

    private AsyncEvent()
    {
        invocationList = new List<Func<CancellationToken, Task>>();
        locker = new object();
    }

    public static AsyncEvent operator +(
        AsyncEvent e, Func<CancellationToken, Task> callback)
    {
        if (callback == null) throw new NullReferenceException("callback is null");

        //Note: Thread safety issue- if two threads register to the same event (on the first time, i.e when it is null)
        //they could get a different instance, so whoever was first will be overridden.
        //A solution for that would be to switch to a public constructor and use it, but then we'll 'lose' the similar syntax to c# events
        if (e == null) e = new AsyncEvent();

        lock (e.locker)
        {
            e.invocationList.Add(callback);
        }
        return e;
    }

    public static AsyncEvent operator -(
        AsyncEvent e, Func<CancellationToken, Task> callback)
    {
        if (callback == null) throw new NullReferenceException("callback is null");
        if (e == null) return null;

        lock (e.locker)
        {
            e.invocationList.Remove(callback);
        }
        return e;
    }

    public async Task InvokeAsync(CancellationToken cancellation)
    {
        List<Func<CancellationToken, Task>> tmpInvocationList;
        lock (locker)
        {
            tmpInvocationList = new List<Func<CancellationToken, Task>>(invocationList);
        }

        foreach (var callback in tmpInvocationList)
        {
            //Assuming we want a serial invocation, for a parallel invocation we can use Task.WhenAll instead
            await callback(cancellation);
        }
    }
}


问:
React Native: Exception thrown while executing UI block: put reactNavSuperviewLink back
After I upgraded React Native from 0.14 to 0.26 for my IOS app I am keep getting this exception:

*** Assertion failure in -RCTNavigator reactSuperview, /path_to_app/node_modules/react-native/React/Views/RCTNavigator.m:461
2016-05-20 20:55:43.217 [error][tid:main][RCTUIManager.m:1100] Exception thrown while executing UI block: put reactNavSuperviewLink back

Before the upgrade I did not have this problem. I am using NavigatorIOS.

Any advice on how to fix it or what to even look at while debugging is greatly appreciated

答: After commenting out the line as indicated in the follow up post by @Mark, I ended up getting a different error Cannot adjust current top of stack beyond available views. Reading up on another thread (React-native on IOS: cannot adjust current top of stack beyond available views) it turns out I wasn't properly importing the component that was being used. Although this turned out to be a "user error" on my behalf, perhaps this might explain other accounts of this error.


问:
comparing blank variable using if statement
When i am comparing a blank variable with a string i am getting below error

```<code>[: !=: unary operator expected
</code>```

Below is line in my script

```<code>if [ $monthlystatus = Completed ];then

command x
</code>```

When i try to change this as below

```<code>if [ "$monthlystatus" = Completed ];then

command x
</code>```

It does not give me expected result i.e. if statement give me wrong result.
For example when i am using double quote and even the value of variable monthlystatus is equal to Completed but still command x is not executed.

Below is the real code .

```<code>if [ $monthlystatus != Failed ] && [ $monthlystatus != Aborted ];then

cat /home/a-hkataria/objectstatus_filesystem2.txt /home/a-hkataria/objectstatus_filesystem3.txt > /home/a-hkataria/objectstatus_filesystem4.txt

awk '$2 = $2 FS "Yes"'  /home/a-hkataria/objectstatus_filesystem4.txt

else

cat /home/a-hkataria/objectstatus_filesystem2.txt /home/a-hkataria/objectstatus_filesystem3.txt > /home/a-hkataria/objectstatus_filesystem4.txt

awk '$2 = $2 FS "No"'  /home/a-hkataria/objectstatus_filesystem4.txt

fi
</code>```

So in case variable monthlystatus is blank it is giving me error and when i use the double quote even value of variable is Completed but still it is not displaying yes in second column.

答:
Your second approach is correct. Need quote the variable. Demo:

```<code>while read -r line; do
    [ "$line" = Completed ] && echo "true1 for =$line=" || echo "false1 for =$line="
    [[ "$line" == Completed ]] && echo "true2 for =$line=" || echo "false2 for =$line="
    [[ "$line" =~ ^Completed$ ]] && echo "true3 for =$line=" || echo "false3 for =$line="
    echo
done <<EOF
Completed
completed
Completediano
not Completed
notCompleted

etc
EOF
</code>```

output

```<code>true1 for =Completed=
true2 for =Completed=
true3 for =Completed=

false1 for =completed=
false2 for =completed=
false3 for =completed=

false1 for =Completediano=
false2 for =Completediano=
false3 for =Completediano=

false1 for =not Completed=
false2 for =not Completed=
false3 for =not Completed=

false1 for =notCompleted=
false2 for =notCompleted=
false3 for =notCompleted=

false1 for ==
false2 for ==
false3 for ==

false1 for =etc=
false2 for =etc=
false3 for =etc=
</code>```

Body:
When i am comparing a blank variable with a string i am getting below error

[: !=: unary operator expected

Below is line in my script

if [ $monthlystatus = Completed ];then

command x

When i try to change this as below

if [ "$monthlystatus" = Completed ];then

command x

It does not give me expected result i.e. if statement give me wrong result.
For example when i am using double quote and even the value of variable monthlystatus is equal to Completed but still command x is not executed.

Below is the real code .

if [ $monthlystatus != Failed ] && [ $monthlystatus != Aborted ];then

cat /home/a-hkataria/objectstatus_filesystem2.txt /home/a-hkataria/objectstatus_filesystem3.txt > /home/a-hkataria/objectstatus_filesystem4.txt

awk '$2 = $2 FS "Yes"'  /home/a-hkataria/objectstatus_filesystem4.txt

else

cat /home/a-hkataria/objectstatus_filesystem2.txt /home/a-hkataria/objectstatus_filesystem3.txt > /home/a-hkataria/objectstatus_filesystem4.txt

awk '$2 = $2 FS "No"'  /home/a-hkataria/objectstatus_filesystem4.txt

fi

So in case variable monthlystatus is blank it is giving me error and when i use the double quote even value of variable is Completed but still it is not displaying yes in second column.

Body:
Your second approach is correct. Need quote the variable. Demo:

while read -r line; do
    [ "$line" = Completed ] && echo "true1 for =$line=" || echo "false1 for =$line="
    [[ "$line" == Completed ]] && echo "true2 for =$line=" || echo "false2 for =$line="
    [[ "$line" =~ ^Completed$ ]] && echo "true3 for =$line=" || echo "false3 for =$line="
    echo
done <<EOF
Completed
completed
Completediano
not Completed
notCompleted

etc
EOF

output

true1 for =Completed=
true2 for =Completed=
true3 for =Completed=

false1 for =completed=
false2 for =completed=
false3 for =completed=

false1 for =Completediano=
false2 for =Completediano=
false3 for =Completediano=

false1 for =not Completed=
false2 for =not Completed=
false3 for =not Completed=

false1 for =notCompleted=
false2 for =notCompleted=
false3 for =notCompleted=

false1 for ==
false2 for ==
false3 for ==

false1 for =etc=
false2 for =etc=
false3 for =etc=


问:
li tree menu from array
I have array:

parent 1 is first step!

```<code>Array
(
    [0] => Array
        (
            [categoryID] => 1
            [parent] => 1
            [name] => 111
        )

    [1] => Array
        (
            [categoryID] => 2
            [parent] => 1
            [name] => 2222
        )

    [2] => Array
        (
            [categoryID] => 3
            [parent] => 2
            [name] => 3333
        )
    [3] => Array
        (
            [categoryID] => 4
            [parent] => 3
            [name] => 444
        )

)
</code>```

In result I need tree structure with ul and li elements:

```<code><ul>
 <li>111</li>
 <li>222
  <ul>
   <li>333
   <ul>
    <li>444</li>
   </ul>
   </li>
  </ul>
 </li>
</ul>
</code>```

Thanks!

答:
```<code><?php

$input_array = array(
    array(
        'categoryID' => 1,
        'parent' => 1,
        'name' => 111,
    ),
    array(
        'categoryID' => 2,
        'parent' => 1,
        'name' => 2222,
    ),
    array(
        'categoryID' => 3,
        'parent' => 2,
        'name' => 3333,
    ),
    array(
        'categoryID' => 4,
        'parent' => 3,
        'name' => 444,
    )
);

function buildHtmlList($array)
{
    $maxlevel = 0;

    // just to be sure that the array keys are continuous
    $array = array_values($array);

    foreach ($array as $key => $value)
    {
        $previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
        $nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;

        if ($value['parent'] != $previousparent)
        {
            echo "\n<ul>";
            ++$maxlevel;
        }

        echo "\n<li>" . $value['name'];

        if ($nextparent == $value['parent'])
            echo "</li>";
    }

    for ($i = 0; $i < $maxlevel; ++$i)
    {
        echo "\n</li>\n</ul>";
    }
}

buildHtmlList($input_array);
</code>```

Title: li tree menu from array

Body:
I have array:

parent 1 is first step!

Array
(
    [0] => Array
        (
            [categoryID] => 1
            [parent] => 1
            [name] => 111
        )

    [1] => Array
        (
            [categoryID] => 2
            [parent] => 1
            [name] => 2222
        )

    [2] => Array
        (
            [categoryID] => 3
            [parent] => 2
            [name] => 3333
        )
    [3] => Array
        (
            [categoryID] => 4
            [parent] => 3
            [name] => 444
        )

)

In result I need tree structure with ul and li elements:

111

222

333

444

Thanks!


问:
Infinite loop with redirection, but runs properly with normal input
My code works perfectly when input is directly in the terminal, but creates an infinite loop when used with input redirection (same content). </p>

```<code>int main()
{
    int c,d;
    int x=1;
    while(x)
    {
        c=getchar();
        if((c>='A')&&(c<='J'))
        {
            d=getchar();
            if(d=='\n'||d==EOF)
            {
               if(c=='A')
                    x=0;
            }

        }
        if(x)
        {
            printf("Invalid Input\n");//this keeps repeatingn
        }
    }
    return 0;
}
</code>```

答:
Really your program loops in terminal and with pipe input,the difference is that in terminal getchar blocks waiting for input but at pipe you get EOF.

You should check for EOF after each getchar invocation, so to solve your loop issue you could do,

```<code>int main()
{
    int c,d;
    int x=1;
    while(x)
    {
        c=getchar();

        /* EOF check */
        if (c == EOF)
            break;

        if((c>='A')&&(c<='J'))
        {
            d=getchar();
            if(d=='\n'||d==EOF)
            {
               if(c=='A')
                    x=0;
            }

        }
        if(x)
        {
            printf("Invalid Input\n");//this keeps repeatingn
        }
    }
    return 0;
}
</code>```

OwnerDisplayName: Julie J.

Body:
My code works perfectly when input is directly in the terminal, but creates an infinite loop when used with input redirection (same content).

int main()
{
    int c,d;
    int x=1;
    while(x)
    {
        c=getchar();
        if((c>='A')&&(c<='J'))
        {
            d=getchar();
            if(d=='\n'||d==EOF)
            {
               if(c=='A')
                    x=0;
            }

        }
        if(x)
        {
            printf("Invalid Input\n");//this keeps repeatingn
        }
    }
    return 0;
}

Body:
Really your program loops in terminal and with pipe input,the difference is that in terminal getchar blocks waiting for input but at pipe you get EOF.

You should check for EOF after each getchar invocation, so to solve your loop issue you could do,

int main()
{
    int c,d;
    int x=1;
    while(x)
    {
        c=getchar();

        /* EOF check */
        if (c == EOF)
            break;

        if((c>='A')&&(c<='J'))
        {
            d=getchar();
            if(d=='\n'||d==EOF)
            {
               if(c=='A')
                    x=0;
            }

        }
        if(x)
        {
            printf("Invalid Input\n");//this keeps repeatingn
        }
    }
    return 0;
}

OwnerDisplayName: xae


问:
Validating a Django field dependently on context
I write the code to edit the list of users which belong to a team. For this I create a form, as below:

```<code>class Organization(models.Model):
    name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Organization Name'), max_length=256)

class Team(models.Model):
    organization = models.ForeignKey('Organization')
    name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Team Name'), max_length=256)
    users = models.ManyToManyField('User', related_name='teams')

    def __str__(self):
        return self.name

class TeamUsersForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ['users']

    users = forms.ModelMultipleChoiceField(queryset=User.objects.filter(request.user.organization), required=False)

    def clean_users(self):
        users = self.cleaned_data['users']
        if users.exclude(organization=request.user.organization):
            raise ValidationError(_("Cannot add user from another organization"))
        return users
</code>```

The code above should look into request value to determine the current organization and restrict display and model store only to users from the same organization.

But the above code cannot work, because the value of request is not known at class loading time.

What do you suggest to do?

I thought of two variants:

create a local (to a function) class like the above class TeamUsersForm

dismiss using Django forms for this altogether and use more low-level API

答:
Overide the __init__ of the TeamUsersForm and access request there.

```<code>class TeamUsersForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super().__init__(*args, **kwargs)
        self.fields['users'] = forms.ModelMultipleChoiceField(queryset=User.objects.filter(self.request.user.organization), required=False)
</code>```

This implies that when you instantiate your form, you should it this way:

```<code># somewhere in your views.py, probably

f = TeamUsersForm(request.POST, request=request)
</code>```

Body:
I write the code to edit the list of users which belong to a team. For this I create a form, as below:

class Organization(models.Model):
    name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Organization Name'), max_length=256)

class Team(models.Model):
    organization = models.ForeignKey('Organization')
    name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Team Name'), max_length=256)
    users = models.ManyToManyField('User', related_name='teams')

    def __str__(self):
        return self.name

class TeamUsersForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ['users']

    users = forms.ModelMultipleChoiceField(queryset=User.objects.filter(request.user.organization), required=False)

    def clean_users(self):
        users = self.cleaned_data['users']
        if users.exclude(organization=request.user.organization):
            raise ValidationError(_("Cannot add user from another organization"))
        return users

The code above should look into request value to determine the current organization and restrict display and model store only to users from the same organization.

But the above code cannot work, because the value of request is not known at class loading time.

What do you suggest to do?

I thought of two variants:

create a local (to a function) class like the above class TeamUsersForm

dismiss using Django forms for this altogether and use more low-level API

Body:
Overide the __init__ of the TeamUsersForm and access request there.

class TeamUsersForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super().__init__(*args, **kwargs)
        self.fields['users'] = forms.ModelMultipleChoiceField(queryset=User.objects.filter(self.request.user.organization), required=False)

This implies that when you instantiate your form, you should it this way:

# somewhere in your views.py, probably

f = TeamUsersForm(request.POST, request=request)


答:
You can join a string array with commas using Java 8 streams:

```<code>String joined = Arrays.asList(stat).stream()
    .map(s -> "'" + s + "'")
    .collect(Collectors.joining(", "));
</code>```

But note that joining strings like this is a really bad idea: you are vulnerable to SQL injection attacks, e.g. if one of the element of stat is something like:

```<code>'); DROP TABLES Table; --
</code>```

You are better off building the query using a PreparedStatement. See this question.

Body:
I am trying to get values from MySQL db using a query which gets values from a multiple select. The problem is that I am using StringBuilder to create the query based on the values I am getting. If you see the Where clause used why me, every time a new variable is fetched a comma is added in the end.

How do I remove the last comma added as it is giving me an error in the sql query. Will appreciate any help.

String[] stat = req.getParameterValues("status");
StringBuilder sb = new StringBuilder(200);

if (stat != null) {

    for (int i = 0; i < stat.length; i++) {

        sb.append("'" + stat[i] + "',");

    }

    String app = "WHERE status in (" + sb.toString() + ")";
    String sqlquery = "SELECT * FROM Table " + app + ";";
}

Result Query:

SELECT * FROM Table
   WHERE status in ('Deployed','PendingDisposal','Available','Reserved','Broken',);

I want to get rid of the last comma after 'Broken'

Body:
You can join a string array with commas using Java 8 streams:

String joined = Arrays.asList(stat).stream()
    .map(s -> "'" + s + "'")
    .collect(Collectors.joining(", "));

But note that joining strings like this is a really bad idea: you are vulnerable to SQL injection attacks, e.g. if one of the element of stat is something like:

'); DROP TABLES Table; --

You are better off building the query using a PreparedStatement. See this question.


问:
Instance of Show list for a custom datatype
I have defined a (Matrix) datatype, as a 2D list:

```<code>newtype Matrix a = M [[a]]
</code>```

and an instance for Show, as follows:

```<code>instance Show a => Show (Matrix a) where
    show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
</code>```

Which behaves like so:

```<code>> mat = M [[3,1,8],[6,3,0],[6,8,8]]
> mat
3 1 8
6 3 0
6 8 8
</code>```

However, I'd like to handle how it prints lists, because the default behaviour looks a bit weird. How do I specify this? I've tried something like these:

```<code>instance Show a => Show ([Matrix a]) where
    show mat = case mat of
      [M a] -> intercalate "\n" (map (unwords . map show) a) ++ "\n"
      (m:ms) -> show m ++ "\n" ++ show ms

  instance Show a => Show (Matrix a) where
    show (M a)  = intercalate "\n" (map (unwords . map show) a) ++ "\n"
    show (m:ms) = show m ++ "\n" ++ show ms
</code>```

But I just get syntax errors. I tried googling the issue, but I couldn't find anything (Perhaps I used the wrong keywords?)

Thanks in advance.

EDIT:

Desired input and output:

```<code>mat1 = M [[1,2],[3,4]]
mat2 = M [[1,2],[3,4]]
> [mat1, mat2]
1 2
3 4,
1 2
3 4
</code>```

答:
This is exactly what the showList method is for:

```<code>instance Show a => Show (Matrix a) where
    show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
    showList (m:ms) = shows m . ("\n" ++) . showList ms
</code>```

Note that this doesn't handle empty lists, though, so you also need

```<code>    showList [] = id
</code>```

(or whatever you want it to show for empty lists.)

Body:
I have defined a (Matrix) datatype, as a 2D list:

newtype Matrix a = M [[a]]

and an instance for Show, as follows:

instance Show a => Show (Matrix a) where
    show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"

Which behaves like so:

> mat = M [[3,1,8],[6,3,0],[6,8,8]]
> mat
3 1 8
6 3 0
6 8 8

However, I'd like to handle how it prints lists, because the default behaviour looks a bit weird. How do I specify this? I've tried something like these:

instance Show a => Show ([Matrix a]) where
    show mat = case mat of
      [M a] -> intercalate "\n" (map (unwords . map show) a) ++ "\n"
      (m:ms) -> show m ++ "\n" ++ show ms

  instance Show a => Show (Matrix a) where
    show (M a)  = intercalate "\n" (map (unwords . map show) a) ++ "\n"
    show (m:ms) = show m ++ "\n" ++ show ms

But I just get syntax errors. I tried googling the issue, but I couldn't find anything (Perhaps I used the wrong keywords?)

Thanks in advance.

EDIT:

Desired input and output:

mat1 = M [[1,2],[3,4]]
mat2 = M [[1,2],[3,4]]
> [mat1, mat2]
1 2
3 4,
1 2
3 4

Body:
This is exactly what the showList method is for:

instance Show a => Show (Matrix a) where
    show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
    showList (m:ms) = shows m . ("\n" ++) . showList ms

Note that this doesn't handle empty lists, though, so you also need

    showList [] = id

(or whatever you want it to show for empty lists.)


问:
Infinite recursion in function
In such a snippet:

```<code>struct A;
struct B {
    B(int k): k_(k) { }
    int k_;
    operator A() const;
 };

 struct A {
     B k_;
 };

 B::operator A() const
 {
    return A(B(this->k_));
 }
</code>```

clang produces a warning (in the conversion operator):

```<code> warning: all paths through this function will call itself [-Winfinite-recursion]
</code>```

And  consequently when I do:

```<code>int main()
{
     A a = B(1);
}
</code>```

the program fails with segmentation fault.

Can anybody, please, explain why there is infinite recurcsion.

答:
```<code>A a = B(1);
</code>```

Lets first construct a B object with B(1) through the constructor that takes int k.

Now, let's use the user-defined conversion operator to cast this B into an A to make it fit a. This returns A(B(this->k_));.

Let's construct an A object using a newly-constructed B object that uses the same k_. The only fitting constructor is the copy constructor/move constructor that wants a const A&/A&&. We can use the user-defined conversion operator to cast the newly-constructed B object to an A, let's do that.

This will construct A(B(this->k_)); again.

There's your infinite recursion.

Title: Infinite recursion in function

Body:
In such a snippet:

struct A;
struct B {
    B(int k): k_(k) { }
    int k_;
    operator A() const;
 };

 struct A {
     B k_;
 };

 B::operator A() const
 {
    return A(B(this->k_));
 }

clang produces a warning (in the conversion operator):

 warning: all paths through this function will call itself [-Winfinite-recursion]

And  consequently when I do:

int main()
{
     A a = B(1);
}

the program fails with segmentation fault.

Can anybody, please, explain why there is infinite recurcsion.

Body:
A a = B(1);

Lets first construct a B object with B(1) through the constructor that takes int k.

Now, let's use the user-defined conversion operator to cast this B into an A to make it fit a. This returns A(B(this->k_));.

Let's construct an A object using a newly-constructed B object that uses the same k_. The only fitting constructor is the copy constructor/move constructor that wants a const A&/A&&. We can use the user-defined conversion operator to cast the newly-constructed B object to an A, let's do that.

This will construct A(B(this->k_)); again.

There's your infinite recursion.


问:
Outlook 2010 - VBA MsgBox if more then 10 unread elements mails
I would like to start Outlook, then Outlook should only show ALL mailboxes, which have also unread emails.

At the moment, my VBA-Script expand all my mailbox folders / accounts.
But the list is unfortunately too long, now.

I am looking for a way to check unread elements.
I have tried it with a simple MsgBox, but does not work.

```<code>    Private Sub Application_Startup()
    'Folder-Variable definieren
    Dim objFolderIMAP01 As Outlook.Folder
    Dim objFolderIMAP02 As Outlook.Folder
    Dim objFolderIMAP03 As Outlook.Folder

    'IMAP-Folder zuweisen (hier in Klammern mit Anführungszeichen den Namen der IMAP-Datendatei eintragen)
    Set objFolderIMAP01 = Outlook.Session.Folders("MailBox1")
    Set objFolderIMAP02 = Outlook.Session.Folders("MailBox2")
    Set objFolderIMAP03 = Outlook.Session.Folders("MailBox3")

    'Alle Unterordner selektieren (und damit aufklappen)
    Call selectAllFolderRec(objFolderIMAP01)
    Call selectAllFolderRec(objFolderIMAP02)
    Call selectAllFolderRec(objFolderIMAP03)

    'Posteingang als Startordnder auswählen
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP01.Folders("Posteingang"))
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP02.Folders("Posteingang"))
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP03.Folders("Posteingang"))

    'Info wenn mehr als 10 Emails ungelesen
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 1 ist voll!"
    End If
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 2 ist voll!"
    End If
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 3 ist voll!"
    End If
End Sub

Sub selectAllFolderRec(objFolder As Outlook.Folder)
    Dim lngCounter As Long
    Dim bolSkipSelect As Boolean
    bolSkipSelect = False
    For lngCounter = 1 To objFolder.Folders.Count
        If objFolder.Folders(lngCounter).Folders.Count > 0 And objFolder.Folders(lngCounter).Folders.UnReadItemCount > 10 Then
            Call selectAllFolderRec(objFolder.Folders(lngCounter))
          Else
            If bolSkipSelect = False Then
                Call Outlook.ActiveExplorer.SelectFolder(objFolder.Folders(lngCounter))
                bolSkipSelect = True
            End If
        End If
    Next lngCounter
End Sub
</code>```

答:
The folder called "MailBox1" will not have mail.

If you want to check for unread mail in the inbox of Mailbox1 you have to specify objFolderIMAP01.Folders("Posteingang").

```<code>'Info wenn mehr als 10 Emails ungelesen
'Info if more than 10 mails unread
If objFolderIMAP01.Folders("Posteingang").UnReadItemCount > 10 Then
    MsgBox "Inbox of Mailbox 1 is full! - Posteingang von Mailbox 1 ist voll!"
End If
</code>```

Body:
I would like to start Outlook, then Outlook should only show ALL mailboxes, which have also unread emails.

At the moment, my VBA-Script expand all my mailbox folders / accounts.
But the list is unfortunately too long, now.

I am looking for a way to check unread elements.
I have tried it with a simple MsgBox, but does not work.

    Private Sub Application_Startup()
    'Folder-Variable definieren
    Dim objFolderIMAP01 As Outlook.Folder
    Dim objFolderIMAP02 As Outlook.Folder
    Dim objFolderIMAP03 As Outlook.Folder

    'IMAP-Folder zuweisen (hier in Klammern mit Anführungszeichen den Namen der IMAP-Datendatei eintragen)
    Set objFolderIMAP01 = Outlook.Session.Folders("MailBox1")
    Set objFolderIMAP02 = Outlook.Session.Folders("MailBox2")
    Set objFolderIMAP03 = Outlook.Session.Folders("MailBox3")

    'Alle Unterordner selektieren (und damit aufklappen)
    Call selectAllFolderRec(objFolderIMAP01)
    Call selectAllFolderRec(objFolderIMAP02)
    Call selectAllFolderRec(objFolderIMAP03)

    'Posteingang als Startordnder auswählen
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP01.Folders("Posteingang"))
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP02.Folders("Posteingang"))
    Call Outlook.ActiveExplorer.SelectFolder(objFolderIMAP03.Folders("Posteingang"))

    'Info wenn mehr als 10 Emails ungelesen
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 1 ist voll!"
    End If
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 2 ist voll!"
    End If
    If objFolderIMAP01.UnReadItemCount > 10 Then
        MsgBox "Mailbox 3 ist voll!"
    End If
End Sub

Sub selectAllFolderRec(objFolder As Outlook.Folder)
    Dim lngCounter As Long
    Dim bolSkipSelect As Boolean
    bolSkipSelect = False
    For lngCounter = 1 To objFolder.Folders.Count
        If objFolder.Folders(lngCounter).Folders.Count > 0 And objFolder.Folders(lngCounter).Folders.UnReadItemCount > 10 Then
            Call selectAllFolderRec(objFolder.Folders(lngCounter))
          Else
            If bolSkipSelect = False Then
                Call Outlook.ActiveExplorer.SelectFolder(objFolder.Folders(lngCounter))
                bolSkipSelect = True
            End If
        End If
    Next lngCounter
End Sub

Body:
The folder called "MailBox1" will not have mail.

If you want to check for unread mail in the inbox of Mailbox1 you have to specify objFolderIMAP01.Folders("Posteingang").

'Info wenn mehr als 10 Emails ungelesen
'Info if more than 10 mails unread
If objFolderIMAP01.Folders("Posteingang").UnReadItemCount > 10 Then
    MsgBox "Inbox of Mailbox 1 is full! - Posteingang von Mailbox 1 ist voll!"
End If


问:
How can I build a Android app with local MySQL database?
I would like to build a local database android app with MySQL. Can I do that? Does the user need MySQL server installed in their phone to run the app? Is there any special stuff to do? Thanks.</p>

答:
You need to have the database installed on a server and the user access the database using some API.

You do this only if you need the database to be on your server if the data stored concerns the user only then just have Sqlite database on the user's device.
Again,You should not connect to the Server-database directly from your application.


问:
Changing only one value of a key in a dictionary that has multiple values
I have a key with multiple values assigned. I would like to ask the user for input (new_population), and replace the old value (current_population) within the key. I would like the other value within the key (num) to remain unaffected.

```<code>current_population = 5
num = 3
dict = {}
dict["key"] = [current_population, num]

new_population = input("What is the new population?")
</code>```

Say (for example sake), the value of new_population is 10. My goal is a final output of:

```<code>{'key': [10, 3]}
</code>```

How would I go about doing this?

答:
To be clear, what you actually have is a dictionary where each element is a list. It is not possible to have multiple elements with the same key, since that would create undefined behaviour (which element would be returned by a lookup?). If you do

```<code>current_population = 5
num = 3
mydict = {}
mydict["key"] = [current_population, num]
elem = mydict["key"]
print elem
</code>```

you will see that elem is actually the list [5,3]. So to get or set either value, you need to index into the list you get from indexing into the dictionary.

```<code>mydict["key"][0] = new_population
</code>```

(like in the accepted answer).

If you don't want to keep track of which index is population and which is num, you could make a dictionary of dictionaries instead:

```<code>mydict = {}
mydict["key"] = {"pop": current_population, "num", num}
mydict["key"]["pop"] = new_population
</code>```

Body:
I have a key with multiple values assigned. I would like to ask the user for input (new_population), and replace the old value (current_population) within the key. I would like the other value within the key (num) to remain unaffected.

current_population = 5
num = 3
dict = {}
dict["key"] = [current_population, num]

new_population = input("What is the new population?")

Say (for example sake), the value of new_population is 10. My goal is a final output of:

{'key': [10, 3]}

How would I go about doing this?

Body:
To be clear, what you actually have is a dictionary where each element is a list. It is not possible to have multiple elements with the same key, since that would create undefined behaviour (which element would be returned by a lookup?). If you do

current_population = 5
num = 3
mydict = {}
mydict["key"] = [current_population, num]
elem = mydict["key"]
print elem

you will see that elem is actually the list [5,3]. So to get or set either value, you need to index into the list you get from indexing into the dictionary.

mydict["key"][0] = new_population

(like in the accepted answer).

If you don't want to keep track of which index is population and which is num, you could make a dictionary of dictionaries instead:

mydict = {}
mydict["key"] = {"pop": current_population, "num", num}
mydict["key"]["pop"] = new_population


问:
How do I "Hide()" a Modal WPF Window without it closing?
I have a WPF window that is run on a background thread as a sort of "notifier window"... when an event is raised, it displays a message... a user clicks the "Snooze" button and I call this.Visibility = Visibility.Collapsed

The very moment that I hide the window (either by calling this.Hide() or setting the Visibility as mentioned above)... the "ShowDialog()" code releases the window and closes it.

This is absolutely a bug in the WPF code (which I've identified via reflector)... but my question remains. Has anyone been able to come up with a work-around for this issue?

I've tried many things and am now reaching out to ya'll smart people :)

答:
OK, and as quickly as that - my boss (old C++ goofy guy that he is) figured out the answer.

Here was the code inside of my background thread (which is set to STA mode):

```<code>// Show dialog - keeps the thread open and shows the window! Yay!!!
new BeamUI.Notifier.NotifierWindow().ShowDialog();
</code>```

And here is the modification, that strangely enough works perfectly :)

```<code>// Show... hmm, that shows the window... but how do I keep this thread open?
new BeamUI.Notifier.NotifierWindow().Show();

// ZOMG - a line of code that JUST keeps the thread (and msgpump) going!!!
System.Windows.Threading.Dispatcher.Run();
</code>```

And that's it.

This kinda thing makes me hate C++ people though, and makes me want to just say "if you just built it right in the first place I wouldn't have to look for a work-around!" (j/k)

Body:
OK, and as quickly as that - my boss (old C++ goofy guy that he is) figured out the answer.

Here was the code inside of my background thread (which is set to STA mode):

// Show dialog - keeps the thread open and shows the window! Yay!!!
new BeamUI.Notifier.NotifierWindow().ShowDialog();

And here is the modification, that strangely enough works perfectly :)

// Show... hmm, that shows the window... but how do I keep this thread open?
new BeamUI.Notifier.NotifierWindow().Show();

// ZOMG - a line of code that JUST keeps the thread (and msgpump) going!!!
System.Windows.Threading.Dispatcher.Run();

And that's it.

This kinda thing makes me hate C++ people though, and makes me want to just say "if you just built it right in the first place I wouldn't have to look for a work-around!" (j/k)


问:
finding roots of inequation in python
I'm just getting into python so I do not really know lots of libraries of linear programming.

What I want to do is:

Setting up a polyhedron  Ax<=b  and finding all the solutions it has (feasible solutions & basic feasible solutions).

where A is a MxN Matrix (M rows & N columns) and b is the vector of minimal values of each restriction.

I tried getting into scipy optimizer and numpy but I have not been able to find what I want.

Thanks!

答: Maybe you can use sympy library which has the inequality solver, that seems to be doing what you're asking.</p>

Title: finding roots of inequation in python


问:
Angular $location.path is not working
i am using angular with web api problem is when i use
 $location.url("/home");
home page did not display when i checked user url (in chrome development toll)
http://errors.angularjs.org/1.6.3/$compile/tpload?p0=template%2Fhome.html&p1=undefined&p2=undefined

in url template%2Fhome.html where as my path template/home so what is %2F

kindly help me
regards,
Akmal.

答: Do you have the $routeParams service injected in your js file along with $location?

Title: Angular $location.path is not working


问:
JavaFX VBox.getHeight() returns wrong value
I'm making a program that converts a .xml file, containing information regarding a UML diagram, to an actual UML diagram. To draw arrows, I need to get the height of the VBoxes I'm using (they are children of an AnchorPane). I did the following thing:

```<code>pane.applyCss();
pane.layout();
VBox.getHeight();
</code>```

But the getHeight() value returns the wrong value. It should be something around 40 but I get 32.

How could I fix this?

答:
It might help to get this value relative to its parent pane:</p>

```<code>double requestedHeight = yourVBox.getBoundsInParent().getHeight();
</code>```

Body:
I'm making a program that converts a .xml file, containing information regarding a UML diagram, to an actual UML diagram. To draw arrows, I need to get the height of the VBoxes I'm using (they are children of an AnchorPane). I did the following thing:

pane.applyCss();
pane.layout();
VBox.getHeight();

But the getHeight() value returns the wrong value. It should be something around 40 but I get 32.

How could I fix this?

Body:
It might help to get this value relative to its parent pane:

double requestedHeight = yourVBox.getBoundsInParent().getHeight();


问:
Input validation to only accept numbers
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

```<code>#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}
</code>```

Here's the error im receiving

答:
do{
...
}while(0);

means your loop is done exactly once. It will exit always. So you can spare this do-while loop.

The code after while(0); looks like a function which is supposed to test the user input.

I would introduce strings and exceptions and write it like this:

```<code>#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

//Work-Class
class Triangle {
private:
    double base;
    double height;

public:
    void setBase(double);
    void setHeight(double);
    double getBase() const;
    double getHeight() const;
    double getArea() const;
};

void Triangle::setBase(double b) {
    base = b;
}

void Triangle::setHeight(double hg) {
    height = hg;
}

double Triangle::getBase()const {
    return base;
}

double Triangle::getHeight() const {
    return height;
}

double Triangle::getArea() const {
    return (base*height) / 2;
}

//conversion and test function
double getDoubleString(string questString) {
    string userAnswer;
    double d;

    cout << questString;
    getline(cin, userAnswer);
    try {
        d = stod(userAnswer);
    }
    catch (const std::invalid_argument& ia) {
        cerr << "Invalid argument: " << ia.what() << '\n';
        d = 0.0;
    }
    return d;
}

//Enter the hell
int main() {
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    cout << "--------------------------------------------------------------\n\n";
    //Triangle one
    one.setBase(getDoubleString("What is the base of Triangle One: "));
    cout << "You have entered " << one.getBase() << " for the base of the triangle.\n";
    one.setHeight(getDoubleString("What is the height of Triangle One: "));
    cout << "You have entered " << one.getHeight() << " for the height of the triangle.\n\n";

    //Triangle two
    two.setBase(getDoubleString("What is the base of Triangle Two: "));
    cout << "You have entered " << two.getBase() << " for the base of the triangle.\n";
    two.setHeight(getDoubleString("What is the height of Triangle Two: "));
    cout << "You have entered " << two.getHeight() << " for the height of the triangle.\n\n";

    //Triangle three
    three.setBase(getDoubleString("What is the base of Triangle Three: "));
    cout << "You have entered " << three.getBase() << " for the base of the triangle.\n";
    three.setHeight(getDoubleString("What is the height of Triangle Three: "));
    cout << "You have entered " << three.getHeight() << " for the height of the triangle.\n\n";

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "--------------------------------------------------------------\n\n";
    cout << "The total area of the three triangles ist " << totalArea << endl;
    return 0;
}
</code>```

Title: Input validation to only accept numbers

Body:
I'm creating  program and it should only be allowed to accept numbers if a letter is entered it should re-ask the use to enter a number. When i run the code i get an error saying there's a problem with the break heres a copy of my code

#include <iostream>
using namespace std;

class Triangle
{
    private:
        double base;
        double height;
    public:
        void setBase(double);
        void setHeight(double);
        double getBase() const;
        double getHeight() const;
        double getArea() const;
};

void Triangle::setBase(double b)
{
    base = b;
}

void Triangle::setHeight(double hg)
{
    height = hg;
}

double Triangle::getBase() const
{
    return base;
}

ouble Triangle::getHeight() const
{
    return height;
}

double Triangle::getArea() const
{
    return .50 *(base * height);
}

int main()
{
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    do
    {
        cout << "What is the base of Triangle One:";
        cin >> number;

        one.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle One:";
        cin >> number;
        one.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Two: ";
        cin >> number;
        two.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Two:";
        cin >> number;
        two.setHeight(number);
            cout << "You have entered " << number << " for the height of the triangle.\n";

            cout << "What is the base of Triangle Three:";
        cin >> number;
        three.setBase(number);
            cout << "You have entered " << number << " for the base of the triangle.\n";

        cout << "What is the height of Triangle Three:";
        cin >> number;
        three.setHeight(number);
             cout << "You have entered " << number << " for the height of the triangle.\n";
    }
    while (0);
    {
        if (cin >> number)
        {
            break;
        }
        else
        {
            cout << "Invalid Input! Please input a numerical value." << endl;
                    cin.clear();
            while (cin.get() != '\n') ;
        }
    }

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "The total area of the three triangles is " << totalArea << endl;

    return 0;

}

Here's the error im receiving

Body:
do{
...
}while(0);

means your loop is done exactly once. It will exit always. So you can spare this do-while loop.

The code after while(0); looks like a function which is supposed to test the user input.

I would introduce strings and exceptions and write it like this:

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

//Work-Class
class Triangle {
private:
    double base;
    double height;

public:
    void setBase(double);
    void setHeight(double);
    double getBase() const;
    double getHeight() const;
    double getArea() const;
};

void Triangle::setBase(double b) {
    base = b;
}

void Triangle::setHeight(double hg) {
    height = hg;
}

double Triangle::getBase()const {
    return base;
}

double Triangle::getHeight() const {
    return height;
}

double Triangle::getArea() const {
    return (base*height) / 2;
}

//conversion and test function
double getDoubleString(string questString) {
    string userAnswer;
    double d;

    cout << questString;
    getline(cin, userAnswer);
    try {
        d = stod(userAnswer);
    }
    catch (const std::invalid_argument& ia) {
        cerr << "Invalid argument: " << ia.what() << '\n';
        d = 0.0;
    }
    return d;
}

//Enter the hell
int main() {
    double number;
    double totalArea;
    Triangle one;
    Triangle two;
    Triangle three;

    cout << "--------------------------------------------------------------\n\n";
    //Triangle one
    one.setBase(getDoubleString("What is the base of Triangle One: "));
    cout << "You have entered " << one.getBase() << " for the base of the triangle.\n";
    one.setHeight(getDoubleString("What is the height of Triangle One: "));
    cout << "You have entered " << one.getHeight() << " for the height of the triangle.\n\n";

    //Triangle two
    two.setBase(getDoubleString("What is the base of Triangle Two: "));
    cout << "You have entered " << two.getBase() << " for the base of the triangle.\n";
    two.setHeight(getDoubleString("What is the height of Triangle Two: "));
    cout << "You have entered " << two.getHeight() << " for the height of the triangle.\n\n";

    //Triangle three
    three.setBase(getDoubleString("What is the base of Triangle Three: "));
    cout << "You have entered " << three.getBase() << " for the base of the triangle.\n";
    three.setHeight(getDoubleString("What is the height of Triangle Three: "));
    cout << "You have entered " << three.getHeight() << " for the height of the triangle.\n\n";

    totalArea = one.getArea() + two.getArea() + three.getArea();

    cout << "--------------------------------------------------------------\n\n";
    cout << "The total area of the three triangles ist " << totalArea << endl;
    return 0;
}


问:
Sorting an array of names in assembly
I have to write a procedure in assembly that sort an array of upto 20 Names,
max 11 characters. My programs accepts 3 records but keeps crashing at
everything else and I can't get it to sort. I'm using bubble sort.

BTW, I can't change anything in C++ since this is an assignment.

These first 3 lines are from the C++ code.

```<code>extern "C" void Sort (char [] [11], char [], double [], long);

char Names [20] [11];

Sort (Names, LetterGrades, Averages, NumStudents - 1);

_Sort proc

      mov ecx, [esp +16]
      dec ecx

L1:   push ecx
    mov esi, [esp + 4]

L2:   mov eax, [esi]
      cmp [esi + 11], eax
    jg L3
      xchg eax,[esi + 11]
      mov [esi],eax

L3:   add esi,11
      loop L2

      pop ecx
      loop L1

L4: ret

_Sort endp
</code>```

答:
I think that you should compare every character (A) of every name against the corresponding character (B) of all the other names, then, eventually, swap the two names if B and all characters preceding it are smaller than A and characters before. Right now that's my only idea but I can't translate it in code, I should think about it still some time...

I tried to explain it as best as I could, anyway I'm sorry if it's a mess.. =)

Title: Sorting an array of names in assembly

Body:
I have to write a procedure in assembly that sort an array of upto 20 Names,
max 11 characters. My programs accepts 3 records but keeps crashing at
everything else and I can't get it to sort. I'm using bubble sort.

BTW, I can't change anything in C++ since this is an assignment.

These first 3 lines are from the C++ code.

extern "C" void Sort (char [] [11], char [], double [], long);

char Names [20] [11];

Sort (Names, LetterGrades, Averages, NumStudents - 1);

_Sort proc

      mov ecx, [esp +16]
      dec ecx

L1:   push ecx
    mov esi, [esp + 4]

L2:   mov eax, [esi]
      cmp [esi + 11], eax
    jg L3
      xchg eax,[esi + 11]
      mov [esi],eax

L3:   add esi,11
      loop L2

      pop ecx
      loop L1

L4: ret

_Sort endp


问:
Response object is not defined when passed in a function
I am using Facebook Graph NodeJS API to fetch user_posts. The response has pagination and therefore I need to loop over the response to fetch all the posts. I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses function:

```<code>var posts = "";

function get_user_statuses(response_posts, res) {

    var link_regex = /https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}/g;
    var isNextPageAvailable = true;

    if ("paging" in response_posts) {
        var nextPage = response_posts.paging.next;
        isNextPageAvailable = true;

    } else {
        isNextPageAvailable = false;
    }

    for (var i = 0; i < response_posts.data.length; i++) {

        var post = response_posts.data[i].message + " ";

        if ("message" in response_posts.data[i]) {
            posts += post.replace(link_regex, "");
        }
    }

    if (nextPage !== undefined) {
        request(nextPage, function (error, response, body) {

            if (!error && response.statusCode === 200) {
                get_user_statuses(JSON.parse(body));

            } else {
                console.log(error);
            }
        });
    }

    if (!isNextPageAvailable){
        //Sending posts to facebook Modal
        console.log(posts);
        res.send(JSON.stringify({posts: posts}));    //res is not defined here
    }
}

router.post('/fbData', function (req, response, next) {

    FB.setAccessToken(req.body.access_token);
    FB.api('/me?fields=posts&posts.limit=1000', function (res) {

        if (!res || res.error) {
            if (!res) {
                response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
            }
            response.send(JSON.stringify({error: response.error}));
            return;
        }

        get_user_statuses(res.posts, response);   //Passing response object here

    });
});
</code>```

The issue is that response object passed from express route is not defined in get_user_statuses function. Now I have two question:

Why is response object is not defined?

Is there better approach to achieve this arrangement?

答:
I solved my problem. I needed to create a function with a callback. In case anyone else is stuck at this kind of issue, this post helped me resolve it: </p>

<p>[How to recurse asynchronously over API callbacks in node.js?</p>

Body:
I am using Facebook Graph NodeJS API to fetch user_posts. The response has pagination and therefore I need to loop over the response to fetch all the posts. I am using following route to fetch facebook posts and I am looping over pagination using get_user_statuses function:

var posts = "";

function get_user_statuses(response_posts, res) {

    var link_regex = /https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,}/g;
    var isNextPageAvailable = true;

    if ("paging" in response_posts) {
        var nextPage = response_posts.paging.next;
        isNextPageAvailable = true;

    } else {
        isNextPageAvailable = false;
    }

    for (var i = 0; i < response_posts.data.length; i++) {

        var post = response_posts.data[i].message + " ";

        if ("message" in response_posts.data[i]) {
            posts += post.replace(link_regex, "");
        }
    }

    if (nextPage !== undefined) {
        request(nextPage, function (error, response, body) {

            if (!error && response.statusCode === 200) {
                get_user_statuses(JSON.parse(body));

            } else {
                console.log(error);
            }
        });
    }

    if (!isNextPageAvailable){
        //Sending posts to facebook Modal
        console.log(posts);
        res.send(JSON.stringify({posts: posts}));    //res is not defined here
    }
}

router.post('/fbData', function (req, response, next) {

    FB.setAccessToken(req.body.access_token);
    FB.api('/me?fields=posts&posts.limit=1000', function (res) {

        if (!res || res.error) {
            if (!res) {
                response.send(JSON.stringify({error: 'An error occurred. Please try again.'}))
            }
            response.send(JSON.stringify({error: response.error}));
            return;
        }

        get_user_statuses(res.posts, response);   //Passing response object here

    });
});

The issue is that response object passed from express route is not defined in get_user_statuses function. Now I have two question:

Why is response object is not defined?

Is there better approach to achieve this arrangement?

Body:
I solved my problem. I needed to create a function with a callback. In case anyone else is stuck at this kind of issue, this post helped me resolve it:

[How to recurse asynchronously over API callbacks in node.js?


问:
CakePHP redirect with status code 404
For CakePHP errors I know that there exists CakeError and AppError solutions.
But I need to make a redirection within controller.

In AppController there exists:

```<code>function afterFilter() {
    if ($this->response->statusCode() == '404')
    {
        $this->redirect(array(
            'controller' => 'mycontroller',
            'action' => 'error', 404),404
        );
    }
}
</code>```

But this doesn't create a 404 status code. It creates a 302 code.
I changed code to this:

```<code>$this->redirect('/mycontroller/error/404', 404);
</code>```

But the result is same.

I added this, it didn't work also deprecated:

```<code>$this->header('http/1.0 404 not found');
</code>```

How can I send a 404 code within controller redirect ?

答:
CakePHP 3</p>

```<code>use Cake\Network\Exception\NotFoundException;
...
throw new NotFoundException(__('Article not found'));
</code>```

Title: CakePHP redirect with status code 404

Body:
For CakePHP errors I know that there exists CakeError and AppError solutions.
But I need to make a redirection within controller.

In AppController there exists:

function afterFilter() {
    if ($this->response->statusCode() == '404')
    {
        $this->redirect(array(
            'controller' => 'mycontroller',
            'action' => 'error', 404),404
        );
    }
}

But this doesn't create a 404 status code. It creates a 302 code.
I changed code to this:

$this->redirect('/mycontroller/error/404', 404);

But the result is same.

I added this, it didn't work also deprecated:

$this->header('http/1.0 404 not found');

How can I send a 404 code within controller redirect ?

Body:
CakePHP 3

use Cake\Network\Exception\NotFoundException;
...
throw new NotFoundException(__('Article not found'));

ContentLicense: CC BY-SA 4.0


问:
Haskell: "Couldn't match expected type IO () with IO ThreadId"
I'm new to concurrency in Haskell and I'm trying to get a result where a new MVar is made in the main thread, is passed over empty to the userThread thread, which takes a character input from the user, then puts that value in an MVar and has the main thread print it.

Here is what I have so far

```<code>module Main where

import Control.Concurrent
import Control.Monad
import System.IO
import System.Random
import Text.Printf

data Msg = C Char | Time

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  hSetBuffering stdin NoBuffering
  hSetEcho stdin False

  -- shared resources
  chan <- newEmptyMVar
  forkIO $ userThread chan
  --r <- takeMVar chan
  --show(r)

userThread :: MVar Msg -> IO ()
userThread chan = forever $ do
  x <- getChar
  putMVar chan (C x)
</code>```

Right now, I'm stuck on trying to put the entered char into the MVar, I've pasted the error below

```<code>assignment1.hs:20:3: error:
    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId
    * In a stmt of a 'do' block: forkIO $ userThread chan
      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.
</code>```

Any pointers in the right direction would be a great help!
Thanks everyone

答:
forkIO $ userThread chan is an IO action which returns ThreadId, and being the last statement in the main do block, it makes main return that as well. However, you declared main :: IO () so there's a type mismatch.

Simply return a dummy tuple.

```<code>main = do
   ...
   forkIO $ userThread chan
   return ()
</code>```

(There's also a void library function for this, but you can ignore it.)

Body:
I'm new to concurrency in Haskell and I'm trying to get a result where a new MVar is made in the main thread, is passed over empty to the userThread thread, which takes a character input from the user, then puts that value in an MVar and has the main thread print it.

Here is what I have so far

module Main where

import Control.Concurrent
import Control.Monad
import System.IO
import System.Random
import Text.Printf

data Msg = C Char | Time

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  hSetBuffering stdin NoBuffering
  hSetEcho stdin False

  -- shared resources
  chan <- newEmptyMVar
  forkIO $ userThread chan
  --r <- takeMVar chan
  --show(r)

userThread :: MVar Msg -> IO ()
userThread chan = forever $ do
  x <- getChar
  putMVar chan (C x)

Right now, I'm stuck on trying to put the entered char into the MVar, I've pasted the error below

assignment1.hs:20:3: error:
    * Couldn't match type `ThreadId' with `()'
      Expected type: IO ()
        Actual type: IO ThreadId
    * In a stmt of a 'do' block: forkIO $ userThread chan
      In the expression:
        do { hSetBuffering stdout NoBuffering;
             hSetBuffering stdin NoBuffering;
             hSetEcho stdin False;
             chan <- newEmptyMVar;
             .... }
      In an equation for `main':
          main
            = do { hSetBuffering stdout NoBuffering;
                   hSetBuffering stdin NoBuffering;
                   hSetEcho stdin False;
                   .... }
Failed, modules loaded: none.

Any pointers in the right direction would be a great help!
Thanks everyone

Body:
forkIO $ userThread chan is an IO action which returns ThreadId, and being the last statement in the main do block, it makes main return that as well. However, you declared main :: IO () so there's a type mismatch.

Simply return a dummy tuple.

main = do
   ...
   forkIO $ userThread chan
   return ()

(There's also a void library function for this, but you can ignore it.)


问:
How to update array to firebase?
I am new in this field. I see there are many ways on the internet and most of them is about the old version of Firebase, like using push(), update(), save(). So, I really don't know how to update it. I tried that like this:

```<code>function writeNewEvent(eObj) {
          // A post entry.
            var userObj = authObj.$getAuth();

            // Get a key for a new Post.
            var newEventKey = ref.child('events').child(userObj.uid).push().key;

            // Write the new post's data simultaneously in the posts list and the user's post list.
            var updates = {};
            updates['/events/' + userObj.uid+ '/' + newEventKey] = userObj;

            return ref.update(updates);
        }
</code>```

But the error is:

```<code>angular.js:13920 Error: Firebase.update failed: First argument  contains an invalid key ($d) in property 'events.LRnkjDgEu1QtuvUTazTwyms4U063.-KW56c87MThrK0PZp-XH.f'.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"
</code>```

Could you tell me if my method is correct? And how to implement this function.

答:
It looks like you have an ID so you don't need to use push(), just set() at the id like:

```<code>// assuming your input looks somthing like:
let eObj = {
  "uuid": "98765-8765-1234567890-7890",
  "some-data": "stuff",
  "other-data": "other stuff",
  "numeric-data": 12345
}

function writeNewEventUsingObjUuid(eObj) {
  // A post entry.
  var userObj = authObj.$getAuth();

  return ref.child('events').child(userObj.uid).set(eObj).then(function () {
    console.log('Event added with ID: ' + userObj.uid);
  }).catch(function (e) {
    console.log('Error adding event: ' + e.message);
  });
}
</code>```

If you really want to use push(), firebase will assign you an ID. Note that an empty push() like you had returns a thenable reference. The work is still done asynchronously event though you get an ID upfront.

Title: How to update array to firebase?

Body:
I am new in this field. I see there are many ways on the internet and most of them is about the old version of Firebase, like using push(), update(), save(). So, I really don't know how to update it. I tried that like this:

function writeNewEvent(eObj) {
          // A post entry.
            var userObj = authObj.$getAuth();

            // Get a key for a new Post.
            var newEventKey = ref.child('events').child(userObj.uid).push().key;

            // Write the new post's data simultaneously in the posts list and the user's post list.
            var updates = {};
            updates['/events/' + userObj.uid+ '/' + newEventKey] = userObj;

            return ref.update(updates);
        }

But the error is:

angular.js:13920 Error: Firebase.update failed: First argument  contains an invalid key ($d) in property 'events.LRnkjDgEu1QtuvUTazTwyms4U063.-KW56c87MThrK0PZp-XH.f'.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"

Could you tell me if my method is correct? And how to implement this function.

Body:
It looks like you have an ID so you don't need to use push(), just set() at the id like:

// assuming your input looks somthing like:
let eObj = {
  "uuid": "98765-8765-1234567890-7890",
  "some-data": "stuff",
  "other-data": "other stuff",
  "numeric-data": 12345
}

function writeNewEventUsingObjUuid(eObj) {
  // A post entry.
  var userObj = authObj.$getAuth();

  return ref.child('events').child(userObj.uid).set(eObj).then(function () {
    console.log('Event added with ID: ' + userObj.uid);
  }).catch(function (e) {
    console.log('Error adding event: ' + e.message);
  });
}

If you really want to use push(), firebase will assign you an ID. Note that an empty push() like you had returns a thenable reference. The work is still done asynchronously event though you get an ID upfront.


问:
PHP: Create XML file and send it with curl?
How do I create an XML-file with PHP and then send it with curl?

I have come this far:

```<code><?php
ob_start();

header("Content-type: text/xml");
header('Content-Disposition: attachment; filename="feed.xml"');
?>

<products>
<?php
foreach ($products as $product)
{
?>
<product></product>
<?php
}
?>
</products>

<?php
ob_flush();

 $curlOpts = array(
    CURLOPT_URL => 'https://website.com/api/importfile',
    CURLOPT_GET => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array('Authorization: api 1234-56789', 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition: form-data; name="feed"; filename="feed.xml"')
);

$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$response = curl_exec($ch);
curl_close($ch);
?>
</code>```

But don't know how to continue. How do I get it to be a "file" and connect it to the curl call? Do I have to save it as a file locally first? Or is it possible to just save it to the curl call?

答:
It seems you just need to send file using curl ... this might help:

http://code.stephenmorley.org/php/sending-files-using-curl/

Body:
How do I create an XML-file with PHP and then send it with curl?

I have come this far:

<?php
ob_start();

header("Content-type: text/xml");
header('Content-Disposition: attachment; filename="feed.xml"');
?>

<products>
<?php
foreach ($products as $product)
{
?>
<product></product>
<?php
}
?>
</products>

<?php
ob_flush();

 $curlOpts = array(
    CURLOPT_URL => 'https://website.com/api/importfile',
    CURLOPT_GET => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array('Authorization: api 1234-56789', 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Disposition: form-data; name="feed"; filename="feed.xml"')
);

$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$response = curl_exec($ch);
curl_close($ch);
?>

But don't know how to continue. How do I get it to be a "file" and connect it to the curl call? Do I have to save it as a file locally first? Or is it possible to just save it to the curl call?