问:
jQuery/Ajax like button not working properly second time
I'm trying to create an Ajax like button for my Django project(Python's framework). Basically, what I'm doing is making a partial update on index.html when the Ajax call is a success. It works fine the first time, but when a button with the same id is clicked for the second time, it will reload the entire page, which is not what I expect. Could anyone teach me how to prevent this from happening?

I'm not sure if the Python side has anything to do with this, but I'm going to paste some of the codes anyway. Thank you.

main.js

```<code>  $('button').on('click', function(event){
      event.preventDefault();
      var element = $(this);
      $.ajax({
        url : element.attr("data-id") + '/like/',
        type : 'POST',
        data : { card_id : element.attr("data-id")},
        success : function(response){
          console.log(response);
          $('#like-area-' + element.attr("data-id")).load(document.URL +  ' #like-area-' + element.attr("data-id"));
        }
      })
    })

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
</code>```

templates/index.html

```<code>{% for card in cards %}

......

    <section id="like-area-{{ card.id }}">

        <!-- currently testing if ajax works properly with this button-->
        <form  method="post">
                {% csrf_token %}
                <button data-id="{{ card.id }}"　class="btn btn-default">いいね</button>
        </form>

        <!-- ultimately I'd like to fire up ajax through this anchor tag -->
        <a id="like-button-{{ card.id }}" href="{% url 'like-post' card.id %}"><span class="glyphicon glyphicon-heart
        {% for your_like in your_likes %}
            {% if card  == your_like.liked_post %}
            red no-border
            {% endif %}
        {% endfor %}
        "></span></a>
    </section>

.....

{% endfor %}
</code>```

views.py

```<code>def like_post(request, card_id):
    if Like.objects.filter(liker=request.user, liked_post = card_id).exists():
        existing_like = Like.objects.get(liker=request.user, liked_post = card_id)
        existing_like.delete()
        likes = Like.objects.all()
        is_liked = 0
        # return HttpResponse(likes)
        return HttpResponse(is_liked) #not really using this yet
    else:
        card = Card.objects.get(id=card_id)
        new_like = Like(liker=request.user, liked_post = card)
        new_like.save()
        # likes = Like.objects.all()
        likes = Like.objects.all()
        is_liked = 1
        return HttpResponse(is_liked) #not really using this yet
</code>```

urls.py

```<code>url(r'^(?P<card_id>[0-9]+)/like/$', views.like_post, name='like-post'),
</code>```

答:
I just read your request: ajax cần't click 2 time (need reload or it auto reload page)

~> Create a var for ajax and abort it.

```<code>var ajaxcall1
def ...
if (ajaxcall1)
        ajaxcall1.abort();
# some more code
</code>```

You can try it, i just think you don't check the status. If not, i will check for more detail late

Body:
I'm trying to create an Ajax like button for my Django project(Python's framework). Basically, what I'm doing is making a partial update on index.html when the Ajax call is a success. It works fine the first time, but when a button with the same id is clicked for the second time, it will reload the entire page, which is not what I expect. Could anyone teach me how to prevent this from happening?

I'm not sure if the Python side has anything to do with this, but I'm going to paste some of the codes anyway. Thank you.

main.js

  $('button').on('click', function(event){
      event.preventDefault();
      var element = $(this);
      $.ajax({
        url : element.attr("data-id") + '/like/',
        type : 'POST',
        data : { card_id : element.attr("data-id")},
        success : function(response){
          console.log(response);
          $('#like-area-' + element.attr("data-id")).load(document.URL +  ' #like-area-' + element.attr("data-id"));
        }
      })
    })

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

templates/index.html

{% for card in cards %}

......

        <form  method="post">
                {% csrf_token %}
                <button data-id="{{ card.id }}"　class="btn btn-default">いいね</button>
        </form>

.....

{% endfor %}

views.py

def like_post(request, card_id):
    if Like.objects.filter(liker=request.user, liked_post = card_id).exists():
        existing_like = Like.objects.get(liker=request.user, liked_post = card_id)
        existing_like.delete()
        likes = Like.objects.all()
        is_liked = 0
        # return HttpResponse(likes)
        return HttpResponse(is_liked) #not really using this yet
    else:
        card = Card.objects.get(id=card_id)
        new_like = Like(liker=request.user, liked_post = card)
        new_like.save()
        # likes = Like.objects.all()
        likes = Like.objects.all()
        is_liked = 1
        return HttpResponse(is_liked) #not really using this yet

urls.py

url(r'^(?P<card_id>[0-9]+)/like/$', views.like_post, name='like-post'),

Body:
I just read your request: ajax cần't click 2 time (need reload or it auto reload page)

~> Create a var for ajax and abort it.

var ajaxcall1
def ...
if (ajaxcall1)
        ajaxcall1.abort();
# some more code

You can try it, i just think you don't check the status. If not, i will check for more detail late


来源: stackexchange

问:
Merge deep groups of rows by their numeric key and sum column values while grouping
I have the following array which needs to be reduced with internal values being summed.

Input:

```<code>$array = [
    [
        121 => [ "number" => 121, "name" => "Some Name 1", "value" => "2.222" ],
        116 => [ "number" => 116, "name" => "Some Name 2", "value" => "1.111" ],
          1 => [ "number" =>   1, "name" => "Some Name 3", "value" => "1.232" ]
    ],
    [
        121 => [ "number" => 121, "name" => "Some Name 1", "value" => "1.111" ],
        116 => [ "number" => 116, "name" => "Some Name 2", "value" => "2.222" ],
          1 => [ "number" =>   1, "name" => "Some Name 3", "value" => "3.111" ]
    ]
];
</code>```

Desired result:

```<code>0 => array:116 [
  121 => array:3 [
    "number" => 121
    "name" => "Some Name 1"
    "value" => "3.333"
  ]
  116 => array:3 [
    "number" => 116
    "name" => "Some Name 2"
    "value" => "3.333"
  ]
  1 => array:3 [
    "number" => 1
    "name" => "Some Name 3"
    "value" => "4.343"
  ]
]
</code>```

What would be the efficient/effective way to calculate the resulting array based on the input, assuming that the length of input array is undefined, but the complexity/nesting level is 2 maximum.

I am seeking a performance optimized solution for PHP5.6 as well as PHP7+.

答:
I updated the functionality to be able to take many children. In the repl I've linked two I added an extra child to both array key's 0 and 1.

```<code>// Merege $a[0] and $a[1] and sum up the `value` key

$merge_sum = array_map(function($key, ...$a) {
  $merged = array_merge(...$a);
  $merged['value'] = array_sum(array_column($a, 'value'));
  return [ $key => $merged ];
}, array_keys($a[0]), ...$a);

// // Fix array array keys

$final = array_reduce($merge_sum, function($c, $i) {
  $concat = $c + $i;
  return $concat;
}, []);

var_dump($final);
</code>```

Test it on this repl; https://repl.it/Id7T/6

ContentLicense: CC BY-SA 4.0

Body:
I have the following array which needs to be reduced with internal values being summed.

Input:

$array = [
    [
        121 => [ "number" => 121, "name" => "Some Name 1", "value" => "2.222" ],
        116 => [ "number" => 116, "name" => "Some Name 2", "value" => "1.111" ],
          1 => [ "number" =>   1, "name" => "Some Name 3", "value" => "1.232" ]
    ],
    [
        121 => [ "number" => 121, "name" => "Some Name 1", "value" => "1.111" ],
        116 => [ "number" => 116, "name" => "Some Name 2", "value" => "2.222" ],
          1 => [ "number" =>   1, "name" => "Some Name 3", "value" => "3.111" ]
    ]
];

Desired result:

0 => array:116 [
  121 => array:3 [
    "number" => 121
    "name" => "Some Name 1"
    "value" => "3.333"
  ]
  116 => array:3 [
    "number" => 116
    "name" => "Some Name 2"
    "value" => "3.333"
  ]
  1 => array:3 [
    "number" => 1
    "name" => "Some Name 3"
    "value" => "4.343"
  ]
]

What would be the efficient/effective way to calculate the resulting array based on the input, assuming that the length of input array is undefined, but the complexity/nesting level is 2 maximum.

I am seeking a performance optimized solution for PHP5.6 as well as PHP7+.

Body:
I updated the functionality to be able to take many children. In the repl I've linked two I added an extra child to both array key's 0 and 1.

// Merege $a[0] and $a[1] and sum up the `value` key

$merge_sum = array_map(function($key, ...$a) {
  $merged = array_merge(...$a);
  $merged['value'] = array_sum(array_column($a, 'value'));
  return [ $key => $merged ];
}, array_keys($a[0]), ...$a);

// // Fix array array keys

$final = array_reduce($merge_sum, function($c, $i) {
  $concat = $c + $i;
  return $concat;
}, []);

var_dump($final);

Test it on this repl; https://repl.it/Id7T/6

ContentLicense: CC BY-SA 3.0


问:
Google play app signing key hash
I have opted for google play app signing and i understand that google changes the signing keys for the app and I found the Sha 1 certificate but couldnt find the keyhash .

How can i get the keyhash of my released app is there a way to extract it from the certificate?

答:
You can extract keyhash from the Sha1 certificate signature. Key hashes are usually extracted in the following way:

```<code>public static String getKeyHash(final Context context) {
    PackageInfo packageInfo = getPackageInfo(context, PackageManager.GET_SIGNATURES);
    if (packageInfo == null)
        return null;

    for (Signature signature : packageInfo.signatures) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
        } catch (NoSuchAlgorithmException e) {
            Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e);
        }
    }
    return null;
}
</code>```

You can see that SHA-1 version of signature is Base64 encoded.

Under App Signing menu in Google play developer console, you will see Sha-1 certificate signature that looks like this:

```<code>SHA1: 3B:DA:A0:5B:4F:35:71:02:4E:27:22:B9:AC:B2:77:2F:9D:A9:9B:D9
</code>```

Basically, what you have to do is to change this into a byte array and Base64 encode that byte array. You can do something like:

```<code>byte[] sha1 = {
    0x3B, (byte)0xDA, (byte)0xA0, 0x5B, 0x4F, 0x35, 0x71, 0x02, 0x4E, 0x27, 0x22, (byte)0xB9, (byte)0xAc, (byte)0xB2, 0x77, 0x2F, (byte)0x9D, (byte)0xA9, (byte)0x9B, (byte)0xD9
};
Log.e("keyhash", Base64.encodeToString(sha1, Base64.NO_WRAP));
</code>```

You can register this keyhash to facebook android login settings or wherever you like.

Title: Google play app signing key hash

Body:
You can extract keyhash from the Sha1 certificate signature. Key hashes are usually extracted in the following way:

public static String getKeyHash(final Context context) {
    PackageInfo packageInfo = getPackageInfo(context, PackageManager.GET_SIGNATURES);
    if (packageInfo == null)
        return null;

    for (Signature signature : packageInfo.signatures) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
        } catch (NoSuchAlgorithmException e) {
            Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e);
        }
    }
    return null;
}

You can see that SHA-1 version of signature is Base64 encoded.

Under App Signing menu in Google play developer console, you will see Sha-1 certificate signature that looks like this:

SHA1: 3B:DA:A0:5B:4F:35:71:02:4E:27:22:B9:AC:B2:77:2F:9D:A9:9B:D9

Basically, what you have to do is to change this into a byte array and Base64 encode that byte array. You can do something like:

byte[] sha1 = {
    0x3B, (byte)0xDA, (byte)0xA0, 0x5B, 0x4F, 0x35, 0x71, 0x02, 0x4E, 0x27, 0x22, (byte)0xB9, (byte)0xAc, (byte)0xB2, 0x77, 0x2F, (byte)0x9D, (byte)0xA9, (byte)0x9B, (byte)0xD9
};
Log.e("keyhash", Base64.encodeToString(sha1, Base64.NO_WRAP));

You can register this keyhash to facebook android login settings or wherever you like.


问:
Java PriorityQueue implementation: Why Object[] queue instead of E[] queue? What's the purpose of "key" in siftUp/siftDownComparable?
I'm studying the JDK implementation of PriorityQueue.

1) The entire queue is stored in

```<code> transient Object[] queue;
</code>```

Why not declare the array using the generic E? (Instead, there's a lot of casting E to objects in the class.)

2) The first line of the siftUpComparable/siftDownComparable methods is

```<code>    Comparable<? super E> key = (Comparable<? super E>)x;
</code>```

Is this a guard clause to verify that x is comparable? (Otherwise, why not just use x directly?)

Here's the entire method:

```<code>private void siftDownComparable(int k, E x) {
    Comparable<? super E> key = (Comparable<? super E>)x;
    int half = size >>> 1;        // loop while a non-leaf
    while (k < half) {
        int child = (k << 1) + 1; // assume left child is least
        Object c = queue[child];
        int right = child + 1;
        if (right < size &&
            ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
            c = queue[child = right];
        if (key.compareTo((E) c) <= 0)
            break;
        queue[k] = c;
        k = child;
    }
    queue[k] = key;
}
</code>```

答:
1) You cannot instantiate an array of a generic type without having a reference to the Class of the object. See JavaDevil's comment below for an example. However, by creating an array of Object's instead, there's is no requirement to feed an instance of the Class to the PriorityQueue.

```<code>E[] array = new E[10]; // won't compile
</code>```

2) A PriorityQueue can sort its elements either by a Comparable's object compareTo() method or using a Comparator for objects that are not necessarily Comparable. The siftDownComparable method is only invoked if a Comparator was not provided when the PriorityQueue was created. Since the type parameter does not stipulate that <E extends Comparable>, you need to cast it explicitly. Here's the siftDown() method.

```<code>private void siftDown(int k, E x) {
    if (comparator != null)
        siftDownUsingComparator(k, x);
    else
        siftDownComparable(k, x);
}
</code>```

Body:
I'm studying the JDK implementation of PriorityQueue.

1) The entire queue is stored in

 transient Object[] queue;

Why not declare the array using the generic E? (Instead, there's a lot of casting E to objects in the class.)

2) The first line of the siftUpComparable/siftDownComparable methods is

    Comparable<? super E> key = (Comparable<? super E>)x;

Is this a guard clause to verify that x is comparable? (Otherwise, why not just use x directly?)

Here's the entire method:

private void siftDownComparable(int k, E x) {
    Comparable<? super E> key = (Comparable<? super E>)x;
    int half = size >>> 1;        // loop while a non-leaf
    while (k < half) {
        int child = (k << 1) + 1; // assume left child is least
        Object c = queue[child];
        int right = child + 1;
        if (right < size &&
            ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
            c = queue[child = right];
        if (key.compareTo((E) c) <= 0)
            break;
        queue[k] = c;
        k = child;
    }
    queue[k] = key;
}

Body:
1) You cannot instantiate an array of a generic type without having a reference to the Class of the object. See JavaDevil's comment below for an example. However, by creating an array of Object's instead, there's is no requirement to feed an instance of the Class to the PriorityQueue.

E[] array = new E[10]; // won't compile

2) A PriorityQueue can sort its elements either by a Comparable's object compareTo() method or using a Comparator for objects that are not necessarily Comparable. The siftDownComparable method is only invoked if a Comparator was not provided when the PriorityQueue was created. Since the type parameter does not stipulate that <E extends Comparable>, you need to cast it explicitly. Here's the siftDown() method.

private void siftDown(int k, E x) {
    if (comparator != null)
        siftDownUsingComparator(k, x);
    else
        siftDownComparable(k, x);
}


问:
NLog: logging an object serialized to JSON
I have .Net project with NLog configuration which allows me to produce JSON-formatted log file. It works fine with simple text messages. Now, I need to log a number of arbitrary objects already serialized to JSON. When I log those JSON strings as log messages, NLog puts the text in quotes and subsequently escapes inner JSON syntax. This renders such output unusable. So far I have failed to find an NLog feature or layout setting that would simply dump my JSON string as a literal, without quotation marks and escape characters. Am I missing something?

Example. Currently my log entries look like:]

```<code>{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message": "\"description\": \"blah-blah\", \"Request\": { \"Request URL\":\/somepagepage\/}, \"Content\": { \"Form\": { ... } , \"Body\": \"Blah\" } ", "utcDateTime": "2017-06-05 06:10:34.1411" }
</code>```

Instead, I need to make them to look like:

```<code>{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message":
 { "description": "blah-blah", "Request": { "Request URL":/somepagepage/, "Content": { "Form": {...}, "Body": "Blah" }  }, "utcDateTime": "2017-06-05 06:10:34.1411" }
</code>```

Relevant section from NLog.config:

 <layout xsi:type="JsonLayout">
   <attribute name="dateTime" layout="${longdate}" />
   <attribute name="level" layout="${level:upperCase=true}"/>
   <attribute name="message" layout="${message}" />
   <attribute name="utcDateTime" layout="${longdate:universalTime=true}" />
 </layout>
```

Ultimately, I would like to see a log entry with JSON nested inside "message", and not a quoted version of it.

答:
As per @Rolf Kristensen's commentary above. Essentially, parameter encode="false" allows to log unquoted JSON:

```<code>  <attribute name="message" layout="${message}" encode="false" />
</code>```

Plain text also comes out unquoted now, but this can be dealt with by a custom layout renderer that can tell plain text from JSON.

Body:
I have .Net project with NLog configuration which allows me to produce JSON-formatted log file. It works fine with simple text messages. Now, I need to log a number of arbitrary objects already serialized to JSON. When I log those JSON strings as log messages, NLog puts the text in quotes and subsequently escapes inner JSON syntax. This renders such output unusable. So far I have failed to find an NLog feature or layout setting that would simply dump my JSON string as a literal, without quotation marks and escape characters. Am I missing something?

Example. Currently my log entries look like:]

{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message": "\"description\": \"blah-blah\", \"Request\": { \"Request URL\":\/somepagepage\/}, \"Content\": { \"Form\": { ... } , \"Body\": \"Blah\" } ", "utcDateTime": "2017-06-05 06:10:34.1411" }

Instead, I need to make them to look like:

{ "dateTime": "2017-06-07 11:50:55.7324", "level": "DEBUG", "message":
 { "description": "blah-blah", "Request": { "Request URL":/somepagepage/, "Content": { "Form": {...}, "Body": "Blah" }  }, "utcDateTime": "2017-06-05 06:10:34.1411" }

Relevant section from NLog.config:

 <layout xsi:type="JsonLayout">
   <attribute name="dateTime" layout="${longdate}" />
   <attribute name="level" layout="${level:upperCase=true}"/>
   <attribute name="message" layout="${message}" />
   <attribute name="utcDateTime" layout="${longdate:universalTime=true}" />
 </layout>

Ultimately, I would like to see a log entry with JSON nested inside "message", and not a quoted version of it.

Body:
As per @Rolf Kristensen's commentary above. Essentially, parameter encode="false" allows to log unquoted JSON:

  <attribute name="message" layout="${message}" encode="false" />

Plain text also comes out unquoted now, but this can be dealt with by a custom layout renderer that can tell plain text from JSON.


问:
Keyboard shortcut to open Google Chrome on Mac
On a Mac, I'd like to have a keyboard shortcut to open Google Chrome.  I know how to set a keyboard shortcut in the system preferences, however I'm unsure how to script it and hook it up.

Is this possible through AppleScript?

答:
Here is a trick.
Use Ctrl + ↑ to create a new desktop, say desktop2, and drag chrome application into that new desktop.

Open the keyboard preference pane, switch to the shortcut tab, and select  mission control to assign a key to that desktop2. Now you can switch to chrome use that key.


问:
Regex to match [any char][any digit]dot with an exception case
I have a regex [a-zA-Z0-9]\\.(.*) to match:
[any character, any digit] followed by a dot and then followed by anything. For example e1.abc, r11.xyz, etc.

This works fine. However I have a case where if string is e.abc then it should not match i.e. only if it is e. then it should not match.

How do I modify my regex to handle this specific exclusion?

答:
You can modify your regex by adding a negative lookahead assertion before the first pre-dot character.  This lookahead will ensure that this first letter is not e.  Here is the pattern:

```<code>.*(?!e)[a-zA-Z0-9]\.(.*)
</code>```

Sample code:

```<code>String match = "a.abc";
if (match.matches(".*(?!e)[a-zA-Z0-9]\\.(.*)")) {
    System.out.println("match");
}
String noMatch = "e.abc";
if (noMatch.matches(".*(?!e)[a-zA-Z0-9]\\.(.*)")) {
    System.out.println("no match");
}
</code>```

Note that I assume that there is only one dot in your string.  If not, then this answer would need to change.

Demo here:

Rextester

Body:
You can modify your regex by adding a negative lookahead assertion before the first pre-dot character.  This lookahead will ensure that this first letter is not e.  Here is the pattern:

.*(?!e)[a-zA-Z0-9]\.(.*)

Sample code:

String match = "a.abc";
if (match.matches(".*(?!e)[a-zA-Z0-9]\\.(.*)")) {
    System.out.println("match");
}
String noMatch = "e.abc";
if (noMatch.matches(".*(?!e)[a-zA-Z0-9]\\.(.*)")) {
    System.out.println("no match");
}

Note that I assume that there is only one dot in your string.  If not, then this answer would need to change.

Demo here:

Rextester


问:
How remove \n from lines
```<code>file, _ := os.Open("x.txt")
    f := bufio.NewReader(file)

    for {
        read_line, _ := ReadString('\n')
        fmt.Print(read_line)

        // other code what work with parsed line...
        }
</code>```

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

答:
You can slice off the last character:

```<code>read_line = read_line[:len(read_line)-1]
</code>```

Perhaps a better approach is to use the strings library:

```<code>read_line = strings.TrimSuffix(read_line, "\n")
</code>```

Title: How remove \n from lines

Body:
file, _ := os.Open("x.txt")
    f := bufio.NewReader(file)

    for {
        read_line, _ := ReadString('\n')
        fmt.Print(read_line)

        // other code what work with parsed line...
        }

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

Body:
You can slice off the last character:

read_line = read_line[:len(read_line)-1]

Perhaps a better approach is to use the strings library:

read_line = strings.TrimSuffix(read_line, "\n")


问:
How to do 'Average' in Prolog?
I'm trying to do a predicate of average in Prolog, but I'm facing some problems,

it's called average(N,X), with N is a number, and X is the result of the average from 1 to N .

I've tried to do this,  but it doesn't always work well :

```<code>       average(1,1).
       average(N,X) :- K is N-1 ,K>1 , average(K,S1) , X is /(+(S1,N),N).
       average(N,X) :- K is N-1 ,K=:=1 , average(K,S1) , X is +(S1,N).
</code>```

Some help ?

答:
Think about your rules...

```<code>average(1, 1).
</code>```

The average of 1 is 1.

That sounds correct. I'm going to skip to your 3rd rule, which is also quite specific, but just verbose:

```<code>average(N,X) :- K is N-1 ,K=:=1 , average(K,S1) , X is +(S1,N).
</code>```

The average of 1 to N is X if K is N-1, K is 1, the average of K numbers is S1, and X is S1+N.

This could be simplified a great deal since N is necessarily 2 in this rule:

```<code>average(2, X) :- average(1, S1), X is S1 + 2.
</code>```

Then further, since we know the one result for average(1, S1):

```<code>average(2, X) :- X is 3   % X is 1 + 2
</code>```

And then even further, just:

```<code>average(2, 3).
</code>```

So you don't need all that logic for your 3rd rule.

Now let's look at the second rule, which is your most general case:

```<code>average(N,X) :- K is N-1 ,K>1 , average(K,S1) , X is /(+(S1,N),N).
</code>```

The average of 1 to N is X if K is N-1, K > 1, the average of 1 to K is S1, and X is (S1 + N)/N.

This is the case where K > 1, or equivalently, N > 2. It's saying I can take the average of 1 to N by first taking the average of 1 to N-1, then just add N and then divide by N to get the average of 1 to N. This isn't mathematically valid. Let's take a simple counter example where N is 3:

```<code>S1 = average of 1 to 2, = (1+2)/2 = 1.5.
</code>```

Now if we say the average of 1 to 3 is the average of 1 to 2 added to 3 then divided by 3, we'd get:

```<code>S = average of 1 to 3 = (S1 + 3)/3 = (1.5+3)/3 = 4.5/3 = 1.5
</code>```

However, the correct answer is (1+2+3)/3 which is 6/3 or just 2.

What would the correct formula be? Well, S1 being the average of 1 to N-1 would be sum of 1 to N-1 / (N-1). If I want to go from that to S, the sum of 1 to N / N, which is the average of 1 to N, I would need to multiply S1 by N-1, then add in N, then divide by N. In other words, your 2nd rule should be:

```<code>average(N,X) :- K is N-1, K > 1 , average(K, S1), X is (S1*(N-1)+N)/N.
</code>```

Going back to our trivial example for 1 to 3, we found the average of 1 to 2 was 1.5. If we multiply that back by 2, then add 3, then divide by 3, we get: ((1.5*2)+3)/3 = (3+3)/3 = 6/3 = 2, which is the correct answer.

In summary, your rules become:

```<code>average(1, 1).
average(2, 3).
average(N, X) :- K is N-1, K > 1 , average(K, S1), X is (S1*(N-1)+N)/N.
</code>```

But really you don't need the second rule. The 3rd rule and the base case take care of it for you if we adjust the condition in the 3rd rule for K (or really just make it a rule for N, which is clearer). So just:

```<code>average(1, 1).
average(N, X) :- N > 1, K is N-1, average(K, S1), X is (S1*(N-1)+N)/N.
</code>```

As an aside, I assume this is just an exercise in recursion in Prolog since there is already a simple formula for the sum of numbers from 1 to N (N*(N+1)/2), and therefore for the average, which would be: (N+1)/2.

Title: How to do 'Average' in Prolog?

Body:
I'm trying to do a predicate of average in Prolog, but I'm facing some problems,

it's called average(N,X), with N is a number, and X is the result of the average from 1 to N .

I've tried to do this,  but it doesn't always work well :

       average(1,1).
       average(N,X) :- K is N-1 ,K>1 , average(K,S1) , X is /(+(S1,N),N).
       average(N,X) :- K is N-1 ,K=:=1 , average(K,S1) , X is +(S1,N).

Some help ?

Body:
Think about your rules...

average(1, 1).

The average of 1 is 1.

That sounds correct. I'm going to skip to your 3rd rule, which is also quite specific, but just verbose:

average(N,X) :- K is N-1 ,K=:=1 , average(K,S1) , X is +(S1,N).

The average of 1 to N is X if K is N-1, K is 1, the average of K numbers is S1, and X is S1+N.

This could be simplified a great deal since N is necessarily 2 in this rule:

average(2, X) :- average(1, S1), X is S1 + 2.

Then further, since we know the one result for average(1, S1):

average(2, X) :- X is 3   % X is 1 + 2

And then even further, just:

average(2, 3).

So you don't need all that logic for your 3rd rule.

Now let's look at the second rule, which is your most general case:

average(N,X) :- K is N-1 ,K>1 , average(K,S1) , X is /(+(S1,N),N).

The average of 1 to N is X if K is N-1, K > 1, the average of 1 to K is S1, and X is (S1 + N)/N.

This is the case where K > 1, or equivalently, N > 2. It's saying I can take the average of 1 to N by first taking the average of 1 to N-1, then just add N and then divide by N to get the average of 1 to N. This isn't mathematically valid. Let's take a simple counter example where N is 3:

S1 = average of 1 to 2, = (1+2)/2 = 1.5.

Now if we say the average of 1 to 3 is the average of 1 to 2 added to 3 then divided by 3, we'd get:

S = average of 1 to 3 = (S1 + 3)/3 = (1.5+3)/3 = 4.5/3 = 1.5

However, the correct answer is (1+2+3)/3 which is 6/3 or just 2.

What would the correct formula be? Well, S1 being the average of 1 to N-1 would be sum of 1 to N-1 / (N-1). If I want to go from that to S, the sum of 1 to N / N, which is the average of 1 to N, I would need to multiply S1 by N-1, then add in N, then divide by N. In other words, your 2nd rule should be:

average(N,X) :- K is N-1, K > 1 , average(K, S1), X is (S1*(N-1)+N)/N.

Going back to our trivial example for 1 to 3, we found the average of 1 to 2 was 1.5. If we multiply that back by 2, then add 3, then divide by 3, we get: ((1.5*2)+3)/3 = (3+3)/3 = 6/3 = 2, which is the correct answer.

In summary, your rules become:

average(1, 1).
average(2, 3).
average(N, X) :- K is N-1, K > 1 , average(K, S1), X is (S1*(N-1)+N)/N.

But really you don't need the second rule. The 3rd rule and the base case take care of it for you if we adjust the condition in the 3rd rule for K (or really just make it a rule for N, which is clearer). So just:

average(1, 1).
average(N, X) :- N > 1, K is N-1, average(K, S1), X is (S1*(N-1)+N)/N.

As an aside, I assume this is just an exercise in recursion in Prolog since there is already a simple formula for the sum of numbers from 1 to N (N*(N+1)/2), and therefore for the average, which would be: (N+1)/2.


问:
Function with multiple classes that have a mixin

The Mixin

I have a mixin that prints the assigns the class name as a String to an instance variable.

```<code>import Foundation

protocol Recyclable {
    static var name: String { get }
}

extension Recyclable {
    static var name: String {
        return String(describing: Self.self)
    }
}
</code>```

There are two classes that implement the mixin:

```<code>class One: NSObject, Recyclable { }
class Two: NSObject, Recyclable { }
</code>```

So if I want to print the class name, I can just

```<code>One.self.name // "One"
</code>```

This works perfectly. Now let's get deeper.

Generic function to print multiple given classes

Putting this into a function to print the name of all given classes. It needs to be a generic, since it can accept any class that conforms to the Recyclable protocol.

```<code>func printAllNames<T: NSObject>(_ things: T.Type...) where T: Recyclable {
    for thing in things {
        print(thing.name)
    }
}
</code>```

If I use this for one class only, it works as expected.

```<code>printAllNames(One.self) // "One"
</code>```

But when used with more than one, it errors out

```<code>printAllNames(One.self, Two.self)
</code>```

Playground execution failed: error: GenericMixins.playground:20:1:
  error: generic parameter 'T' could not be inferred
  printAllNames(One.self, Two.self)

Any hints on what might be happening?

Playground: https://www.dropbox.com/sh/q0b5b3oo0luj471/AABSG2QEOIj_SBsvtv7cEv-Ka?dl=0

答:
I ended up figuring it out. The right approach is to make function accept anything, and then check if what was accepted conforms to the protocol.

The function should be

```<code>func printAllNames(_ things: AnyObject...) {
    for thing in things {
        if let klass = thing.self as? Recyclable.Type {
            print(klass.name)
        }
    }
}
</code>```

And then it works as expected

```<code>printAllNames(One.self, Two.self)
</code>```

One

Two

Updated playground: https://www.dropbox.com/sh/9sjboo3lfu83662/AAC9CKn_dU_wrihCvKUfujQ7a?dl=0

Body:
The Mixin

I have a mixin that prints the assigns the class name as a String to an instance variable.

import Foundation

protocol Recyclable {
    static var name: String { get }
}

extension Recyclable {
    static var name: String {
        return String(describing: Self.self)
    }
}

There are two classes that implement the mixin:

class One: NSObject, Recyclable { }
class Two: NSObject, Recyclable { }

So if I want to print the class name, I can just

One.self.name // "One"

This works perfectly. Now let's get deeper.

Generic function to print multiple given classes

Putting this into a function to print the name of all given classes. It needs to be a generic, since it can accept any class that conforms to the Recyclable protocol.

func printAllNames<T: NSObject>(_ things: T.Type...) where T: Recyclable {
    for thing in things {
        print(thing.name)
    }
}

If I use this for one class only, it works as expected.

printAllNames(One.self) // "One"

But when used with more than one, it errors out

printAllNames(One.self, Two.self)

Playground execution failed: error: GenericMixins.playground:20:1:
  error: generic parameter 'T' could not be inferred
  printAllNames(One.self, Two.self)

Any hints on what might be happening?

Playground: https://www.dropbox.com/sh/q0b5b3oo0luj471/AABSG2QEOIj_SBsvtv7cEv-Ka?dl=0

Body:
I ended up figuring it out. The right approach is to make function accept anything, and then check if what was accepted conforms to the protocol.

The function should be

func printAllNames(_ things: AnyObject...) {
    for thing in things {
        if let klass = thing.self as? Recyclable.Type {
            print(klass.name)
        }
    }
}

And then it works as expected

printAllNames(One.self, Two.self)

One

Two

Updated playground: https://www.dropbox.com/sh/9sjboo3lfu83662/AAC9CKn_dU_wrihCvKUfujQ7a?dl=0


问:
Best way of adding SNMP support to your own application on Debian
I am working on Debian and I have this server we want to monitor.

The application is ours and there are around a hundred real-time counters we want to export for monitoring purposes, graphs and alarms.

I've been looking at the Debian way of doing this because we do use Debian packaging to install the app, and Debian uses snmpd daemon, based on net-snmp, to export SNMP.
So far every approach I've seen looks very complicated, from recompiling snmpd to load a dynamic library into it, and compiling a form of subagent that replicates what snmpd does.

While all of those options make me think I should go for something else than SNMP I don't want to give up that early and I was wondering if anybody has found a feasible implementation.

Ideally it should be coded in C or C++ as the app is in C++, but I'm open to wrappers or other kind of suggestions.

答:
An often overlooked solution is Agent++ API, which to me looks pretty nice and is under the Apache license. As far as I understand, you can modify that agent to answer to your own MIBs.

That said, doing a subagent isn't such a bad choice. You start the standard unpatched snmpd (from net-snmp). Then you connect to it with your subagent, which only adds those OIDs you want it to add. The net-snmp kit for coding AgentX (as the protocol is called) sub-agents is not dead simple to use, but not very hard either. There is also a Perl module for sub-agent development: https://metacpan.org/pod/NetSNMP::agent

ContentLicense: CC BY-SA 2.5


问:
My C# function will not work
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.</p>

```<code>namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}
</code>```

答: Si main is static, AddNumbers must be static as well.

Title: My C# function will not work

Body:
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.

namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}


问:
Excel PasteSpecial function pasting as image
I am trying to copy formatted cells from existing excel sheet  to new sheet in vb.net(2010)  using pastespecial method but it is pasting the cell values as picture rather than text.
Any help in this regard would be highly appreciated:

```<code>    Public Sub set_header(ByVal r As Integer, ByVal c As Integer, ByVal dt1 As Date, ByVal dt2 As Date, ByVal sheetname As String)

    Dim wbCopy As Excel.Workbook
    Dim wsCopy As Excel.Worksheet
    Dim rngCopy As Excel.Range
    Dim wbPaste As Excel.Workbook
    Dim wsPaste As Excel.Worksheet
    Dim rngPaste As Excel.Range
    Dim xlsApp As Excel.Application
    xlsApp = New Excel.Application
    wbCopy = xlsApp.Workbooks.Open("C:\Windows\rta2.xlsx")
    wsCopy = wbCopy.Worksheets(sheetname)
    rngCopy = wsCopy.Range("A7:O9")
    Dim addr As Object
    addr = ExcelSheet.Cells(r, c).Address(False, False)
    rngPaste = ExcelSheet.Range(addr)
    rngCopy.Copy()
    rngPaste.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,false,false)
    ExcelSheet.Cells(r + 2, c + 4) = "from " & dt1 & " to " & dt2
    Set wbCopy = Nothing
    Set wsCopy = Nothing
    Set rngCopy = Nothing
    Set wbPaste = Nothing
    Set wsPaste = Nothing
    Set rngPaste = Nothing
    ExcelApp.Quit
   End sub
</code>```

Thanks

答:
I have the same problem.
I first check to see if content of clipboard is in excel format.
If yes, I will use Excel's PasteSpecial as Value
If no, I will paste value from clipboard with MSForms.DataObject

below is my code, you can see if it solve the issue:

```<code>' Code Block to prevent pasting Images with PasteSpecial
If IsClipboardContentInExcelFormat Then
    Selection.PasteSpecial Paste:=xlValues
Else
    Selection.Value = GetClipBoardText
End If

Function GetClipBoardText()
   ' src: http://stackoverflow.com/questions/9022245/get-text-from-clipboard-using-gettext-avoid-error-on-empty-clipboard
   Dim DataObj As MSForms.DataObject
   Set DataObj = New MSForms.DataObject '<~~ Amended as per jp's suggestion
   Dim myString As String

   On Error GoTo ErrorHandling

   DataObj.GetFromClipboard '~~> Get data from the clipboard.
   myString = DataObj.GetText(1)
   GetClipBoardText = myString

   Exit Function
ErrorHandling:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Function

' Will use MSForms.DataObject for geting clipboard content
' reference: http://stackoverflow.com/questions/9022245/get-text-from-clipboard-using-gettext-avoid-error-on-empty-clipboard
' reference: http://msdn.microsoft.com/en-us/library/office/ff839748%28v=office.14%29.aspx
Private Function IsClipboardContentInExcelFormat() As Boolean
    IsClipboardContentInExcelFormat = False

    On Error GoTo ErrorHandling

    Dim aFmts, fmt
    aFmts = Application.ClipboardFormats

    For Each fmt In aFmts

        If (fmt = xlClipboardFormatBIFF _
             Or fmt = xlClipboardFormatBIFF12 _
             Or fmt = xlClipboardFormatBIFF2 _
             Or fmt = xlClipboardFormatBIFF3 _
             Or fmt = xlClipboardFormatBIFF4 _
             ) Then
            IsClipboardContentInExcelFormat = True
            Exit Function
        End If
    Next

    Exit Function

ErrorHandling:
    If Err <> 0 Then MsgBox "Cannot Read Data in Clipboard"

End Function
</code>```

Body:
I am trying to copy formatted cells from existing excel sheet  to new sheet in vb.net(2010)  using pastespecial method but it is pasting the cell values as picture rather than text.
Any help in this regard would be highly appreciated:

    Public Sub set_header(ByVal r As Integer, ByVal c As Integer, ByVal dt1 As Date, ByVal dt2 As Date, ByVal sheetname As String)

    Dim wbCopy As Excel.Workbook
    Dim wsCopy As Excel.Worksheet
    Dim rngCopy As Excel.Range
    Dim wbPaste As Excel.Workbook
    Dim wsPaste As Excel.Worksheet
    Dim rngPaste As Excel.Range
    Dim xlsApp As Excel.Application
    xlsApp = New Excel.Application
    wbCopy = xlsApp.Workbooks.Open("C:\Windows\rta2.xlsx")
    wsCopy = wbCopy.Worksheets(sheetname)
    rngCopy = wsCopy.Range("A7:O9")
    Dim addr As Object
    addr = ExcelSheet.Cells(r, c).Address(False, False)
    rngPaste = ExcelSheet.Range(addr)
    rngCopy.Copy()
    rngPaste.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,false,false)
    ExcelSheet.Cells(r + 2, c + 4) = "from " & dt1 & " to " & dt2
    Set wbCopy = Nothing
    Set wsCopy = Nothing
    Set rngCopy = Nothing
    Set wbPaste = Nothing
    Set wsPaste = Nothing
    Set rngPaste = Nothing
    ExcelApp.Quit
   End sub

Thanks

Body:
I have the same problem.
I first check to see if content of clipboard is in excel format.
If yes, I will use Excel's PasteSpecial as Value
If no, I will paste value from clipboard with MSForms.DataObject

below is my code, you can see if it solve the issue:

' Code Block to prevent pasting Images with PasteSpecial
If IsClipboardContentInExcelFormat Then
    Selection.PasteSpecial Paste:=xlValues
Else
    Selection.Value = GetClipBoardText
End If

Function GetClipBoardText()
   ' src: http://stackoverflow.com/questions/9022245/get-text-from-clipboard-using-gettext-avoid-error-on-empty-clipboard
   Dim DataObj As MSForms.DataObject
   Set DataObj = New MSForms.DataObject '<~~ Amended as per jp's suggestion
   Dim myString As String

   On Error GoTo ErrorHandling

   DataObj.GetFromClipboard '~~> Get data from the clipboard.
   myString = DataObj.GetText(1)
   GetClipBoardText = myString

   Exit Function
ErrorHandling:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Function

' Will use MSForms.DataObject for geting clipboard content
' reference: http://stackoverflow.com/questions/9022245/get-text-from-clipboard-using-gettext-avoid-error-on-empty-clipboard
' reference: http://msdn.microsoft.com/en-us/library/office/ff839748%28v=office.14%29.aspx
Private Function IsClipboardContentInExcelFormat() As Boolean
    IsClipboardContentInExcelFormat = False

    On Error GoTo ErrorHandling

    Dim aFmts, fmt
    aFmts = Application.ClipboardFormats

    For Each fmt In aFmts

        If (fmt = xlClipboardFormatBIFF _
             Or fmt = xlClipboardFormatBIFF12 _
             Or fmt = xlClipboardFormatBIFF2 _
             Or fmt = xlClipboardFormatBIFF3 _
             Or fmt = xlClipboardFormatBIFF4 _
             ) Then
            IsClipboardContentInExcelFormat = True
            Exit Function
        End If
    Next

    Exit Function

ErrorHandling:
    If Err <> 0 Then MsgBox "Cannot Read Data in Clipboard"

End Function


问:
Give user permissions to htdocs in Ubuntu
I installed xampp with root permission to opt/lampp folder in Ubuntu.but i cant access htdocs folder and unable to start apache server since the lampp folder has only root permission.How can i solve this and are there any proper way to install xampp in Ubuntu</p>

答:
set USER Permission

```<code>sudo chmod 755 -R /opt/lampp/htdocs
</code>```

Proper way to install XAMPP in ubuntu is as below.
open your terminal

Official document

COMMANDS

```<code>1.) mkdir xampp
2.) cd xampp/
3.) wget https://www.apachefriends.org/xampp-files/5.6.20/xampp-linux-x64-5.6.20-0-installer.run
4.) chmod +x xampp-linux-x64-5.6.20-0-installer.run
5.) sudo ./xampp-linux-x64-5.6.20-0-installer.run
</code>```

ACCESS phpMyAdmin

```<code>6.) sudo vim /opt/lampp/etc/extra/httpd-xampp.conf
</code>```

AND COMMENT OUT THE FOLLOWING LINE

```<code>Require local
</code>```

EX.

```<code>#Require local
</code>```

Save and quit the file and restart XAMPP service

```<code>7.) sudo /opt/lampp/lampp restart
</code>```

OVER COME THE SECURITY OPTION

```<code>8.) sudo /opt/lampp/lampp security
</code>```

And follow the instruction

Body:
set USER Permission

sudo chmod 755 -R /opt/lampp/htdocs

Proper way to install XAMPP in ubuntu is as below.
open your terminal

Official document

COMMANDS

1.) mkdir xampp
2.) cd xampp/
3.) wget https://www.apachefriends.org/xampp-files/5.6.20/xampp-linux-x64-5.6.20-0-installer.run
4.) chmod +x xampp-linux-x64-5.6.20-0-installer.run
5.) sudo ./xampp-linux-x64-5.6.20-0-installer.run

ACCESS phpMyAdmin

6.) sudo vim /opt/lampp/etc/extra/httpd-xampp.conf

AND COMMENT OUT THE FOLLOWING LINE

Require local

EX.

#Require local

Save and quit the file and restart XAMPP service

7.) sudo /opt/lampp/lampp restart

OVER COME THE SECURITY OPTION

8.) sudo /opt/lampp/lampp security

And follow the instruction


问:
Group and count over a start and end range
If I have data in the following format:

```<code>[
  {
    _id: 1,
    startDate: ISODate("2017-01-1T00:00:00.000Z"),
    endDate: ISODate("2017-02-25T00:00:00.000Z"),
    type: 'CAR'
  },
  {
    _id: 2,
    startDate: ISODate("2017-02-17T00:00:00.000Z"),
    endDate: ISODate("2017-03-22T00:00:00.000Z"),
    type: 'HGV'
  }
]
</code>```

Is it possible to retrieve data grouped by 'type', but also with a count of the type for each of month in a given date range e.g. between 2017/1/1 to 2017/4/1 would return:

```<code>[
  {
   _id: 'CAR',
   monthCounts: [
     /*January*/
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 1
     },
     /*February*/
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     /*March*/
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 0
     },
   ]
  },
  {
   _id: 'HGV',
   monthCounts: [
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 0
     },
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 1
     },
   ]
  }
]
</code>```

The returned format is not really important, but what I am trying to achieve is in a single query to retrieve a number of counts for the same grouping (one per month).  The input could be simply a start and end date to report from or more likely it could be an array of the date ranges to group by.

答:
The algorithm for this is to basically "iterate" values between the interval of the two values. MongoDB has a couple of ways to deal with this, being what has always been present with mapReduce() and with new features available to the aggregate() method.

I'm going expand on your selection to deliberately show an overlapping month since your examples did not have one. This will result in the "HGV" values appearing in "three" months of output.

{
        "_id" : 1,
        "startDate" : ISODate("2017-01-01T00:00:00Z"),
        "endDate" : ISODate("2017-02-25T00:00:00Z"),
        "type" : "CAR"
}
{
        "_id" : 2,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-03-22T00:00:00Z"),
        "type" : "HGV"
}
{
        "_id" : 3,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-04-22T00:00:00Z"),
        "type" : "HGV"
}
```

<h2>Aggregate - Requires MongoDB 3.4</h2>

<pre class="lang-js prettyprint-override"><code>db.cars.aggregate([
  { "$addFields": {
    "range": {
      "$reduce": {
        "input": { "$map": {
          "input": { "$range": [
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$startDate", new Date(0) ] },
                1000
              ]
            }},
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$endDate", new Date(0) ] },
                1000
              ]
            }},
            60 * 60 * 24
          ]},
          "as": "el",
          "in": {
            "$let": {
              "vars": {
                "date": {
                  "$add": [
                    { "$multiply": [ "$$el", 1000 ] },
                    new Date(0)
                  ]
                },
                "month": {
                }
              },
              "in": {
                "$add": [
                  { "$multiply": [ { "$year": "$$date" }, 100 ] },
                  { "$month": "$$date" }
                ]
              }
            }
          }
        }},
        "initialValue": [],
        "in": {
          "$cond": {
            "if": { "$in": [ "$$this", "$$value" ] },
            "then": "$$value",
            "else": { "$concatArrays": [ "$$value", ["$$this"] ] }
          }
        }
      }
    }
  }},
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": { "$sum": 1 }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])
</code>```

The key to making this work is the $range operator which takes values for a "start" and and "end" as well as an "interval" to apply. The result is an array of values taken from the "start" and incremented until the "end" is reached.

We use this with startDate and endDate to generate the possible dates in between those values. You will note that we need to do some math here since the $range only takes a 32-bit integer, but we can take the milliseconds away from the timestamp values so that is okay.

Because we want "months", the operations applied extract the month and year values from the generated range. We actually generate the range as the "days" in between since "months" are difficult to deal with in math. The subsequent $reduce operation takes only the "distinct months" from the date range.

The result therefore of the first aggregation pipeline stage is a new field in the document which is an "array" of all the distinct months covered between startDate and endDate. This gives an "iterator" for the rest of the operation.

By "iterator" I mean than when we apply $unwind we get a copy of the original document for every distinct month covered in the interval. This then allows the following two $group stages to first apply a grouping to the common key of "month" and "type" in order to "total" the counts via $sum, and next $group makes the key just the "type" and puts the results in an array via $push.

This gives the result on the above data:

{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                }
        ]
}
```

<p>Note that the coverage of "months" is only present where there is actual data. Whilst possible to produce zero values over a range, it requires quite a bit of wrangling to do so and is not very practical. If you want zero values then it is better to add that in post processing in the client once the results have been retrieved.</p>

<p>If you really have your heart set on the zero values, then you should separately query for <code>$min</code> and <code>$max</code> values, and pass these in to "brute force" the pipeline into generating the copies for each supplied possible range value.</p>

<p>So this time the "range" is made externally to all documents, and you then use a <code>$cond</code> statement into the accumulator to see if the current data is within the grouped range produced. Also since the generation is "external", we really don't need the MongoDB 3.4 operator of <code>$range</code>, so this can be applied to earlier versions as well:</p>

<pre class="lang-js prettyprint-override"><code>// Get min and max separately
var ranges = db.cars.aggregate(
 { "$group": {
   "_id": null,
   "startRange": { "$min": "$startDate" },
   "endRange": { "$max": "$endDate" }
 }}
).toArray()[0]

// Make the range array externally from all possible values
var range = [];
for ( var d = new Date(ranges.startRange.valueOf()); d <= ranges.endRange; d.setUTCMonth(d.getUTCMonth()+1)) {
  var v = ( d.getUTCFullYear() * 100 ) + d.getUTCMonth()+1;
  range.push(v);
}

// Run conditional aggregation
db.cars.aggregate([
  { "$addFields": { "range": range } },
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": {
      "$sum": {
        "$cond": {
          "if": {
            "$and": [
              { "$gte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$startDate" }, 100 ] },
                  { "$month": "$startDate" }
                ]}
              ]},
              { "$lte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$endDate" }, 100 ] },
                  { "$month": "$endDate" }
                ]}
              ]}
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])
</code>```

Which produces the consistent zero fills for all possible months on all groupings:

{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 0
                },
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                },
                {
                        "month" : 201703,
                        "count" : 0
                },
                {
                        "month" : 201704,
                        "count" : 0
                }
        ]
}
```

<h2>MapReduce</h2>

<p>All versions of MongoDB support mapReduce, and the simple case of the "iterator" as mentioned above is handled by a <code>for</code> loop in the mapper. We can get output as generated up to the first <code>$group</code> from above by simply doing:</p>

<pre class="lang-js prettyprint-override"><code>db.cars.mapReduce(
  function () {
    for ( var d = this.startDate; d <= this.endDate;
      d.setUTCMonth(d.getUTCMonth()+1) )
    {
      var m = new Date(0);
      m.setUTCFullYear(d.getUTCFullYear());
      m.setUTCMonth(d.getUTCMonth());
      emit({ id: this.type, date: m},1);
    }
  },
  function(key,values) {
    return Array.sum(values);
  },
  { "out": { "inline": 1 } }
)
</code>```

Which produces:

{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-01-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-03-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-04-01T00:00:00Z")
        },
        "value" : 1
}
```

So it does not have the second grouping to compound to arrays, but we did produce the same basic aggregated output.

Body:
If I have data in the following format:

[
  {
    _id: 1,
    startDate: ISODate("2017-01-1T00:00:00.000Z"),
    endDate: ISODate("2017-02-25T00:00:00.000Z"),
    type: 'CAR'
  },
  {
    _id: 2,
    startDate: ISODate("2017-02-17T00:00:00.000Z"),
    endDate: ISODate("2017-03-22T00:00:00.000Z"),
    type: 'HGV'
  }
]

Is it possible to retrieve data grouped by 'type', but also with a count of the type for each of month in a given date range e.g. between 2017/1/1 to 2017/4/1 would return:

[
  {
   _id: 'CAR',
   monthCounts: [
     /*January*/
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 1
     },
     /*February*/
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     /*March*/
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 0
     },
   ]
  },
  {
   _id: 'HGV',
   monthCounts: [
     {
       from: ISODate("2017-01-1T00:00:00.000Z"),
       to: ISODate("2017-01-31T23:59:59.999Z"),
       count: 0
     },
     {
       from: ISODate("2017-02-1T00:00:00.000Z"),
       to: ISODate("2017-02-28T23:59:59.999Z"),
       count: 1
     },
     {
       from: ISODate("2017-03-1T00:00:00.000Z"),
       to: ISODate("2017-03-31T23:59:59.999Z"),
       count: 1
     },
   ]
  }
]

The returned format is not really important, but what I am trying to achieve is in a single query to retrieve a number of counts for the same grouping (one per month).  The input could be simply a start and end date to report from or more likely it could be an array of the date ranges to group by.

Body:
The algorithm for this is to basically "iterate" values between the interval of the two values. MongoDB has a couple of ways to deal with this, being what has always been present with mapReduce() and with new features available to the aggregate() method.

I'm going expand on your selection to deliberately show an overlapping month since your examples did not have one. This will result in the "HGV" values appearing in "three" months of output.

{
        "_id" : 1,
        "startDate" : ISODate("2017-01-01T00:00:00Z"),
        "endDate" : ISODate("2017-02-25T00:00:00Z"),
        "type" : "CAR"
}
{
        "_id" : 2,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-03-22T00:00:00Z"),
        "type" : "HGV"
}
{
        "_id" : 3,
        "startDate" : ISODate("2017-02-17T00:00:00Z"),
        "endDate" : ISODate("2017-04-22T00:00:00Z"),
        "type" : "HGV"
}

Aggregate - Requires MongoDB 3.4

db.cars.aggregate([
  { "$addFields": {
    "range": {
      "$reduce": {
        "input": { "$map": {
          "input": { "$range": [
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$startDate", new Date(0) ] },
                1000
              ]
            }},
            { "$trunc": {
              "$divide": [
                { "$subtract": [ "$endDate", new Date(0) ] },
                1000
              ]
            }},
            60 * 60 * 24
          ]},
          "as": "el",
          "in": {
            "$let": {
              "vars": {
                "date": {
                  "$add": [
                    { "$multiply": [ "$$el", 1000 ] },
                    new Date(0)
                  ]
                },
                "month": {
                }
              },
              "in": {
                "$add": [
                  { "$multiply": [ { "$year": "$$date" }, 100 ] },
                  { "$month": "$$date" }
                ]
              }
            }
          }
        }},
        "initialValue": [],
        "in": {
          "$cond": {
            "if": { "$in": [ "$$this", "$$value" ] },
            "then": "$$value",
            "else": { "$concatArrays": [ "$$value", ["$$this"] ] }
          }
        }
      }
    }
  }},
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": { "$sum": 1 }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])

The key to making this work is the $range operator which takes values for a "start" and and "end" as well as an "interval" to apply. The result is an array of values taken from the "start" and incremented until the "end" is reached.

We use this with startDate and endDate to generate the possible dates in between those values. You will note that we need to do some math here since the $range only takes a 32-bit integer, but we can take the milliseconds away from the timestamp values so that is okay.

Because we want "months", the operations applied extract the month and year values from the generated range. We actually generate the range as the "days" in between since "months" are difficult to deal with in math. The subsequent $reduce operation takes only the "distinct months" from the date range.

The result therefore of the first aggregation pipeline stage is a new field in the document which is an "array" of all the distinct months covered between startDate and endDate. This gives an "iterator" for the rest of the operation.

By "iterator" I mean than when we apply $unwind we get a copy of the original document for every distinct month covered in the interval. This then allows the following two $group stages to first apply a grouping to the common key of "month" and "type" in order to "total" the counts via $sum, and next $group makes the key just the "type" and puts the results in an array via $push.

This gives the result on the above data:

{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                }
        ]
}

Note that the coverage of "months" is only present where there is actual data. Whilst possible to produce zero values over a range, it requires quite a bit of wrangling to do so and is not very practical. If you want zero values then it is better to add that in post processing in the client once the results have been retrieved.

If you really have your heart set on the zero values, then you should separately query for $min and $max values, and pass these in to "brute force" the pipeline into generating the copies for each supplied possible range value.

So this time the "range" is made externally to all documents, and you then use a $cond statement into the accumulator to see if the current data is within the grouped range produced. Also since the generation is "external", we really don't need the MongoDB 3.4 operator of $range, so this can be applied to earlier versions as well:

// Get min and max separately
var ranges = db.cars.aggregate(
 { "$group": {
   "_id": null,
   "startRange": { "$min": "$startDate" },
   "endRange": { "$max": "$endDate" }
 }}
).toArray()[0]

// Make the range array externally from all possible values
var range = [];
for ( var d = new Date(ranges.startRange.valueOf()); d <= ranges.endRange; d.setUTCMonth(d.getUTCMonth()+1)) {
  var v = ( d.getUTCFullYear() * 100 ) + d.getUTCMonth()+1;
  range.push(v);
}

// Run conditional aggregation
db.cars.aggregate([
  { "$addFields": { "range": range } },
  { "$unwind": "$range" },
  { "$group": {
    "_id": {
      "type": "$type",
      "month": "$range"
    },
    "count": {
      "$sum": {
        "$cond": {
          "if": {
            "$and": [
              { "$gte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$startDate" }, 100 ] },
                  { "$month": "$startDate" }
                ]}
              ]},
              { "$lte": [
                "$range",
                { "$add": [
                  { "$multiply": [ { "$year": "$endDate" }, 100 ] },
                  { "$month": "$endDate" }
                ]}
              ]}
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  }},
  { "$sort": { "_id": 1 } },
  { "$group": {
    "_id": "$_id.type",
    "monthCounts": {
      "$push": { "month": "$_id.month", "count": "$count" }
    }
  }}
])

Which produces the consistent zero fills for all possible months on all groupings:

{
        "_id" : "HGV",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 0
                },
                {
                        "month" : 201702,
                        "count" : 2
                },
                {
                        "month" : 201703,
                        "count" : 2
                },
                {
                        "month" : 201704,
                        "count" : 1
                }
        ]
}
{
        "_id" : "CAR",
        "monthCounts" : [
                {
                        "month" : 201701,
                        "count" : 1
                },
                {
                        "month" : 201702,
                        "count" : 1
                },
                {
                        "month" : 201703,
                        "count" : 0
                },
                {
                        "month" : 201704,
                        "count" : 0
                }
        ]
}

MapReduce

All versions of MongoDB support mapReduce, and the simple case of the "iterator" as mentioned above is handled by a for loop in the mapper. We can get output as generated up to the first $group from above by simply doing:

db.cars.mapReduce(
  function () {
    for ( var d = this.startDate; d <= this.endDate;
      d.setUTCMonth(d.getUTCMonth()+1) )
    {
      var m = new Date(0);
      m.setUTCFullYear(d.getUTCFullYear());
      m.setUTCMonth(d.getUTCMonth());
      emit({ id: this.type, date: m},1);
    }
  },
  function(key,values) {
    return Array.sum(values);
  },
  { "out": { "inline": 1 } }
)

Which produces:

{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-01-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "CAR",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 1
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-02-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-03-01T00:00:00Z")
        },
        "value" : 2
},
{
        "_id" : {
                "id" : "HGV",
                "date" : ISODate("2017-04-01T00:00:00Z")
        },
        "value" : 1
}

So it does not have the second grouping to compound to arrays, but we did produce the same basic aggregated output.


问:
Using relative path for templateUrl in Component with SystemJS
I'm trying to use relative path when defining templateUrl in angular2 component, as described here:
http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/

```<code>@Component({
    selector: 'login-app',
    moduleId: module.id,
    templateUrl: './app.html'
})
</code>```

although I keep getting:

ERROR: module is not defined

I am using --m commonjs in TypeScripy compile settings.

How to make it work?

答:
With systemjs, first declare the string __moduleName (two underscores) and then use it instead of module.id as follows:</p>

```<code>declare var __moduleName: string;

@Component({
    selector: 'login-app',
    moduleId: __moduleName,
    templateUrl: './app.html'
})
</code>```

Body:
I'm trying to use relative path when defining templateUrl in angular2 component, as described here:
http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/

@Component({
    selector: 'login-app',
    moduleId: module.id,
    templateUrl: './app.html'
})

although I keep getting:

ERROR: module is not defined

I am using --m commonjs in TypeScripy compile settings.

How to make it work?

Body:
With systemjs, first declare the string __moduleName (two underscores) and then use it instead of module.id as follows:

declare var __moduleName: string;

@Component({
    selector: 'login-app',
    moduleId: __moduleName,
    templateUrl: './app.html'
})


问:
Socket.io > calling client-side functions from server?
I am trying to execute functions on the client side from a node server using socket.io. The data is getting to the client side no problem but I am not able to execute functions on connect.

My server code (emit in a loop):

```<code>var io = require('socket.io')(server);
io.on('connection', function(client){
    setInterval(function(){
        client.emit('for_client', datatosend);
    }, 100);
});
</code>```

My client side code:

```<code>socket.on('for_client', function (data) {

    console.log(data);

    switch(true) {
        case (data == "reload"):
            console.log('DO reload');  //<<< not working
            break;

        case (data == "switch"):
            console.log('DO switch');  //<<< not working
            break;

        default:
            console.log(data);  //<<< this DOES work
    }

});
</code>```

And here is proof the data is coming through ;)

Any help is super appreciated.

答:
Your switch statement is what's mucking it up.  You should have</p>

```<code>switch(data) {
    case "reload":
        console.log('DO reload');
        break;

    case "switch":
        console.log('DO switch');
        break;

    default:
        console.log(data);
}
</code>```

Body:
I am trying to execute functions on the client side from a node server using socket.io. The data is getting to the client side no problem but I am not able to execute functions on connect.

My server code (emit in a loop):

var io = require('socket.io')(server);
io.on('connection', function(client){
    setInterval(function(){
        client.emit('for_client', datatosend);
    }, 100);
});

My client side code:

socket.on('for_client', function (data) {

    console.log(data);

    switch(true) {
        case (data == "reload"):
            console.log('DO reload');  //<<< not working
            break;

        case (data == "switch"):
            console.log('DO switch');  //<<< not working
            break;

        default:
            console.log(data);  //<<< this DOES work
    }

});

And here is proof the data is coming through ;)

Any help is super appreciated.

Body:
Your switch statement is what's mucking it up.  You should have

switch(data) {
    case "reload":
        console.log('DO reload');
        break;

    case "switch":
        console.log('DO switch');
        break;

    default:
        console.log(data);
}


问:
How to store a 128 bit number in a single column in MySQL?
I'm changing some tables to store IP addresses as numbers rather than strings.  This is simple with IPv4 where the 32 bit address can fit into an integer column.  However, an IPv6 address is 128 bits.

The MySQL documentation only shows numeric types up to 64 bits ("bigint").

Should I stick with char/varchar for IPv6? (Ideally I'd like to use the same column for IPv4 and IPv6, so I'd prefer not to do this).

Is there anything better than using two bigint columns?  I would prefer not to have to break the value into upper and lower /64 whenever using the address.

I'm using MariaDB 5.1 - if there's a better solution in a later version of MySQL then that would be nice to know, although not helpfully immediately.

[EDIT] Note that I'm after a recommendation for the best way to do this - it's obvious that there are various ways of doing this (including the existing string representation), but which is (in terms of performance) best?  (i.e. if someone has done the analysis already, that would save me doing it, or if I'm missing something obvious, that would be great to know too).

答:
To quote: "Have you considered binary (64)"

Storing very large integers in MySQL


问:
Delete image after upload new one
I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:

```<code>//Save logo
         if ($request->hasFile('logo')) {
           $avatar = $request->file('logo');
           $filename = time() . '.' . $avatar->getClientOriginalExtension();
           $location = public_path('avatars/logos/');
           $request->file('logo')->move($location, $filename);
           $oldFilename = $general_Settings->logo;

           $general_Settings->logo = $filename;
           Storage::delete($oldFilename);
         }

         $general_Settings->save();
</code>```

for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.

what do you think is issue of that?

答:
Since, You have stored logo file name only not full path of file,

You need to give full path from public folder to delete image. Change delete line as:

```<code>if ($request->hasFile('logo')) {
       $avatar = $request->file('logo');
       $filename = time() . '.' . $avatar->getClientOriginalExtension();
       $location = public_path('avatars/logos/');
       $request->file('logo')->move($location, $filename);

       $oldFilename = $general_Settings->logo;
       $file_path = "avatars/logos/".$oldFilename;

       $general_Settings->logo = $filename;
       Storage::delete($file_path);
     }

     $general_Settings->save();
</code>```

This might work.

Title: Delete image after upload new one

Body:
I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:

//Save logo
         if ($request->hasFile('logo')) {
           $avatar = $request->file('logo');
           $filename = time() . '.' . $avatar->getClientOriginalExtension();
           $location = public_path('avatars/logos/');
           $request->file('logo')->move($location, $filename);
           $oldFilename = $general_Settings->logo;

           $general_Settings->logo = $filename;
           Storage::delete($oldFilename);
         }

         $general_Settings->save();

for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.

what do you think is issue of that?

Body:
Since, You have stored logo file name only not full path of file,

You need to give full path from public folder to delete image. Change delete line as:

if ($request->hasFile('logo')) {
       $avatar = $request->file('logo');
       $filename = time() . '.' . $avatar->getClientOriginalExtension();
       $location = public_path('avatars/logos/');
       $request->file('logo')->move($location, $filename);

       $oldFilename = $general_Settings->logo;
       $file_path = "avatars/logos/".$oldFilename;

       $general_Settings->logo = $filename;
       Storage::delete($file_path);
     }

     $general_Settings->save();

This might work.


问:
Transactions with Python sqlite3
I'm trying to port some code to Python that uses sqlite databases, and I'm trying to get transactions to work, and I'm getting really confused. I'm really confused by this; I've used sqlite a lot in other languages, because it's great, but I simply cannot work out what's wrong here.

Here is the schema for my test database (to be fed into the sqlite3 command line tool).

```<code>BEGIN TRANSACTION;
CREATE TABLE test (i integer);
INSERT INTO "test" VALUES(99);
COMMIT;
</code>```

Here is a test program.

```<code>import sqlite3

sql = sqlite3.connect("test.db")
with sql:
    c = sql.cursor()
    c.executescript("""
        update test set i = 1;
        fnord;
        update test set i = 0;
        """)
</code>```

You may notice the deliberate mistake in it. This causes the SQL script to fail on the second line, after the update has been executed.

According to the docs, the with sql statement is supposed to set up an implicit transaction around the contents, which is only committed if the block succeeds. However, when I run it, I get the expected SQL error... but the value of i is set from 99 to 1. I'm expecting it to remain at 99, because that first update should be rolled back.

Here is another test program, which explicitly calls commit() and rollback().

```<code>import sqlite3

sql = sqlite3.connect("test.db")
try:
    c = sql.cursor()
    c.executescript("""
        update test set i = 1;
        fnord;
        update test set i = 0;
    """)
    sql.commit()
except sql.Error:
    print("failed!")
    sql.rollback()
</code>```

This behaves in precisely the same way --- i gets changed from 99 to 1.

Now I'm calling BEGIN and COMMIT explicitly:

```<code>import sqlite3

sql = sqlite3.connect("test.db")
try:
    c = sql.cursor()
    c.execute("begin")
    c.executescript("""
            update test set i = 1;
            fnord;
            update test set i = 0;
    """)
    c.execute("commit")
except sql.Error:
    print("failed!")
    c.execute("rollback")
</code>```

This fails too, but in a different way. I get this:

```<code>sqlite3.OperationalError: cannot rollback - no transaction is active
</code>```

However, if I replace the calls to c.execute() to c.executescript(), then it works (i remains at 99)!

(I should also add that if I put the begin and commit inside the inner call to executescript then it behaves correctly in all cases, but unfortunately I can't use that approach in my application. In addition, changing sql.isolation_level appears to make no difference to the behaviour.)

Can someone explain to me what's happening here? I need to understand this; if I can't trust the transactions in the database, I can't make my application work...

Python 2.7, python-sqlite3 2.6.0, sqlite3 3.7.13, Debian.

答:
Here's what I think is happening based on my reading of Python's sqlite3 bindings as well as official Sqlite3 docs.  The short answer is that if you want a proper transaction, you should stick to this idiom:

```<code>with connection:
    db.execute("BEGIN")
    # do other things, but do NOT use 'executescript'
</code>```

Contrary to my intuition, with connection does not call BEGIN upon entering the scope.  In fact it doesn't do anything at all in __enter__.  It only has an effect when you __exit__ the scope, choosing either COMMIT or ROLLBACK depending on whether the scope is exiting normally or with an exception.

Therefore, the right thing to do is to always explicitly mark the beginning of your transactional with connection blocks using BEGIN.  This renders isolation_level irrelevant within the block, because thankfully it only has an effect while autocommit mode is enabled, and autocommit mode is always suppressed within transaction blocks.

Another quirk is executescript, which always issues a COMMIT before running your script.  This can easily mess up the transactional with connection block, so your choice is to either

use exactly one executescript within the with block and nothing else, or

avoid executescript entirely; you can call execute as many times as you want, subject to the one-statement-per-execute limitation.

Title: Transactions with Python sqlite3

Body:
I'm trying to port some code to Python that uses sqlite databases, and I'm trying to get transactions to work, and I'm getting really confused. I'm really confused by this; I've used sqlite a lot in other languages, because it's great, but I simply cannot work out what's wrong here.

Here is the schema for my test database (to be fed into the sqlite3 command line tool).

BEGIN TRANSACTION;
CREATE TABLE test (i integer);
INSERT INTO "test" VALUES(99);
COMMIT;

Here is a test program.

import sqlite3

sql = sqlite3.connect("test.db")
with sql:
    c = sql.cursor()
    c.executescript("""
        update test set i = 1;
        fnord;
        update test set i = 0;
        """)

You may notice the deliberate mistake in it. This causes the SQL script to fail on the second line, after the update has been executed.

According to the docs, the with sql statement is supposed to set up an implicit transaction around the contents, which is only committed if the block succeeds. However, when I run it, I get the expected SQL error... but the value of i is set from 99 to 1. I'm expecting it to remain at 99, because that first update should be rolled back.

Here is another test program, which explicitly calls commit() and rollback().

import sqlite3

sql = sqlite3.connect("test.db")
try:
    c = sql.cursor()
    c.executescript("""
        update test set i = 1;
        fnord;
        update test set i = 0;
    """)
    sql.commit()
except sql.Error:
    print("failed!")
    sql.rollback()

This behaves in precisely the same way --- i gets changed from 99 to 1.

Now I'm calling BEGIN and COMMIT explicitly:

import sqlite3

sql = sqlite3.connect("test.db")
try:
    c = sql.cursor()
    c.execute("begin")
    c.executescript("""
            update test set i = 1;
            fnord;
            update test set i = 0;
    """)
    c.execute("commit")
except sql.Error:
    print("failed!")
    c.execute("rollback")

This fails too, but in a different way. I get this:

sqlite3.OperationalError: cannot rollback - no transaction is active

However, if I replace the calls to c.execute() to c.executescript(), then it works (i remains at 99)!

(I should also add that if I put the begin and commit inside the inner call to executescript then it behaves correctly in all cases, but unfortunately I can't use that approach in my application. In addition, changing sql.isolation_level appears to make no difference to the behaviour.)

Can someone explain to me what's happening here? I need to understand this; if I can't trust the transactions in the database, I can't make my application work...

Python 2.7, python-sqlite3 2.6.0, sqlite3 3.7.13, Debian.

Body:
Here's what I think is happening based on my reading of Python's sqlite3 bindings as well as official Sqlite3 docs.  The short answer is that if you want a proper transaction, you should stick to this idiom:

with connection:
    db.execute("BEGIN")
    # do other things, but do NOT use 'executescript'

Contrary to my intuition, with connection does not call BEGIN upon entering the scope.  In fact it doesn't do anything at all in __enter__.  It only has an effect when you __exit__ the scope, choosing either COMMIT or ROLLBACK depending on whether the scope is exiting normally or with an exception.

Therefore, the right thing to do is to always explicitly mark the beginning of your transactional with connection blocks using BEGIN.  This renders isolation_level irrelevant within the block, because thankfully it only has an effect while autocommit mode is enabled, and autocommit mode is always suppressed within transaction blocks.

Another quirk is executescript, which always issues a COMMIT before running your script.  This can easily mess up the transactional with connection block, so your choice is to either

use exactly one executescript within the with block and nothing else, or

avoid executescript entirely; you can call execute as many times as you want, subject to the one-statement-per-execute limitation.


答:
Just get all the matches using your current regex, then just add an If statement as followings:

```<code>    String test="e.this is test";
if(!test.startsWith("e."){
    //Do someting
  }
</code>```

Title: Regex to match [any char][any digit]dot with an exception case

Body:
I have a regex [a-zA-Z0-9]\\.(.*) to match:
[any character, any digit] followed by a dot and then followed by anything. For example e1.abc, r11.xyz, etc.

This works fine. However I have a case where if string is e.abc then it should not match i.e. only if it is e. then it should not match.

How do I modify my regex to handle this specific exclusion?

Body:
Just get all the matches using your current regex, then just add an If statement as followings:

    String test="e.this is test";
if(!test.startsWith("e."){
    //Do someting
  }


问:
AVPlayer can't load .mov file saved after re-running app via xcode
I have this app in which the main purpose is to record video using AVFoundation, and then saving the outputfile delegate.

On first any normal run the app could properly record and save the video, and I could load the resulting outputfile URL into Avplayer I have on the next viewcontroller.

The AVPlayer would play just fine normally if the Xcode is not re-run. What I mean with rerunning is tapping into the Command+R again or clicking on the Play button on xcode to rebuild re-run.

What happens when I run the app again is that I could still see the files and list them via print, but when I'm trying to access the recorded file the app would no longer play the video. It would seem that the video wasn't loaded properly or anything even if it had already been working earlier. After this happens I could still go on record new ones and play the newly recorded ones, but not the old files.

The old files before rebuild of app would just look like this on AVPlayer

Also the AVPlayer would successfully return .readyToPlay status on my observer.

I'm confused how should I go on fixing this one.

```<code>if let videoPreviewController = storyBoard.instantiateViewController(withIdentifier: "VideoPreviewController") as? VideoPreviewController {

                    let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")
                    videoPreviewController.player = AVPlayer()
                    let playerItem = AVPlayerItem.init(url: url as URL)
                    videoPreviewController.player?.replaceCurrentItem(with: playerItem)

                    videoPreviewController.report = relationship
                    videoPreviewController.appointment = self.appointment
                    navigation.pushViewController(videoPreviewController, animated: true)
                }
</code>```

答:
Your problem is this line:

```<code>  let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")
</code>```

That path will change every time your restart your app -- you can't hard code it.  You have to ask the OS for the path to your documents folder and append your filename to it.

```<code>let userDocumentsURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileName = "Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov"

let movieURL = userDocumentsURL.appendingPathComponent(fileName)
</code>```

And by the way, that's probably how you saved the file in the first place... get the path, append your filename and save it.

Body:
I have this app in which the main purpose is to record video using AVFoundation, and then saving the outputfile delegate.

On first any normal run the app could properly record and save the video, and I could load the resulting outputfile URL into Avplayer I have on the next viewcontroller.

The AVPlayer would play just fine normally if the Xcode is not re-run. What I mean with rerunning is tapping into the Command+R again or clicking on the Play button on xcode to rebuild re-run.

What happens when I run the app again is that I could still see the files and list them via print, but when I'm trying to access the recorded file the app would no longer play the video. It would seem that the video wasn't loaded properly or anything even if it had already been working earlier. After this happens I could still go on record new ones and play the newly recorded ones, but not the old files.

The old files before rebuild of app would just look like this on AVPlayer

Also the AVPlayer would successfully return .readyToPlay status on my observer.

I'm confused how should I go on fixing this one.

if let videoPreviewController = storyBoard.instantiateViewController(withIdentifier: "VideoPreviewController") as? VideoPreviewController {

                    let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")
                    videoPreviewController.player = AVPlayer()
                    let playerItem = AVPlayerItem.init(url: url as URL)
                    videoPreviewController.player?.replaceCurrentItem(with: playerItem)

                    videoPreviewController.report = relationship
                    videoPreviewController.appointment = self.appointment
                    navigation.pushViewController(videoPreviewController, animated: true)
                }

Body:
Your problem is this line:

  let url = NSURL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/61E182ED-D490-4C7D-BAB7-C90D095C7E43/Documents/Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov")

That path will change every time your restart your app -- you can't hard code it.  You have to ask the OS for the path to your documents folder and append your filename to it.

let userDocumentsURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileName = "Thursday,%208%20June%202017%20at%201:47:51%20PM%20Philippine%20Standard%20Time.mov"

let movieURL = userDocumentsURL.appendingPathComponent(fileName)

And by the way, that's probably how you saved the file in the first place... get the path, append your filename and save it.


问:
Advancing numeric string in localstorage
Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.

Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".

```<code>function saveTask() {
        var task = $("#task").val();
        var taskDate = $("#taskDate").val();
        if (newUser == null) {
            var taskNumber = 0;
            localStorage.setItem("taskTracker", "0");
            localStorage.setItem("newUser", "no");
        }
        else {
            var taskNumber = localStorage.getItem("taskTracker");
        }
        var advanceTask = taskNumber + 1;
        localStorage.setItem('task' + taskNumber, task);
        localStorage.setItem('task' + taskNumber + 'date', taskDate);
        localStorage.setItem("taskTracker", advanceTask);
        console.log(advanceTask);
        displayTasks();
}
</code>```

If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.

Thoughts? <3

答:
There is a difference between string + number and number + number. Your current solution is like the stringPlusOne function below. You need to convert the string to a number (using parseInt is one way) and then do the math, like the stringPlusOne2 function below

function stringPlusOne(str) {
  console.log(str + 1);
}

function stringPlusOne2(str) {
  console.log(parseInt(str, 10) + 1);
}

stringPlusOne("2");
stringPlusOne2("2");```

Body:
Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.

Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".

function saveTask() {
        var task = $("#task").val();
        var taskDate = $("#taskDate").val();
        if (newUser == null) {
            var taskNumber = 0;
            localStorage.setItem("taskTracker", "0");
            localStorage.setItem("newUser", "no");
        }
        else {
            var taskNumber = localStorage.getItem("taskTracker");
        }
        var advanceTask = taskNumber + 1;
        localStorage.setItem('task' + taskNumber, task);
        localStorage.setItem('task' + taskNumber + 'date', taskDate);
        localStorage.setItem("taskTracker", advanceTask);
        console.log(advanceTask);
        displayTasks();
}

If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.

Thoughts? <3