问:
Keeping a value when i call a function inside a function?
Given a list, i'm trying to get a random change of two elements. I defined a function dosopt() that does that. Then, I call this function from another function named test(). So in this function "test" i tried to copy the initial argument in the variable x. Then I want to apply de function dosopt() on the variable "v", so it generates the same list "x" but with the interchange of two elements. The thing is that when I do that, the value of x also changes.
I'm not very good at programming so a little bit of help would be nice

```<code>from random import randint
import copy as c

def test(other):
    x=other[:]
    v=dosopt(x)
    return x,v

def dosopt(solution):
    change=[]
    x=0
    while x!=1:
        i=randint(0,len(solution[0])-2)
        j=randint(0,len(solution[0])-2)
        if i!=j and i!=j+1 and j!=i+1:
            x=1
    if i<j:
        a=solution[0][i]
        b=solution[0][i+1]
        c=solution[0][j]
        d=solution[0][j+1]
        pos=[0,j,b,c]
        change.append(pos[:])
        solution[0][i+1]=change[0][3]
        solution[0][change[0][1]]=change[0][2]
    elif i>j:
        a=solution[0][j]
        b=solution[0][j+1]
        c=solution[0][i]
        d=solution[0][i+1]
        pos=[0,i,b,c]
        change.append(pos[:])
        solution[0][j+1]=change[0][3]
        solution[0][change[0][1]]=change[0][2]
    return(solution)

lis=[[0,1,2,3,4,5,6,7,0]]
</code>```

As I can tell, the problem is on the function dosopt because i don't have this problem with other function.

Please ignore the meaningless lines of code, they come from a previous code.

答:
This is because lists are copied by reference instead of copied by value.

Easiest way to get around this is to use the copy module.

```<code>import copy

my_list  = ["a", "b", "c"]
same_list = my_list
new_list = copy.deepcopy(my_list)

same_list[0] = "test"
my_list[1] = "something"
new_list[0] = "hello"

print(my_list)
print(same_list)
print(new_list)
</code>```

results in

```<code>['test', 'something', 'c']
['test', 'something', 'c']
['hello', 'b', 'c']
</code>```

So in your case if you want to copy x and save it you should use v = dosopt(copy.deepcopy(x)). You should be aware though that this could potentially be very slow depending on how big x is.

Also you are shadowing your import of copy as c when you use the variable c later. You should avoid doing this. Plus, copy isn't a long or complicated name so you shouldn't be aliasing it. Aliasing is typically reserved for when things are tedious to type or take up a ton of room on screen such as import matplotlib.pyplot as plt.

Body:
Given a list, i'm trying to get a random change of two elements. I defined a function dosopt() that does that. Then, I call this function from another function named test(). So in this function "test" i tried to copy the initial argument in the variable x. Then I want to apply de function dosopt() on the variable "v", so it generates the same list "x" but with the interchange of two elements. The thing is that when I do that, the value of x also changes.
I'm not very good at programming so a little bit of help would be nice

from random import randint
import copy as c

def test(other):
    x=other[:]
    v=dosopt(x)
    return x,v

def dosopt(solution):
    change=[]
    x=0
    while x!=1:
        i=randint(0,len(solution[0])-2)
        j=randint(0,len(solution[0])-2)
        if i!=j and i!=j+1 and j!=i+1:
            x=1
    if i<j:
        a=solution[0][i]
        b=solution[0][i+1]
        c=solution[0][j]
        d=solution[0][j+1]
        pos=[0,j,b,c]
        change.append(pos[:])
        solution[0][i+1]=change[0][3]
        solution[0][change[0][1]]=change[0][2]
    elif i>j:
        a=solution[0][j]
        b=solution[0][j+1]
        c=solution[0][i]
        d=solution[0][i+1]
        pos=[0,i,b,c]
        change.append(pos[:])
        solution[0][j+1]=change[0][3]
        solution[0][change[0][1]]=change[0][2]
    return(solution)

lis=[[0,1,2,3,4,5,6,7,0]]

As I can tell, the problem is on the function dosopt because i don't have this problem with other function.

Please ignore the meaningless lines of code, they come from a previous code.

Body:
This is because lists are copied by reference instead of copied by value.

Easiest way to get around this is to use the copy module.

import copy

my_list  = ["a", "b", "c"]
same_list = my_list
new_list = copy.deepcopy(my_list)

same_list[0] = "test"
my_list[1] = "something"
new_list[0] = "hello"

print(my_list)
print(same_list)
print(new_list)

results in

['test', 'something', 'c']
['test', 'something', 'c']
['hello', 'b', 'c']

So in your case if you want to copy x and save it you should use v = dosopt(copy.deepcopy(x)). You should be aware though that this could potentially be very slow depending on how big x is.

Also you are shadowing your import of copy as c when you use the variable c later. You should avoid doing this. Plus, copy isn't a long or complicated name so you shouldn't be aliasing it. Aliasing is typically reserved for when things are tedious to type or take up a ton of room on screen such as import matplotlib.pyplot as plt.


来源: stackexchange

问:
Avoid Jquery to hide a message with display:none
hope I can find a way to show two messages when click on a link, I miss a message (Product Added) cause the display:none - it seems there is no way to keep visible the second message :(

This is my code:

```<code><script>
$(document).ready(function() {
$('.shop').click(function(){
$(this).next('.add-button .btn-bottom-linea a').text('Product Added').delay(3000).fadeOut(500);
$(this).text('Add another product').hide().delay(3500).fadeIn(500);
});
});
</script>

<a href="#0" class="shop add-button btn-bottom-line">Add Product</a>
</code>```

答:
The thing here is that you are not waiting  to add the new text.

If you see here you can see that .fadeOut(duration, complete) accepts 2 parameters, the first is the time in miliseconds, the second is the callback that will be called after the animation.

The code should be like this:

```<code>$(document).ready(function() {
    $('.shop').click(function(e){

        var element = $(this);
        element.text('Product Added').delay(3000).fadeOut(500, function () {
            element.text('Add another product').hide().delay(3500).fadeIn(500);
        });
    });

});
</code>```

Check out promises in JS and don't forget to check documentation when using a library of framework.

ContentLicense: CC BY-SA 3.0

Body:
hope I can find a way to show two messages when click on a link, I miss a message (Product Added) cause the display:none - it seems there is no way to keep visible the second message :(

This is my code:

Add Product

Body:
The thing here is that you are not waiting  to add the new text.

If you see here you can see that .fadeOut(duration, complete) accepts 2 parameters, the first is the time in miliseconds, the second is the callback that will be called after the animation.

The code should be like this:

$(document).ready(function() {
    $('.shop').click(function(e){

        var element = $(this);
        element.text('Product Added').delay(3000).fadeOut(500, function () {
            element.text('Add another product').hide().delay(3500).fadeIn(500);
        });
    });

});

Check out promises in JS and don't forget to check documentation when using a library of framework.


问:
jQuery Ajax setTimeout being random
I have the following code that lets me get data from ajax.php and display it in a div. It is supposed to display information for 3 seconds and then hide the #ajax-content and display #welcome-content

However, although most of the time it works and seems to be 3 seconds, occasionally it would randomly be much shorter. A few times it did not even feel like 1 second.

Have I done something wrong? or is there a way to fix this?

```<code>$('#user_id').on('change', function() {
$('#user_id').focus();
id = $("#user_id").val();
$.post("ajax.php", { username:id } ,function(data){
    $("#welcome-content").hide();
    $("#ajax-content").show();
    $("#ajax-content").html(data);
        setTimeout(
           function(){
            $("#ajax-content").hide();
            $("#welcome-content").show();
           },
           3000
        );
});
</code>```

答:
Why do not use a simple way to code this ?

```<code>$('#user_id').on('change', function() {
    $('#user_id').focus();
    id = $("#user_id").val();
    $.post("ajax.php", { username:id } ,function(data){
        $("#welcome-content").hide();
        $("#ajax-content").show();
        $("#ajax-content").html(data);
        setTimeout(HideAjax_ShowWelcome, 3000);
    });
});

function HideAjax_ShowWelcome () {
    $("#ajax-content").hide();
    $("#welcome-content").show();
}
</code>```

The setTimeout statement only asks for the name of the function, it is not a call, do not put parentheses.
If you put in this place a function (a pointer in fact) and its code, the javascript engine must make each time an evaluation of this code [because it is for him just text], which explains the response time random ...

This being the best is to test this version of writing then to tell us if it is better so?

Title: jQuery Ajax setTimeout being random

Body:
I have the following code that lets me get data from ajax.php and display it in a div. It is supposed to display information for 3 seconds and then hide the #ajax-content and display #welcome-content

However, although most of the time it works and seems to be 3 seconds, occasionally it would randomly be much shorter. A few times it did not even feel like 1 second.

Have I done something wrong? or is there a way to fix this?

$('#user_id').on('change', function() {
$('#user_id').focus();
id = $("#user_id").val();
$.post("ajax.php", { username:id } ,function(data){
    $("#welcome-content").hide();
    $("#ajax-content").show();
    $("#ajax-content").html(data);
        setTimeout(
           function(){
            $("#ajax-content").hide();
            $("#welcome-content").show();
           },
           3000
        );
});

Body:
Why do not use a simple way to code this ?

$('#user_id').on('change', function() {
    $('#user_id').focus();
    id = $("#user_id").val();
    $.post("ajax.php", { username:id } ,function(data){
        $("#welcome-content").hide();
        $("#ajax-content").show();
        $("#ajax-content").html(data);
        setTimeout(HideAjax_ShowWelcome, 3000);
    });
});

function HideAjax_ShowWelcome () {
    $("#ajax-content").hide();
    $("#welcome-content").show();
}

The setTimeout statement only asks for the name of the function, it is not a call, do not put parentheses.
If you put in this place a function (a pointer in fact) and its code, the javascript engine must make each time an evaluation of this code [because it is for him just text], which explains the response time random ...

This being the best is to test this version of writing then to tell us if it is better so?


问:
How can I find a link by URL in my functional test?
In the Symfony testing documentation, it shows how to select a link containing specific text:

```<code>$crawler->selectLink('Click here');
</code>```

But the link I'm looking for won't always have the same text. It will say one of a few different things depending on the status of the record, so instead, I need to find it by URL. I think I can figure out how to do it using an xpath filter. Is that what I should go for, or is there a better way?

答:
You would be testing against a known state - and so that state will inform what text should be on the button.

If not - you can also search by a CSS ID, or enough other information to uniquely identify the button, such as a class name of a button within a range specified by an ID, with a CSS Path, or XPath.

```<code>Full CSS Path to the `<code>` block in your question
#question > table > tbody > tr:nth-child(1) > td.postcell > div > div.post-text > pre > code

Xpath
//*[@id="question"]/table/tbody/tr[1]/td[2]/div/div[1]/pre/code
</code>```

A specific ID, or the text to look for would be a lot easier though, and far less likely to break!

Body:
In the Symfony testing documentation, it shows how to select a link containing specific text:

$crawler->selectLink('Click here');

But the link I'm looking for won't always have the same text. It will say one of a few different things depending on the status of the record, so instead, I need to find it by URL. I think I can figure out how to do it using an xpath filter. Is that what I should go for, or is there a better way?

Body:
You would be testing against a known state - and so that state will inform what text should be on the button.

If not - you can also search by a CSS ID, or enough other information to uniquely identify the button, such as a class name of a button within a range specified by an ID, with a CSS Path, or XPath.

Full CSS Path to the `<code>` block in your question
#question > table > tbody > tr:nth-child(1) > td.postcell > div > div.post-text > pre > code

Xpath
//*[@id="question"]/table/tbody/tr[1]/td[2]/div/div[1]/pre/code

A specific ID, or the text to look for would be a lot easier though, and far less likely to break!


问:
R code: finding similar matches with a specified accuracy
I have two tables, and each contains a character variable, for instance in table g1 I have var1 with values such as 'girls leggings', 'leggings', 'leginggs', 'tops', and in g2 I have var2 with values 'girls tops', 'tops', 'leggings', 'long leggings'.
I am trying to compare these character  values  from two tables and based on accuracy match the rows which have  the  highest accuracy match

I thought I can use one to many merge and then just keep the records with the highest match, something like

g$comp<-levenshteinSim(g$var1, g$var2)

for each var1 to all var2 and then pick the row with the highest g$comp.
But since the table is  quite large, the one to many merge can result in really massive data set.
I wonder if there is a way to use the R loop process? Just can't imagine any more elegant and faster way of approaching this.

Any help will be highly appreciated.

Thank you

答:
you may use lapply function together with agrep (approximate grep) which is fuzzy string matching, it's base r; for my needs, this worked better than library(stringi) which you may also explore

```<code>lapply(g$var1, agrep, x=g$var2, max.distance=0.05, value=T)
</code>```

Body:
you may use lapply function together with agrep (approximate grep) which is fuzzy string matching, it's base r; for my needs, this worked better than library(stringi) which you may also explore

lapply(g$var1, agrep, x=g$var2, max.distance=0.05, value=T)


问:
IE7/IE8 z-index not cooperating. Suggestions?
EDIT: Solution found. The pink block had overflow:visible !important, which in Internet Explorer invalidated z-index. After removing it, the logo came to the top.

See: http://bit.ly/i7ER3e

See logo "**" (beside top menu) with Firefox/Chrome, it correctly appears above left-content block (the block with pink background).

In IE7/IE8 the logo, it becomes hidden behind the pink block.

I've been messing with this for 2 hours now. Tried a lot of stuff. Can't get it to appear right in IE7/IE8.

Any suggestions?

(Note: I'm working in a really restrictive framework where I cannot simply float the logo before the menu. I have to use position:absolute to place it.)

答:
try setting position:relative; as well as the z-index.

The default position style is position:static;, and IE has bugs around the z-index handling when combined with static positioning; setting position:relative can solve some of them, without affecting too much else.

See this page for more info. (the link is for CSS3Pie, which is an IE hack to help it support some CSS3 features like border-radius, but the info on the z-index bug is general and likely covers your issue as well)

ContentLicense: CC BY-SA 2.5


问:
Update a progressbar in a thread
I have a Python code where I create a progressbar. The Tkinter environment is created in the Gui function with the progressbar and it is launched as a thread. Then in an other thread I calculate the value that the progressbar must have, but the problem is that I dont know how to update the Gui thread with the new value of the progressbar. Here is my code:

```<code>import tkinter as tk
from tkinter import ttk
import thread

def Gui():
   root = tk.Tk()
   root.geometry('450x450')
   root.title('Hanix Downloader')

   button1 = tk.Button(root, text='Salir', width=25,command=root.destroy)
   button1.pack()

   s = ttk.Style()
   s.theme_use('clam')
   s.configure("green.Horizontal.TProgressbar", foreground='green', background='green')

   mpb = ttk.Progressbar(root,style="green.Horizontal.TProgressbar",orient ="horizontal",length = 200, mode ="determinate")
   mpb.pack()
   mpb["maximum"] = 3620
   mpb["value"] = 1000

   root.mainloop()

def main():
while True:
    #Calculate the new value of the progress bar.
    mpb["value"] = 100 #Does not work
    root.update_idletasks()#Does not work
    #Do some other tasks.

if __name__ == '__main__':
thread.start_new_thread( Gui,() )
thread.start_new_thread( main,() )
</code>```

The error I get is that mpb and root do no exist. Thanks in advance.

答:
You should get error because mpb and root are local variables which exist only in Gui but not in main. You have to use global to inform both functions to use global variables - and then main will have access to mpb created in Gui

I also add time.sleep(1) before while True: because sometimes main may start faster then Gui and it may not find mpb (because Gui had no time to create progressbar)

```<code>import tkinter as tk
from tkinter import ttk
import _thread
import time

def Gui():
   global root, mpb

   root = tk.Tk()

   button1 = tk.Button(root, text='Exit', command=root.destroy)
   button1.pack()

   mpb = ttk.Progressbar(root, mode="determinate")
   mpb.pack()

   mpb["maximum"] = 3000
   mpb["value"] = 1000

   root.mainloop()

def main():
    global root, mpb

    time.sleep(1)

    while True:
        mpb["value"] += 100
        #root.update_idletasks() # works without it

        #Do some other tasks.
        time.sleep(0.2)

if __name__ == '__main__':
    _thread.start_new_thread(Gui, ())
    _thread.start_new_thread(main, ())
</code>```

Tested on Python 3.6.2, Linux Mint 18.2

EDIT: more precisely: you need global only in Gui because it assigns values to variables

root = ..., mpb = ....

Title: Update a progressbar in a thread

Body:
I have a Python code where I create a progressbar. The Tkinter environment is created in the Gui function with the progressbar and it is launched as a thread. Then in an other thread I calculate the value that the progressbar must have, but the problem is that I dont know how to update the Gui thread with the new value of the progressbar. Here is my code:

import tkinter as tk
from tkinter import ttk
import thread

def Gui():
   root = tk.Tk()
   root.geometry('450x450')
   root.title('Hanix Downloader')

   button1 = tk.Button(root, text='Salir', width=25,command=root.destroy)
   button1.pack()

   s = ttk.Style()
   s.theme_use('clam')
   s.configure("green.Horizontal.TProgressbar", foreground='green', background='green')

   mpb = ttk.Progressbar(root,style="green.Horizontal.TProgressbar",orient ="horizontal",length = 200, mode ="determinate")
   mpb.pack()
   mpb["maximum"] = 3620
   mpb["value"] = 1000

   root.mainloop()

def main():
while True:
    #Calculate the new value of the progress bar.
    mpb["value"] = 100 #Does not work
    root.update_idletasks()#Does not work
    #Do some other tasks.

if __name__ == '__main__':
thread.start_new_thread( Gui,() )
thread.start_new_thread( main,() )

The error I get is that mpb and root do no exist. Thanks in advance.

Body:
You should get error because mpb and root are local variables which exist only in Gui but not in main. You have to use global to inform both functions to use global variables - and then main will have access to mpb created in Gui

I also add time.sleep(1) before while True: because sometimes main may start faster then Gui and it may not find mpb (because Gui had no time to create progressbar)

import tkinter as tk
from tkinter import ttk
import _thread
import time

def Gui():
   global root, mpb

   root = tk.Tk()

   button1 = tk.Button(root, text='Exit', command=root.destroy)
   button1.pack()

   mpb = ttk.Progressbar(root, mode="determinate")
   mpb.pack()

   mpb["maximum"] = 3000
   mpb["value"] = 1000

   root.mainloop()

def main():
    global root, mpb

    time.sleep(1)

    while True:
        mpb["value"] += 100
        #root.update_idletasks() # works without it

        #Do some other tasks.
        time.sleep(0.2)

if __name__ == '__main__':
    _thread.start_new_thread(Gui, ())
    _thread.start_new_thread(main, ())

Tested on Python 3.6.2, Linux Mint 18.2

EDIT: more precisely: you need global only in Gui because it assigns values to variables

root = ..., mpb = ....


问:
Change each json object key(fn) value with number multiplied with 2
Hello I want to change each json object key value. JSON -

```<code>abc='[{"fn": 1,"name":"raimonds"},{"fn": 2,"name":"john"}]'
</code>```

Now using some filter in jq -

```<code>res=$(echo "$abc" | jq 'map(if .fn then . + {"fn":22222} else . end)')
</code>```

Now if I'm echoing $res it retuns -

```<code>'[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'
</code>```

I want to multiply each fn by 2 and output it like this -

```<code>abc='[{"fn": 22222,"name":"raimonds"},{"fn": 44444,"name":"john"}]'
</code>```

How can i do that? Thank you!

答:
This filter multiplies the .fn member of each object within an array (or another object) by 2, leaving other members unchanged.

```<code>.[].fn *= 2
</code>```

Try it online at jqplay.org

Body:
Hello I want to change each json object key value. JSON -

abc='[{"fn": 1,"name":"raimonds"},{"fn": 2,"name":"john"}]'

Now using some filter in jq -

res=$(echo "$abc" | jq 'map(if .fn then . + {"fn":22222} else . end)')

Now if I'm echoing $res it retuns -

'[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'

I want to multiply each fn by 2 and output it like this -

abc='[{"fn": 22222,"name":"raimonds"},{"fn": 44444,"name":"john"}]'

How can i do that? Thank you!

Body:
This filter multiplies the .fn member of each object within an array (or another object) by 2, leaving other members unchanged.

.[].fn *= 2

Try it online at jqplay.org


问:
How to resolve issue related to java installing

A jre or jdk must be available in order to run Eclipse. No java virtual machine was found after searching the following locations:

c:\user\ashish\downloads\eclipse\jre\bin\javaw.exe in your current PATH.

答: Perhaps you might have downloaded the wrong file i.e maybe 32 bit for a 64 bit OS (download 64 bit .exe file), try checking that, saves a lot of time.</p>

ContentLicense: CC BY-SA 4.0


问:
Error on sql request on access vba
I've an error on this code:

```<code> Promo_var = Modifiable84.Value
   MsgBox Promo_var

   DoCmd.Hourglass True 'icone tablier a true

   ' set to break on all errors
   Application.SetOption "Error Trapping", 0

   ' start with a clean file built from the template file
   sTemplate = CurrentProject.Path & "\PlanificationAnnuelle_Template.xlsx"
   sOutput = CurrentProject.Path & "\PlanificationAnnuelle.xlsx"
   If Dir(sOutput) <> "" Then Kill sOutput
   FileCopy sTemplate, sOutput

   ' Create the Excel Applicaiton, Workbook and Worksheet and Database object
   Set appExcel = New Excel.Application
   Set wbk = appExcel.Workbooks.Open(sOutput)
   Set wks = appExcel.Worksheets(cTabTwo)

   sSQL = "SELECT Nom, PROMO, Semestre1A, Semestre1B, Semestre2A, Semestre2B, CatSemestre1A, CatSemestre1B, CatSemestre2A, CatSemestre2B FROM Planif WHERE CatSemestre1A > 0 OR CatSemestre1B > 0 OR CatSemestre2A > 0 OR CatSemestre2B > 0 WHERE PROMO = '" & Promo_var & "' ORDER BY Nom ASC "
   MsgBox sSQL
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)
</code>```

The error occurs on these line:

```<code>Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)
</code>```

The error is error

'3075' Syntax error (missing operator)

I can't find where is the problem.
i've tried several sql change but i'm loose

答:
You call WHERE two times in your query

```<code>SELECT Nom, PROMO, Semestre1A, Semestre1B, Semestre2A, Semestre2B, CatSemestre1A, CatSemestre1B, CatSemestre2A, CatSemestre2B
FROM Planif
WHERE CatSemestre1A > 0 OR CatSemestre1B > 0 OR CatSemestre2A > 0 OR CatSemestre2B > 0
WHERE PROMO = '" & Promo_var & "'
ORDER BY Nom ASC
</code>```

Title: Error on sql request on access vba

Body:
I've an error on this code:

 Promo_var = Modifiable84.Value
   MsgBox Promo_var

   DoCmd.Hourglass True 'icone tablier a true

   ' set to break on all errors
   Application.SetOption "Error Trapping", 0

   ' start with a clean file built from the template file
   sTemplate = CurrentProject.Path & "\PlanificationAnnuelle_Template.xlsx"
   sOutput = CurrentProject.Path & "\PlanificationAnnuelle.xlsx"
   If Dir(sOutput) <> "" Then Kill sOutput
   FileCopy sTemplate, sOutput

   ' Create the Excel Applicaiton, Workbook and Worksheet and Database object
   Set appExcel = New Excel.Application
   Set wbk = appExcel.Workbooks.Open(sOutput)
   Set wks = appExcel.Worksheets(cTabTwo)

   sSQL = "SELECT Nom, PROMO, Semestre1A, Semestre1B, Semestre2A, Semestre2B, CatSemestre1A, CatSemestre1B, CatSemestre2A, CatSemestre2B FROM Planif WHERE CatSemestre1A > 0 OR CatSemestre1B > 0 OR CatSemestre2A > 0 OR CatSemestre2B > 0 WHERE PROMO = '" & Promo_var & "' ORDER BY Nom ASC "
   MsgBox sSQL
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)

The error occurs on these line:

Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)

The error is error

'3075' Syntax error (missing operator)

I can't find where is the problem.
i've tried several sql change but i'm loose

Body:
You call WHERE two times in your query

SELECT Nom, PROMO, Semestre1A, Semestre1B, Semestre2A, Semestre2B, CatSemestre1A, CatSemestre1B, CatSemestre2A, CatSemestre2B
FROM Planif
WHERE CatSemestre1A > 0 OR CatSemestre1B > 0 OR CatSemestre2A > 0 OR CatSemestre2B > 0
WHERE PROMO = '" & Promo_var & "'
ORDER BY Nom ASC


问:
How to count total items in a column, if header name is provided
Sorry! May be I couldn't give a nice question title. I have following sample data. Obviously in case of actual data it will be different and more...

Data Screenshot

Suppose, I put Pen in D17 cell then expected result will be 6 in E17 cell as in table/DataArray Pen column has 6 items. Count should be 4 if I put T-Shirt in D17 cell and so on....

Believe me, I tried combination of many formulas, search on google but no satisfied solution found. I can achieve it by VBA but I am trying to solve it by using excel formulas only.

答:
You can use this array formula in cell E17:

```<code>= SUMPRODUCT(MMULT((B3:K3=D17)+0,TRANSPOSE(NOT(ISBLANK(B4:K13))+0)))
</code>```

Note since this is an array formula, you must press Ctrl+Shift+Enter instead of just Enter after typing this formula.

Body:
You can use this array formula in cell E17:

= SUMPRODUCT(MMULT((B3:K3=D17)+0,TRANSPOSE(NOT(ISBLANK(B4:K13))+0)))

Note since this is an array formula, you must press Ctrl+Shift+Enter instead of just Enter after typing this formula.


问:
Thymeleaf and JPA - object saving isn't possible
I have a problem with setting my Country object to my Pet object.

```<code>@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class Country {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
}
</code>```

My Pet class

```<code>@Data
@Entity
public class Pet {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    private Country country;
    }
</code>```

I've tried to do this in this way(countries is list of all countries from database, I added this to model as a attribute):

```<code>    <form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:field="*{country}" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>
</code>```

But this don't save country object to my Pet object.
I had to do this in this way, I save only id to country object:

```<code><form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:name="country.id" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal.id}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>
</code>```

Is there some way to save my country object from list to country in Pet object?
Or some another way.
Is this code with country.id proper way to save existed object from database to object in my Pet class?

答:
You are missing th:field in select tag. Try this

```<code><select class="form-control" th:field="*{country}"> // * is NOTa typo here
    <option th:each="countryVal : ${countries}"
            th:value="${countryVal.id}"
            th:text="${countryVal.getName()}"
            >val
    </option>
</select>
</code>```

Disclaimer: This applies to Thymeleaf 3.

Body:
I have a problem with setting my Country object to my Pet object.

@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class Country {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
}

My Pet class

@Data
@Entity
public class Pet {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    private Country country;
    }

I've tried to do this in this way(countries is list of all countries from database, I added this to model as a attribute):

    <form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:field="*{country}" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>

But this don't save country object to my Pet object.
I had to do this in this way, I save only id to country object:

<form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:name="country.id" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal.id}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>

Is there some way to save my country object from list to country in Pet object?
Or some another way.
Is this code with country.id proper way to save existed object from database to object in my Pet class?

Body:
You are missing th:field in select tag. Try this

<select class="form-control" th:field="*{country}"> // * is NOTa typo here
    <option th:each="countryVal : ${countries}"
            th:value="${countryVal.id}"
            th:text="${countryVal.getName()}"
            >val
    </option>
</select>

Disclaimer: This applies to Thymeleaf 3.


问:
Squarespace ajax call do not load video and audio
i'm working with squarespace developer mode, i create some javascript code to get my blog articles or events, the problem i have is that when i use ajax call to get my events to display them in a page i've created, the data is loaded correctly except blocks having audios and videos, i had the same issue with images, but SQS gives a solution for images :

var images = document.querySelectorAll('img[data-src]' );
        for (var i = 0; i < images.length; i++) {
        ImageLoader.load(images[i], {load: true});
      }

But this do not solve the audio and videos blocks, i've tested every single code part existing on SQS forums but none of them work, ive also tested what suggested here but no solution.

Here is my code to get events:

```<code>$(document).ready(function(){
var url = '/test-blog?format=json';
$.getJSON(url).done(function(data) {
  var items = data.items;

  var $_container = $('#events-container-concert');
  var result = "";
  var appendText = [];
  items.forEach(function(elm) {
    var body = elm.body;
    var $_body = $(body);

    appendText.push("<div class='blog-item'><div id='body'>"+body+"</div>");
  });

  appendText.join(" ");
  $_container.html(appendText);

  var images = document.querySelectorAll('img[data-src]' );
    for (var i = 0; i < images.length; i++) {
    ImageLoader.load(images[i], {load: true});
  }
 });
});
</code>```

Please is there anyone who had this issue on SQS?
no one answered my question on SQS forums
Thanks

答:
You may use this to automatically load all the blocks (I believe even the image blocks, but if not then pair it with your call to ImageLoader):

```<code>window.Squarespace.AFTER_BODY_LOADED = false;
window.Squarespace.afterBodyLoad();
</code>```

Of course, you'll want to wait until the content is on the page. You can pull up the page you linked-to and then run those two lines via console as a quick test. Worked well for me in that context.

Reference: https://github.com/Squarespace/squarespace-core/blob/master/src/Lifecycle.js

Body:
i'm working with squarespace developer mode, i create some javascript code to get my blog articles or events, the problem i have is that when i use ajax call to get my events to display them in a page i've created, the data is loaded correctly except blocks having audios and videos, i had the same issue with images, but SQS gives a solution for images :

var images = document.querySelectorAll('img[data-src]' );
        for (var i = 0; i < images.length; i++) {
        ImageLoader.load(images[i], {load: true});
      }

But this do not solve the audio and videos blocks, i've tested every single code part existing on SQS forums but none of them work, ive also tested what suggested here but no solution.

Here is my code to get events:

$(document).ready(function(){
var url = '/test-blog?format=json';
$.getJSON(url).done(function(data) {
  var items = data.items;

  var $_container = $('#events-container-concert');
  var result = "";
  var appendText = [];
  items.forEach(function(elm) {
    var body = elm.body;
    var $_body = $(body);

    appendText.push("

"+body+"
");
  });

  appendText.join(" ");
  $_container.html(appendText);

  var images = document.querySelectorAll('img[data-src]' );
    for (var i = 0; i < images.length; i++) {
    ImageLoader.load(images[i], {load: true});
  }
 });
});

Please is there anyone who had this issue on SQS?
no one answered my question on SQS forums
Thanks

Body:
You may use this to automatically load all the blocks (I believe even the image blocks, but if not then pair it with your call to ImageLoader):

window.Squarespace.AFTER_BODY_LOADED = false;
window.Squarespace.afterBodyLoad();

Of course, you'll want to wait until the content is on the page. You can pull up the page you linked-to and then run those two lines via console as a quick test. Worked well for me in that context.

Reference: https://github.com/Squarespace/squarespace-core/blob/master/src/Lifecycle.js


问:
How do I animate this graph so that the dot moves and the green line plots over a different range for each element in loop?
I am trying to make this animated so that the dot and the green line move due to the for loop. This code displays 3 different graphs one below the other. The middle graph has no animation section.

```<code>x =lag_range
count = 0
plt.ion()
fig, ax = plt.subplots()
for b in x:

    plt.subplot(311)
    plt.plot(x,pear_corr, color='b', linewidth=1.5, label ='Pearson')
    plt.plot(x,spear_corr, color ='r', linewidth=1.5, label='Spearman')
    plt.plot(x[count],pear_corr[count],'yo')
    plt.legend()
    axes = plt.gca()
    plt.ylabel('Correlation coefficients')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])
    axes.set_ylim(-1,1)

    plt.subplot(312)
    plt.plot(x,pear_p_values, color='b', linewidth=1.5)
    plt.plot(x,spear_p_values, color ='r', linewidth=1.5)
    axes = plt.gca()
    plt.ylabel('P values')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])

    plt.subplot(313)
    ax1 = plt.subplot(313)
    x_for_p = range(len(x_prices))
    ax1.plot(x_for_p, x_prices, color ='grey', linewidth=1.5)
    ax1.set_ylabel('Share price', color ='grey')
    ax1.tick_params('y', colors='grey')
    ax1.set_xlabel('Days')
    axes = plt.gca()
    axes.set_xlim([min(lag_list),(2*last)])

    ax2 = ax1.twinx()
    x_for_den = range(b,(b+len(x_prices)))
    ax2.plot(x_for_den, y_planes, color='g', linewidth=1.5)
    ax2.set_ylabel('Plane density', color='g')
    ax2.tick_params('y', colors='g')

    count += 1
    plt.pause(2)
    plt.draw()
</code>```

cross_corr2_vis(prices, density_p3)

答:
If you could share a working code or just definitions of variables pear_corr, spear_corr, etc., the following code might have not resulted in this simple animation:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

N_points = 1000

x = np.linspace(0,2.*np.pi,N_points)
y = np.sin(x)

fig, ax = plt.subplots()
ax.set_xlim([0,2.*np.pi])
ax.set_ylim([-1,1])
line, = ax.plot(   [],[], lw=2,  color='g')
sctr  = ax.scatter([],[], s=100, color='r')

def animate(i):
    line.set_ydata(y[:i+1])  # update
    line.set_xdata(x[:i+1])
    sctr.set_offsets((x[i],y[i]))
    return line,sctr

ani = animation.FuncAnimation(fig, animate, N_points, interval=5, blit=True)
plt.show()
</code>```

Body:
I am trying to make this animated so that the dot and the green line move due to the for loop. This code displays 3 different graphs one below the other. The middle graph has no animation section.

x =lag_range
count = 0
plt.ion()
fig, ax = plt.subplots()
for b in x:

    plt.subplot(311)
    plt.plot(x,pear_corr, color='b', linewidth=1.5, label ='Pearson')
    plt.plot(x,spear_corr, color ='r', linewidth=1.5, label='Spearman')
    plt.plot(x[count],pear_corr[count],'yo')
    plt.legend()
    axes = plt.gca()
    plt.ylabel('Correlation coefficients')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])
    axes.set_ylim(-1,1)

    plt.subplot(312)
    plt.plot(x,pear_p_values, color='b', linewidth=1.5)
    plt.plot(x,spear_p_values, color ='r', linewidth=1.5)
    axes = plt.gca()
    plt.ylabel('P values')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])

    plt.subplot(313)
    ax1 = plt.subplot(313)
    x_for_p = range(len(x_prices))
    ax1.plot(x_for_p, x_prices, color ='grey', linewidth=1.5)
    ax1.set_ylabel('Share price', color ='grey')
    ax1.tick_params('y', colors='grey')
    ax1.set_xlabel('Days')
    axes = plt.gca()
    axes.set_xlim([min(lag_list),(2*last)])

    ax2 = ax1.twinx()
    x_for_den = range(b,(b+len(x_prices)))
    ax2.plot(x_for_den, y_planes, color='g', linewidth=1.5)
    ax2.set_ylabel('Plane density', color='g')
    ax2.tick_params('y', colors='g')

    count += 1
    plt.pause(2)
    plt.draw()

cross_corr2_vis(prices, density_p3)

Body:
If you could share a working code or just definitions of variables pear_corr, spear_corr, etc., the following code might have not resulted in this simple animation:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

N_points = 1000

x = np.linspace(0,2.*np.pi,N_points)
y = np.sin(x)

fig, ax = plt.subplots()
ax.set_xlim([0,2.*np.pi])
ax.set_ylim([-1,1])
line, = ax.plot(   [],[], lw=2,  color='g')
sctr  = ax.scatter([],[], s=100, color='r')

def animate(i):
    line.set_ydata(y[:i+1])  # update
    line.set_xdata(x[:i+1])
    sctr.set_offsets((x[i],y[i]))
    return line,sctr

ani = animation.FuncAnimation(fig, animate, N_points, interval=5, blit=True)
plt.show()


问:
Angular 4 token based authentication
When I post the username and password, I need to return to me. When I get that token with the get method, I need to return the data from the URL. But error is
http://tcmtestapi.azurewebsites.net/api/demo/inventory: Response for preflight has invalid HTTP status code 405.

@Component({
  selector: 'app-envanter',
  templateUrl: './envanter.component.html',
  styleUrls: ['./envanter.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class EnvanterComponent implements OnInit {
  userName= 'tcmtest';
  password= '123456';
  token : string;
  error: any;
  envanterList: any;

  constructor(private envanterService: EnvanterService) { }

  ngOnInit() {
    this.envanterService.login(this.userName, this.password);
    this.envanterList = this.envanterService.getEnvanterList(this.token)
    .subscribe(
      envanterList => this.envanterList = envanterList,
      error => this.error = error
    );
  }

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@Injectable()
export class EnvanterService {
  public token: string;

  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    this.http = http;

  }
  login(userName: string, password: string): Observable<any> {
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/token`;
    let body = JSON.stringify({userName,password});
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, body, options)
      .map((res: any) => {
        let data = res.json();
        this.token = data.token;
        return this.token;
      });

  }

  getEnvanterList(token) {
    this.token = token;
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/inventory`;
    let headers = new Headers({'Authorization': 'Bearer ' + this.token});
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url,options)
      .map((response: Response) => response.json())
  }
}</code>```

答:
Do you have CORS enabled in you API?. If you have it enabled then add withCredentials : true  like the following:

```<code>this.options = new RequestOptions({ headers: this.headers, withCredentials : true });
</code>```

Title: Angular 4 token based authentication

Body:
When I post the username and password, I need to return to me. When I get that token with the get method, I need to return the data from the URL. But error is
http://tcmtestapi.azurewebsites.net/api/demo/inventory: Response for preflight has invalid HTTP status code 405.

@Component({
  selector: 'app-envanter',
  templateUrl: './envanter.component.html',
  styleUrls: ['./envanter.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class EnvanterComponent implements OnInit {
  userName= 'tcmtest';
  password= '123456';
  token : string;
  error: any;
  envanterList: any;

  constructor(private envanterService: EnvanterService) { }

  ngOnInit() {
    this.envanterService.login(this.userName, this.password);
    this.envanterList = this.envanterService.getEnvanterList(this.token)
    .subscribe(
      envanterList => this.envanterList = envanterList,
      error => this.error = error
    );
  }

}

@Injectable()
export class EnvanterService {
  public token: string;

  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    this.http = http;

  }
  login(userName: string, password: string): Observable<any> {
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/token`;
    let body = JSON.stringify({userName,password});
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, body, options)
      .map((res: any) => {
        let data = res.json();
        this.token = data.token;
        return this.token;
      });

  }

  getEnvanterList(token) {
    this.token = token;
    let url = `http://tcmtestapi.azurewebsites.net/api/demo/inventory`;
    let headers = new Headers({'Authorization': 'Bearer ' + this.token});
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url,options)
      .map((response: Response) => response.json())
  }
}

Body:
Do you have CORS enabled in you API?. If you have it enabled then add withCredentials : true  like the following:

this.options = new RequestOptions({ headers: this.headers, withCredentials : true });


问:
Event Bubbling and jQuery
I'm trying to capture a click event that bubbles up the DOM to the body, check to see what the selector of the click element is, and then based on that, choose to call a function.

Something like this:

```<code><body>
    <a id="do-default-code">Default code</a>
    <a id="do-override-code">Override code</a>
</body>
</code>```

And I'm picturing (psuedo-code) like this. I am using jQuery:

```<code>$('body').bind('click', function() {
    if ($(this) === $('#do-override-code')) {
        overrideCode();
    } else {

    }
});
</code>```

I realize that I don't fully understand event bubbling in this context, and that the above code is not correct, so I am looking to the community for guidance.

答:
In your statement your this refers to the element that you have bound the event to. In this case the body element. Thus the if statement is never true.

So to get the element that you have actually clicked on you need to examine the target in the event object. Something like the following should work.

```<code>$('body').bind('click', function(event) {
    if ($(event.target).attr('id') == 'do-override-code')) {
        overrideCode();
    } else {

    }
});
</code>```

Title: Event Bubbling and jQuery

Body:
I'm trying to capture a click event that bubbles up the DOM to the body, check to see what the selector of the click element is, and then based on that, choose to call a function.

Something like this:

    Default code
    Override code

And I'm picturing (psuedo-code) like this. I am using jQuery:

$('body').bind('click', function() {
    if ($(this) === $('#do-override-code')) {
        overrideCode();
    } else {

    }
});

I realize that I don't fully understand event bubbling in this context, and that the above code is not correct, so I am looking to the community for guidance.

Body:
In your statement your this refers to the element that you have bound the event to. In this case the body element. Thus the if statement is never true.

So to get the element that you have actually clicked on you need to examine the target in the event object. Something like the following should work.

$('body').bind('click', function(event) {
    if ($(event.target).attr('id') == 'do-override-code')) {
        overrideCode();
    } else {

    }
});


问:
"OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 40 seconds'
I'm trying to Code in Selenuim with C# for a website, after Username it's getting time out with the message

OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 40 seconds'

Here is my code which I'm referring to.

```<code>  //Enter user info
  SetMethods.EnterText(driver, "Username", "svedanth", "ID");
  SetMethods.EnterText(driver, "Password", "openopen", "ID");

  SetMethods.Click(driver, "Next", "ID");

  //Thread.Sleep(TimeSpan.FromSeconds(5));
  wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
  By.XPath(".//*[@id='logOnContainer']/form/div[1]/button")));
</code>```

答:
Create a new WebDriverWait like so:

```<code>WebDriverWait customWait = new WebDriverWait(driver,TimeSpan.FromMinutes(5));
</code>```

and do

```<code>customWait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath(".//*[@id='logOnContainer']/form/div[1]/button")));
</code>```

when you initialized your wait at some point in your code, you probably set the timeout at 40 seconds.

The reason you have your problem, is because 40 seconds pass and your elements are still not visible. After they are all visible, program stop "waiting" and will continue with the rest of the code.

If you will, you can set your own timeout by changing the TimeSpan I gave in my example.

Body:
I'm trying to Code in Selenuim with C# for a website, after Username it's getting time out with the message

OpenQA.Selenium.WebDriverTimeoutException: 'Timed out after 40 seconds'

Here is my code which I'm referring to.

  //Enter user info
  SetMethods.EnterText(driver, "Username", "svedanth", "ID");
  SetMethods.EnterText(driver, "Password", "openopen", "ID");

  SetMethods.Click(driver, "Next", "ID");

  //Thread.Sleep(TimeSpan.FromSeconds(5));
  wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
  By.XPath(".//*[@id='logOnContainer']/form/div[1]/button")));

Body:
Create a new WebDriverWait like so:

WebDriverWait customWait = new WebDriverWait(driver,TimeSpan.FromMinutes(5));

and do

customWait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath(".//*[@id='logOnContainer']/form/div[1]/button")));

when you initialized your wait at some point in your code, you probably set the timeout at 40 seconds.

The reason you have your problem, is because 40 seconds pass and your elements are still not visible. After they are all visible, program stop "waiting" and will continue with the rest of the code.

If you will, you can set your own timeout by changing the TimeSpan I gave in my example.


问:
400 Bad Request in my woocommerce-api ionic 3 application
I just installed woocommerce-api, created new api keys (api is enabled) in woocommerce and did a simple call to get products and test it in my ionic 3 application,
but I'm getting this -1 (400 Bad request) error

this is my code

```<code>WooCommerce: any;
constructor(public navCtrl: NavController)
{this.WooCommerce = WC({
url: "http://localhost/wordpress/index.php",
consumerKey: "ck_d165ee6b1c1f85fc17f5a615a9a630f6d7fb086a",
consumerSecret:"cs_a1c208feeb9d9aec03acfdc50cef20ae93294f7a",
wp_api:true,
version:'wc/v3',
});
this.WooCommerce.getAsync("products").then( (data) => {
console.log(data);
},
(err) => {
console.log(err) })}
</code>```

any help?

答:
Please remove two lines from WC parameter

```<code>wp_api:true,
version:'wc/v3',
</code>```

It worked for me.

Body:
I just installed woocommerce-api, created new api keys (api is enabled) in woocommerce and did a simple call to get products and test it in my ionic 3 application,
but I'm getting this -1 (400 Bad request) error

this is my code

WooCommerce: any;
constructor(public navCtrl: NavController)
{this.WooCommerce = WC({
url: "http://localhost/wordpress/index.php",
consumerKey: "ck_d165ee6b1c1f85fc17f5a615a9a630f6d7fb086a",
consumerSecret:"cs_a1c208feeb9d9aec03acfdc50cef20ae93294f7a",
wp_api:true,
version:'wc/v3',
});
this.WooCommerce.getAsync("products").then( (data) => {
console.log(data);
},
(err) => {
console.log(err) })}

any help?

Body:
Please remove two lines from WC parameter

wp_api:true,
version:'wc/v3',

It worked for me.


问:
if else to calculate from a string haskell
hi I am new to haskell and very confused about if condition of haskell.
I was trying to calculate a sum from a String of grades.
For example, grades "ABC" should have the result of "128" while A=56,B=40 and C=32.
I am wondering if I am heading to the right direction. I wanted to output the sum of the grades by having sum after then
Here is the code I got so far :

```<code>grades (x:xs) =
 if x=="A" then sum+=56
 else if x=="B" then sum+=40
 else if x=="C" then sum+=32
 else if x=="D" then sum+=24
 else if x=="E" then sum+=8
 else sum+=0
</code>```

答:
Here is something to get you started. I would recommend a good book, for example Hutton's Haskell Programming (2nd edition).

```<code>-- a function to convert grades to points
pts 'A' = 56
pts 'B' = 40
pts 'C' = 32
pts 'D' = 24
pts 'E' = 8
pts _ = 0

-- then your desired function
grades str = sum (map pts str)
-- or, point-free (no pun intended)
grades' = sum . map pts
</code>```

After these definitions

```<code>λ> map pts "ABC"
[56,40,32]
λ> grades "ABC"
128
</code>```

Happy Haskelling!

Body:
hi I am new to haskell and very confused about if condition of haskell.
I was trying to calculate a sum from a String of grades.
For example, grades "ABC" should have the result of "128" while A=56,B=40 and C=32.
I am wondering if I am heading to the right direction. I wanted to output the sum of the grades by having sum after then
Here is the code I got so far :

grades (x:xs) =
 if x=="A" then sum+=56
 else if x=="B" then sum+=40
 else if x=="C" then sum+=32
 else if x=="D" then sum+=24
 else if x=="E" then sum+=8
 else sum+=0

Body:
Here is something to get you started. I would recommend a good book, for example Hutton's Haskell Programming (2nd edition).

-- a function to convert grades to points
pts 'A' = 56
pts 'B' = 40
pts 'C' = 32
pts 'D' = 24
pts 'E' = 8
pts _ = 0

-- then your desired function
grades str = sum (map pts str)
-- or, point-free (no pun intended)
grades' = sum . map pts

After these definitions

λ> map pts "ABC"
[56,40,32]
λ> grades "ABC"
128

Happy Haskelling!


问:
Upgrade from Angular 4 to 5: "NodeInvocationException: No provider for PlatformRef!"
I've upgraded an app from Angular 4.2 to 5, but got this error:
 unhandled exception occurred while processing the request, more specifically:

NodeInvocationException: No provider for PlatformRef! Error: No
  provider for PlatformRef! at injectionError
  (e:\myapp\ClientApp\dist\vendor.js:12066:90)

The app also uses webpack and ASP.NET Core.

I have installed node v9.1, and typescript 2.6.1.

I also have updated package.json, with the command:

```<code>npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest
</code>```

And afterwards, ran the following:

```<code> npm install --save-dev @ngtools/webpack@latest
</code>```

I've also used HttpClient instead of Http:

```<code>import { HttpClient } from '@angular/common/http';
.....
 getThings() {
        return this.http.get('/api/things');

  }
</code>```

If I downgrade back Angular 4, the app works fine, is there anything in my line of thought that has been done incorrectly?

答:
Two different things, which you can try:

1) import HttpClientModule at your NgModule's import array first.(If you are using HttpClient in your component)

2) https://stackoverflow.com/a/39206501/2810015

Note: to upgrade your application : https://onlyforcoder.blogspot.in/2017/11/angular-5-upgrade-your-project-To-Angular5.html

Body:
I've upgraded an app from Angular 4.2 to 5, but got this error:
 unhandled exception occurred while processing the request, more specifically:

NodeInvocationException: No provider for PlatformRef! Error: No
  provider for PlatformRef! at injectionError
  (e:\myapp\ClientApp\dist\vendor.js:12066:90)

The app also uses webpack and ASP.NET Core.

I have installed node v9.1, and typescript 2.6.1.

I also have updated package.json, with the command:

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest

And afterwards, ran the following:

 npm install --save-dev @ngtools/webpack@latest

I've also used HttpClient instead of Http:

import { HttpClient } from '@angular/common/http';
.....
 getThings() {
        return this.http.get('/api/things');

  }

If I downgrade back Angular 4, the app works fine, is there anything in my line of thought that has been done incorrectly?


问:
Save and load weights in keras
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

```<code>TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')
</code>```

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

```<code>from keras.models import load_model
model = load_model('myModel.h5')
</code>```

but i get this error:

```<code>ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.
</code>```

Any suggestions on what i may be doing wrong?
Thank you in advance.

答:
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

```<code>model.save_weights('my_model_weights.h5')
</code>```

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

```<code>model.load_weights('my_model_weights.h5')
</code>```

Another saving technique is model.save(filepath). This save function saves:

The architecture of the model, allowing to re-create the model.

The weights of the model.

The training configuration (loss, optimizer).

The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

```<code>from keras.models import load_model
new_model = load_model(filepath)'
</code>```

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

```<code>from keras.models import model_from_json
model = model_from_json(json_string)
</code>```

Title: Save and load weights in keras

Body:
Im trying to save and load weights from the model i have trained.

the code im using to save the model is.

TensorBoard(log_dir='/output')
model.fit_generator(image_a_b_gen(batch_size), steps_per_epoch=1, epochs=1)
model.save_weights('model.hdf5')
model.save_weights('myModel.h5')

Let me know if this an incorrect way to do it,or if there is a better way to do it.

but when i try to load them,using this,

from keras.models import load_model
model = load_model('myModel.h5')

but i get this error:

ValueError                                Traceback (most recent call
last)
<ipython-input-7-27d58dc8bb48> in <module>()
      1 from keras.models import load_model
----> 2 model = load_model('myModel.h5')

/home/decentmakeover2/anaconda3/lib/python3.5/site-
packages/keras/models.py in load_model(filepath, custom_objects, compile)
    235         model_config = f.attrs.get('model_config')
    236         if model_config is None:
--> 237             raise ValueError('No model found in config file.')
    238         model_config = json.loads(model_config.decode('utf-8'))
    239         model = model_from_config(model_config,
custom_objects=custom_objects)

ValueError: No model found in config file.

Any suggestions on what i may be doing wrong?
Thank you in advance.

Body:
Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

The architecture of the model, allowing to re-create the model.

The weights of the model.

The training configuration (loss, optimizer).

The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)


问:
R- visNetwork - graph doesn't show edges
I have a code that looks like this:

```<code>setwd("C:/Users/Evangelista/Desktop/v1")

require(visNetwork)
require(dplyr)
require(shiny)
require(magrittr)

graf.info = read.csv("nodes.csv")
id <- rownames(graf.info)
graf.info <- (cbind(id=id, graf.info))
graf.powiazania = read.csv("edges.csv")

visNetworkNodes <- data.frame(graf.info) %>%
  mutate(id=graf.info$id,
         label = nazwa_agenta,
         title = nazwa_agenta)

visNetworkLinks <- data.frame(from = graf.powiazania$From,
                              to = graf.powiazania$To,
                              width = 50,
                              arrows = list(to = list(enabled = TRUE, scaleFactor = 4)))

net <- visNetwork(nodes = visNetworkNodes,
                  edges = visNetworkLinks,
                  height = "600px",
                  width = "800px")

net
</code>```

And my problem is that the graph doesn't display any edges. My data is taken from csv file and it looks like this:

I don't know what is wrong with it. My data looks correct to me, data frame with nodes also has the column id. Data frame with edges has "From" and "To" columns. I run out of ideas what went wrong.

答:
I found a solution : </p>

```<code>visNetworkNodes <- data.frame(graf.info) %>%
  mutate(id=graf.info$nazwa_agenta, <------here i changed 'id' to 'nazwa_agenta'
         label = nazwa_agenta,
         title = nazwa_agenta)
</code>```

Body:
I have a code that looks like this:

setwd("C:/Users/Evangelista/Desktop/v1")

require(visNetwork)
require(dplyr)
require(shiny)
require(magrittr)

graf.info = read.csv("nodes.csv")
id <- rownames(graf.info)
graf.info <- (cbind(id=id, graf.info))
graf.powiazania = read.csv("edges.csv")

visNetworkNodes <- data.frame(graf.info) %>%
  mutate(id=graf.info$id,
         label = nazwa_agenta,
         title = nazwa_agenta)

visNetworkLinks <- data.frame(from = graf.powiazania$From,
                              to = graf.powiazania$To,
                              width = 50,
                              arrows = list(to = list(enabled = TRUE, scaleFactor = 4)))

net <- visNetwork(nodes = visNetworkNodes,
                  edges = visNetworkLinks,
                  height = "600px",
                  width = "800px")

net

And my problem is that the graph doesn't display any edges. My data is taken from csv file and it looks like this:

I don't know what is wrong with it. My data looks correct to me, data frame with nodes also has the column id. Data frame with edges has "From" and "To" columns. I run out of ideas what went wrong.

Body:
I found a solution :

visNetworkNodes <- data.frame(graf.info) %>%
  mutate(id=graf.info$nazwa_agenta, <------here i changed 'id' to 'nazwa_agenta'
         label = nazwa_agenta,
         title = nazwa_agenta)


问:
TaxJar method is not returning anything
I am using TaxJar integration in one of my projects to calculate the tax for an order. I have integrated TaxJar like this:

```<code>    $client = TaxJar\Client::withApiKey("8516090bdbb97d99632daa2acaf910aa30");

    $order_taxes = $client->taxForOrder([
        'from_country' => 'US',
        'from_zip' => '07001',
        'from_state' => 'NJ',
        'to_country' => 'US',
        'to_zip' => '07446',
        'to_state' => 'NJ',
        'amount' => 16.50,
        'shipping' => 1.5,
        'line_items' => [
            [
                'quantity' => 1,
                'unit_price' => 15.0,
                'product_tax_code' => 31000
            ]
        ]
    ]);
</code>```

When I do var_dump($client), it shows all the details of the TaxJar dependencies which are included, but when I do var_dump($order_taxes) it shows nothing.

What should I do to get this work?

答: This API request should work correctly based on the information given. Please see our response to your GitHub issue and reach out to TaxJar support with your account details for further assistance.</p>

Title: TaxJar method is not returning anything

Body:
I am using TaxJar integration in one of my projects to calculate the tax for an order. I have integrated TaxJar like this:

    $client = TaxJar\Client::withApiKey("8516090bdbb97d99632daa2acaf910aa30");

    $order_taxes = $client->taxForOrder([
        'from_country' => 'US',
        'from_zip' => '07001',
        'from_state' => 'NJ',
        'to_country' => 'US',
        'to_zip' => '07446',
        'to_state' => 'NJ',
        'amount' => 16.50,
        'shipping' => 1.5,
        'line_items' => [
            [
                'quantity' => 1,
                'unit_price' => 15.0,
                'product_tax_code' => 31000
            ]
        ]
    ]);

When I do var_dump($client), it shows all the details of the TaxJar dependencies which are included, but when I do var_dump($order_taxes) it shows nothing.

What should I do to get this work?


问:
PHPExcel generate a file with extension error on deployed server, but perfectly working on localhost
I had some routes that fetch data from a DataBase, open a template-file.xlsx and put that data, then, sent create a response to autodownloaded .xlsx file.

Worked at localhost never met any issues, but today deployed the project, and everything working fine, except that routes.

It generates me a result-xlsx file, but when I try to open it, it's treated like a xml and it's all in random symbols and so on.

I'm using PHPExcel bundle for Symfony, that has some shortcuts for PHPExcel library, but in fact is exactly the same.

I'm sure that I don't have problems in my code, but I'll provide it below :

My code :

```<code>   /**
   * @Route("/download-til/{id}", name="downloadTIL")
   * @Method({"GET","HEAD", "POST"})
   */
public function downloadTILAction(Request $request, $id, Loan $loan)
    {
      if($loan->getLine()->getDosier()->getUserId() != $this->getUser()){
          throw $this->createNotFoundException("Access denied"); }

        $query = $this->getDoctrine()
            ->getRepository('AppBundle:Loan')
            ->find($id);

        $em = $this->getDoctrine()->getManager();

        $query1 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        AND p.isActive = true
        ')->setParameter('loanId', $id);

        $query2 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Payment p
        WHERE p.loanId = :loanId
        ')->setParameter('loanId', $id);

        $query3 = $em->createQuery(
        'SELECT d
        FROM AppBundle:Deferral d
        WHERE d.loanId = :loanId
        ')->setParameter('loanId', $id);

        $query4 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        AND p.isActiveTEG = true
        ')->setParameter('loanId', $id);

        $query5 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        ')->setParameter('loanId', $id);

        $calculator = new Calculator(
            $query->getDate(),
            $query->getCapital(),
            $query->getRate(),
            $query->getFrequency(),
            $query->getDuration(),
            $query->getType(),
            $query1->getArrayResult(),//charges with active SCH
            $query2->getArrayResult(),//forced payments
            $query3->getArrayResult(),//deferrals
            $query4->getArrayResult(),//charges with active BANK
            $query5->getArrayResult(),//get absolute all charges(active and inactive), to sort them in Calculator, and return to view
            $query->getForcedTIL()
        );

            $array = $calculator->getArray();
            $chargesArray = $calculator->getChargeTableArray();

          $dur = $query->getDuration();
        // ask the service for a Excel5
          $dir = $this->get('kernel')->getRootDir();
      $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($dir.'/OutputTIL.xlsx');

       $phpExcelObject->getProperties()->setCreator("liuggio")
           ->setLastModifiedBy("Expertiseur")
           ->setTitle("Office 2005 XLSX Test Document")
           ->setSubject("Office 2005 XLSX Test Document")
           ->setDescription("Raport")
           ->setKeywords("office 2005 openxml php")
           ->setCategory("Analyse result file");

           $phpExcelObject->setActiveSheetIndex(0)
           ->setCellValue('B3', $query->getCapital())
           ->setCellValue('E3', $dur)
           ->setCellValue('H3', $array[0]['Date'])
           ->setCellValue('K3', $array[0]['Rate']/100)
           ->setCellValue('B12', $array[0]['Date'])
           ->setCellValue('I12', $array[$dur-1]['Date'])

           ->setCellValue('D12', $chargesArray[1000]['bankInterest1'])
           ->setCellValue('E12', $chargesArray[1000]['legalInterest1'])
           ->setCellValue('E13', $chargesArray[1000]['currentReparation1'])
           ->setCellValue('J12', $chargesArray[1000]['bankInterest2'])
           ->setCellValue('K12', $chargesArray[1000]['legalInterest2'])
           ->setCellValue('K13', $chargesArray[1000]['currentReparation2'])
           ->setCellValue('H15', $chargesArray[1000]['reparationGlobalPotential']);

             for($i = 20, $j = $dur; $j < $dur*2; $i++,$j++) {
                     $phpExcelObject->setActiveSheetIndex(0)
                     ->setCellValue('A'.$i, $i-19)
                     ->setCellValue('B'.$i, $array[$i-20]['Date'])
                     ->setCellValue('C'.$i, $array[$i-20]['Capital'])
                     ->setCellValue('D'.$i, $array[$i-20]['Rate']/100)
                     ->setCellValue('E'.$i, $array[$i-20]['Interest'])
                     ->setCellValue('F'.$i, $array[$i-20]['Payment'])

                     ->setCellValue('H'.$i, $array[$j]['CapitalTIL'])
                     ->setCellValue('I'.$i, $array[$j]['RateTIL']/100)
                     ->setCellValue('J'.$i, $array[$j]['InterestTIL'])
                     ->setCellValue('K'.$i, $array[$j]['PaymentTIL'])
                     ;
                   }

      $BStyle = array(
        'borders' => array(
        'allborders' => array(
        'style' => PHPExcel_Style_Border::BORDER_THIN
    )));

      $highestRow = $phpExcelObject->setActiveSheetIndex(0)->getHighestDataRow();

      $phpExcelObject->setActiveSheetIndex(0)->getStyle("A20:K{$highestRow}")->applyFromArray($BStyle);

       $phpExcelObject->getActiveSheet()->setTitle('Output TIL');
       // Set active sheet index to the first sheet, so Excel opens this as the first sheet

        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
        // create the response
        $response = $this->get('phpexcel')->createStreamedResponse($writer);
        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            '4 Calcul au tx legal.xlsx'
        );
      $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
      $response->headers->set('Pragma', 'public');
      $response->headers->set('Cache-Control', 'maxage=1');
      $response->headers->set('Content-Disposition', $dispositionHeader);

        return $response;
    }//downloadTILAction
</code>```

What can cause that error? Thanks!

答:
Choose the right Content-Type:

For BIFF .xls files

```<code>application/vnd.ms-excel
</code>```

For Excel2007 and above .xlsx files

```<code>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
</code>```

To change this line:

```<code>$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
</code>```

to this:

```<code>$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');
</code>```

Bonus

As a bonus, an answer for a question you didn't ask:

Possibly without even knowing, you are using type hinting with the built-in Doctrine Converter. That makes these lines completely useless:

```<code>$query = $this->getDoctrine()
        ->getRepository('AppBundle:Loan')
        ->find($id);
</code>```

Just use $loan->getDate() instead. And instead of $query* = $em->createQuery() you can use associations. If your Association Mapping is correct (if not, fix it!) you can use $loan->getPayments(). You're using a very powerful and extensive framework, so use it's features!

Body:
I had some routes that fetch data from a DataBase, open a template-file.xlsx and put that data, then, sent create a response to autodownloaded .xlsx file.

Worked at localhost never met any issues, but today deployed the project, and everything working fine, except that routes.

It generates me a result-xlsx file, but when I try to open it, it's treated like a xml and it's all in random symbols and so on.

I'm using PHPExcel bundle for Symfony, that has some shortcuts for PHPExcel library, but in fact is exactly the same.

I'm sure that I don't have problems in my code, but I'll provide it below :

My code :

   /**
   * @Route("/download-til/{id}", name="downloadTIL")
   * @Method({"GET","HEAD", "POST"})
   */
public function downloadTILAction(Request $request, $id, Loan $loan)
    {
      if($loan->getLine()->getDosier()->getUserId() != $this->getUser()){
          throw $this->createNotFoundException("Access denied"); }

        $query = $this->getDoctrine()
            ->getRepository('AppBundle:Loan')
            ->find($id);

        $em = $this->getDoctrine()->getManager();

        $query1 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        AND p.isActive = true
        ')->setParameter('loanId', $id);

        $query2 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Payment p
        WHERE p.loanId = :loanId
        ')->setParameter('loanId', $id);

        $query3 = $em->createQuery(
        'SELECT d
        FROM AppBundle:Deferral d
        WHERE d.loanId = :loanId
        ')->setParameter('loanId', $id);

        $query4 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        AND p.isActiveTEG = true
        ')->setParameter('loanId', $id);

        $query5 = $em->createQuery(
        'SELECT p
        FROM AppBundle:Charge p
        WHERE p.loanId = :loanId
        ')->setParameter('loanId', $id);

        $calculator = new Calculator(
            $query->getDate(),
            $query->getCapital(),
            $query->getRate(),
            $query->getFrequency(),
            $query->getDuration(),
            $query->getType(),
            $query1->getArrayResult(),//charges with active SCH
            $query2->getArrayResult(),//forced payments
            $query3->getArrayResult(),//deferrals
            $query4->getArrayResult(),//charges with active BANK
            $query5->getArrayResult(),//get absolute all charges(active and inactive), to sort them in Calculator, and return to view
            $query->getForcedTIL()
        );

            $array = $calculator->getArray();
            $chargesArray = $calculator->getChargeTableArray();

          $dur = $query->getDuration();
        // ask the service for a Excel5
          $dir = $this->get('kernel')->getRootDir();
      $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($dir.'/OutputTIL.xlsx');

       $phpExcelObject->getProperties()->setCreator("liuggio")
           ->setLastModifiedBy("Expertiseur")
           ->setTitle("Office 2005 XLSX Test Document")
           ->setSubject("Office 2005 XLSX Test Document")
           ->setDescription("Raport")
           ->setKeywords("office 2005 openxml php")
           ->setCategory("Analyse result file");

           $phpExcelObject->setActiveSheetIndex(0)
           ->setCellValue('B3', $query->getCapital())
           ->setCellValue('E3', $dur)
           ->setCellValue('H3', $array[0]['Date'])
           ->setCellValue('K3', $array[0]['Rate']/100)
           ->setCellValue('B12', $array[0]['Date'])
           ->setCellValue('I12', $array[$dur-1]['Date'])

           ->setCellValue('D12', $chargesArray[1000]['bankInterest1'])
           ->setCellValue('E12', $chargesArray[1000]['legalInterest1'])
           ->setCellValue('E13', $chargesArray[1000]['currentReparation1'])
           ->setCellValue('J12', $chargesArray[1000]['bankInterest2'])
           ->setCellValue('K12', $chargesArray[1000]['legalInterest2'])
           ->setCellValue('K13', $chargesArray[1000]['currentReparation2'])
           ->setCellValue('H15', $chargesArray[1000]['reparationGlobalPotential']);

             for($i = 20, $j = $dur; $j < $dur*2; $i++,$j++) {
                     $phpExcelObject->setActiveSheetIndex(0)
                     ->setCellValue('A'.$i, $i-19)
                     ->setCellValue('B'.$i, $array[$i-20]['Date'])
                     ->setCellValue('C'.$i, $array[$i-20]['Capital'])
                     ->setCellValue('D'.$i, $array[$i-20]['Rate']/100)
                     ->setCellValue('E'.$i, $array[$i-20]['Interest'])
                     ->setCellValue('F'.$i, $array[$i-20]['Payment'])

                     ->setCellValue('H'.$i, $array[$j]['CapitalTIL'])
                     ->setCellValue('I'.$i, $array[$j]['RateTIL']/100)
                     ->setCellValue('J'.$i, $array[$j]['InterestTIL'])
                     ->setCellValue('K'.$i, $array[$j]['PaymentTIL'])
                     ;
                   }

      $BStyle = array(
        'borders' => array(
        'allborders' => array(
        'style' => PHPExcel_Style_Border::BORDER_THIN
    )));

      $highestRow = $phpExcelObject->setActiveSheetIndex(0)->getHighestDataRow();

      $phpExcelObject->setActiveSheetIndex(0)->getStyle("A20:K{$highestRow}")->applyFromArray($BStyle);

       $phpExcelObject->getActiveSheet()->setTitle('Output TIL');
       // Set active sheet index to the first sheet, so Excel opens this as the first sheet

        // create the writer
        $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
        // create the response
        $response = $this->get('phpexcel')->createStreamedResponse($writer);
        // adding headers
        $dispositionHeader = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            '4 Calcul au tx legal.xlsx'
        );
      $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
      $response->headers->set('Pragma', 'public');
      $response->headers->set('Cache-Control', 'maxage=1');
      $response->headers->set('Content-Disposition', $dispositionHeader);

        return $response;
    }//downloadTILAction

What can cause that error? Thanks!

Body:
Choose the right Content-Type:

For BIFF .xls files

application/vnd.ms-excel

For Excel2007 and above .xlsx files

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

To change this line:

$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');

to this:

$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8');

Bonus

As a bonus, an answer for a question you didn't ask:

Possibly without even knowing, you are using type hinting with the built-in Doctrine Converter. That makes these lines completely useless:

$query = $this->getDoctrine()
        ->getRepository('AppBundle:Loan')
        ->find($id);

Just use $loan->getDate() instead. And instead of $query* = $em->createQuery() you can use associations. If your Association Mapping is correct (if not, fix it!) you can use $loan->getPayments(). You're using a very powerful and extensive framework, so use it's features!


问:
Assets pipeline rails Heroku
Recently I upgraded my project to Rails 5 and I'm going crazy with the assets pipeline when trying to upload everything to Heroku.

The issue is the following: I have a collection of Ejercicios and, when u click on one of them, the app should show its information, including an image. The routes to the images are stored in my db like this img1: "ejercicios/abdominales/1_4_I1.bmp". That file, for example, would be on app/assets/images/ejercicios/abdominales/1_4_I1.bmp.

The related view show.html.haml prints the images like this: = image_tag(@ejercicio.img1) if @ejercicio.img1?.

It worked perfectly on local but not in production in Heroku, so read about the assets pipeline in order to make it work. So I changed my show.html.haml like this: = image_tag asset_path(@ejercicio.img1) if @ejercicio.img1? and I added the lines the tutorial mentions in Gemfile and application.rb. The executed bundle install and bundle exec rake assets:precompile RAILS_ENV=production, added the new 'public' folder to my git, committed and pushed my git, and finally pushed everything to heroku.

But it doesn't work, the 'alt' of the image is shown. Using the inspector I can see that the images in the html follow the normal url to the image and not the one with the fingerprint, so the helper asset_path seems not to be working properly.

Here's my production.rb in config/environments

```<code>KeepMeFit::Application.configure do

  config.eager_load = true
  config.cache_classes = true

  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  config.serve_static_assets = true

  config.assets.compress = true

  config.assets.compile = true

  config.assets.digest = falsenginx

  config.force_ssl = true

  config.i18n.fallbacks = true

  config.active_support.deprecation = :notify

  config.action_mailer.default_url_options = { :host => "http://keepmefit.herokuapp.com/"}
end
</code>```

My 'application.rb' in 'config':

```<code>require File.expand_path('../boot', __FILE__)

require 'rails/all'

require 'will_paginate/array'

if defined?(Bundler)
  Bundler.require(*Rails.groups(:assets => %w(development test)))
end

module KeepMeFit
  class Application < Rails::Application
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :es

    config.encoding = "utf-8"

    config.filter_parameters += [:password, :password_confirmation]

    config.active_support.escape_html_entities_in_json = true

    config.assets.enabled = true
    config.serve_static_assets = true

    config.assets.initialize_on_precompile = false

    config.assets.version = '1.0'

  end
end
</code>```

And my Gemfile:

```<code>source 'https://rubygems.org'

ruby '2.3.3'

gem 'rails', '5.1.4'

group :development, :test do
    gem 'sqlite3'
  gem 'activemodel'
  gem 'json'

    gem 'rspec-rails'
    gem 'guard-rspec'
    gem 'rb-notifu'
    # gem 'railroady'
end

gem 'rails_12factor', group: :production
group :production do
    gem 'pg'
end

group :test do
    gem 'capybara'
    gem 'factory_girl_rails', '4.1.0'
    gem 'launchy'
end

group :development do
    gem 'annotate'
    gem 'better_errors'
    gem 'binding_of_caller'
    gem 'meta_request'
end

group :assets do
  gem 'sass-rails'
  gem 'coffee-rails'
    gem 'coffee-script-source', '1.8.0'

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'
gem 'bcrypt', '~> 3.1.11', platforms: [:ruby, :x64_mingw, :mingw]

gem 'haml'
gem 'haml-rails'

gem 'bootstrap-sass'

require 'rbconfig'
gem 'wdm', '>= 0.1.0' if RbConfig::CONFIG['target_os'] =~ /mswin|mingw/i

gem 'modernizr-rails'

#gem "font-awesome-rails"

gem 'bootstrap-datepicker-rails'
gem 'tzinfo-data'

gem 'faker', '1.1.2'

gem 'will_paginate', '~> 3.1.0'
gem 'bootstrap-will_paginate'

gem 'turbolinks'
gem 'jquery-turbolinks'

gem 'friendly_id'

gem 'gon'

gem 'cloudinary'
</code>```

答:
The asset pipeline has basically two use-cases:

First, it precompiles and combines various stylesheets or javascript file into single bundles. Being able to precompile - for example - SCSS to CSS simplifies development. And one big combined files can be downloaded faster than many small files.

Second, it adds hashes to the filenames. This allows caching these files for a long time which improves performance too. Even if there is only a small change in one of the files then the hash and therefore the filename will change. The changed filename will not be in the cache and therefore the browser reloads the file immediately.

But in your case, your images are static anyway. There is no point precompiling images and adding hashes to files that are not supposed to change.

Therefore I would just put that images directly into the public folder and would bypass the asset pipeline for this kind of static images.

Title: Assets pipeline rails Heroku

Body:
Recently I upgraded my project to Rails 5 and I'm going crazy with the assets pipeline when trying to upload everything to Heroku.

The issue is the following: I have a collection of Ejercicios and, when u click on one of them, the app should show its information, including an image. The routes to the images are stored in my db like this img1: "ejercicios/abdominales/1_4_I1.bmp". That file, for example, would be on app/assets/images/ejercicios/abdominales/1_4_I1.bmp.

The related view show.html.haml prints the images like this: = image_tag(@ejercicio.img1) if @ejercicio.img1?.

It worked perfectly on local but not in production in Heroku, so read about the assets pipeline in order to make it work. So I changed my show.html.haml like this: = image_tag asset_path(@ejercicio.img1) if @ejercicio.img1? and I added the lines the tutorial mentions in Gemfile and application.rb. The executed bundle install and bundle exec rake assets:precompile RAILS_ENV=production, added the new 'public' folder to my git, committed and pushed my git, and finally pushed everything to heroku.

But it doesn't work, the 'alt' of the image is shown. Using the inspector I can see that the images in the html follow the normal url to the image and not the one with the fingerprint, so the helper asset_path seems not to be working properly.

Here's my production.rb in config/environments

KeepMeFit::Application.configure do

  config.eager_load = true
  config.cache_classes = true

  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  config.serve_static_assets = true

  config.assets.compress = true

  config.assets.compile = true

  config.assets.digest = falsenginx

  config.force_ssl = true

  config.i18n.fallbacks = true

  config.active_support.deprecation = :notify

  config.action_mailer.default_url_options = { :host => "http://keepmefit.herokuapp.com/"}
end

My 'application.rb' in 'config':

require File.expand_path('../boot', __FILE__)

require 'rails/all'

require 'will_paginate/array'

if defined?(Bundler)
  Bundler.require(*Rails.groups(:assets => %w(development test)))
end

module KeepMeFit
  class Application < Rails::Application
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    config.i18n.default_locale = :es

    config.encoding = "utf-8"

    config.filter_parameters += [:password, :password_confirmation]

    config.active_support.escape_html_entities_in_json = true

    config.assets.enabled = true
    config.serve_static_assets = true

    config.assets.initialize_on_precompile = false

    config.assets.version = '1.0'

  end
end

And my Gemfile:

source 'https://rubygems.org'

ruby '2.3.3'

gem 'rails', '5.1.4'

group :development, :test do
    gem 'sqlite3'
  gem 'activemodel'
  gem 'json'

    gem 'rspec-rails'
    gem 'guard-rspec'
    gem 'rb-notifu'
    # gem 'railroady'
end

gem 'rails_12factor', group: :production
group :production do
    gem 'pg'
end

group :test do
    gem 'capybara'
    gem 'factory_girl_rails', '4.1.0'
    gem 'launchy'
end

group :development do
    gem 'annotate'
    gem 'better_errors'
    gem 'binding_of_caller'
    gem 'meta_request'
end

group :assets do
  gem 'sass-rails'
  gem 'coffee-rails'
    gem 'coffee-script-source', '1.8.0'

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'
gem 'bcrypt', '~> 3.1.11', platforms: [:ruby, :x64_mingw, :mingw]

gem 'haml'
gem 'haml-rails'

gem 'bootstrap-sass'

require 'rbconfig'
gem 'wdm', '>= 0.1.0' if RbConfig::CONFIG['target_os'] =~ /mswin|mingw/i

gem 'modernizr-rails'

#gem "font-awesome-rails"

gem 'bootstrap-datepicker-rails'
gem 'tzinfo-data'

gem 'faker', '1.1.2'

gem 'will_paginate', '~> 3.1.0'
gem 'bootstrap-will_paginate'

gem 'turbolinks'
gem 'jquery-turbolinks'

gem 'friendly_id'

gem 'gon'

gem 'cloudinary'


问:
Bash script check time differnce between two directory
I am looking for a bash script to who check time difference between two directory? But in $oldtime i can`t get only 20:09:24 i get this "20:09:24.660157390".
How can i get only hours:min only.</p>

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

oldtime=$(stat -c %y /mnt/dir1| awk '{print $2}' )
ctime=$(date | awk '{print $4}')

DIFF=$($oldtime-$ctime)
if [ $DIFF > 600 ]; then
    echo "This directory have more that 10 min"
fi
</code>```

答:
You could shave off the extra suffix,
but that won't really help you.
20:09:24 - $ctime is not going to work,
because "20:09:24" is not a number.
You have several other syntax errors as well.

To calculate the difference between dates,
you need to work with seconds.

```<code>oldseconds=$(stat -c %Y /mnt/dir1)
newseconds=$(date +%s)

if (((newseconds - oldseconds) / 60)); then
    echo "This directory have more than 10 min"
fi
</code>```

Body:
I am looking for a bash script to who check time difference between two directory? But in $oldtime i can`t get only 20:09:24 i get this "20:09:24.660157390".
How can i get only hours:min only.

#!/bin/bash

oldtime=$(stat -c %y /mnt/dir1| awk '{print $2}' )
ctime=$(date | awk '{print $4}')

DIFF=$($oldtime-$ctime)
if [ $DIFF > 600 ]; then
    echo "This directory have more that 10 min"
fi

Body:
You could shave off the extra suffix,
but that won't really help you.
20:09:24 - $ctime is not going to work,
because "20:09:24" is not a number.
You have several other syntax errors as well.

To calculate the difference between dates,
you need to work with seconds.

oldseconds=$(stat -c %Y /mnt/dir1)
newseconds=$(date +%s)

if (((newseconds - oldseconds) / 60)); then
    echo "This directory have more than 10 min"
fi


问:
determine the average time to look up a key in a randomly generated balanced binary search tree in C#?
I'm trying to determine the average amount of time it takes to loop up a key in a randomly generated balanced binary search tree, as a function of the size of the tree.. I'm unable to write the code to calculate the time.. so if i can get help or at least best way to write the code i would appreciate it... its been a while since i coded</p>

答:
I'm unable to write the code to calculate the time

Use the "StopWatch" class to calculate elapsed time. It's documentation is here:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

You'll want to take measurements of several runs of the algorithm and possibly discard the first one. Remember, the first time that a method runs in a process, the JIT compiler has to jit compile all the code, which takes extra time. That could be throwing off your measurements.


问:
SVG animate D coordinates, instantly changes instead of morphing
So I got an SVG shape:

```<code><path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>
</code>```

which I want to morph into this one:

```<code><path id="shape" d="M1920 119 0 118 0 0 1920 0 1920 119z"/>
</code>```

I tried to achieve that like this:

```<code><path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"
        to="M1920 119 0 118 0 0 1920 0 1920 119z"
    dur="5s"
    fill="freeze"/>
</code>```

But that just changes the shape instantly without any animation, instead of morphing like I wanted to.
Both shapes got the same amount of points (4), so that shouldn't be the problem, right?
Does anyone know what I did wrong?

body{
overflow:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 1920 1080">
<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"
        to="M1920 119 0 118 0 0 1920 0 1920 119z"
    dur="5s"
    fill="freeze"/>
</svg></code>```

答:
It is not the points that have to match, but the path commands. Or, to state it another way: every letter has to reapear, and every number in the path string has to have an equivalent in each animation state. Only then intermediate states can be computed.

You seem to want to transition to a shape with only sharp corners. That is in contrast to your source shape that uses the S smooth curveto command. A transition would include to change to another command, which is not possible.

Reformulate the from path with a C cubic bezier command. (Adding a few spaces and commas to improve readability.) Instead of

```<code>M 1920,975 c -611.4,-49.2 -866.7,-298 -946.6,-602.2 S 682,0 682,0 h 1238 V 975 z
</code>```

use

```<code>M 1920,975 c -611.4-49.2 -866.7,-298 -946.6,-602.2 C 893.5,68.6 682,0 682,0 h 1238 V 975 z
</code>```

Then you can transition to

```<code>M 1920,119 c 0,0 -1920-1 -1920-1 C 0 118 0,0 0,0 h 1920 V 119 z
</code>```

body{
overflow:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 1920 1080">
<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M 1920,975 c-611.4-49.2 -866.7-298 -946.6-602.2 C 893.5,68.6 682,0 682,0 h 1238 V 975z"
        to="M 1920,119 c0,0 -1920-1 -1920-1 C 0 118 0,0 0,0 h 1920 V 119z"
    dur="5s"
    fill="freeze"/>
</svg></code>```

IF that does not look like you want it to, remember you can play around with the numbers, but not with the letters.

Body:
So I got an SVG shape:

<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

which I want to morph into this one:

<path id="shape" d="M1920 119 0 118 0 0 1920 0 1920 119z"/>

I tried to achieve that like this:

<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"
        to="M1920 119 0 118 0 0 1920 0 1920 119z"
    dur="5s"
    fill="freeze"/>

But that just changes the shape instantly without any animation, instead of morphing like I wanted to.
Both shapes got the same amount of points (4), so that shouldn't be the problem, right?
Does anyone know what I did wrong?

body{
overflow:hidden;
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 1920 1080">
<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"
        to="M1920 119 0 118 0 0 1920 0 1920 119z"
    dur="5s"
    fill="freeze"/>
</svg>

Body:
It is not the points that have to match, but the path commands. Or, to state it another way: every letter has to reapear, and every number in the path string has to have an equivalent in each animation state. Only then intermediate states can be computed.

You seem to want to transition to a shape with only sharp corners. That is in contrast to your source shape that uses the S smooth curveto command. A transition would include to change to another command, which is not possible.

Reformulate the from path with a C cubic bezier command. (Adding a few spaces and commas to improve readability.) Instead of

M 1920,975 c -611.4,-49.2 -866.7,-298 -946.6,-602.2 S 682,0 682,0 h 1238 V 975 z

use

M 1920,975 c -611.4-49.2 -866.7,-298 -946.6,-602.2 C 893.5,68.6 682,0 682,0 h 1238 V 975 z

Then you can transition to

M 1920,119 c 0,0 -1920-1 -1920-1 C 0 118 0,0 0,0 h 1920 V 119 z

body{
overflow:hidden;
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 1920 1080">
<path id="shape" d="M1920,975c-611.4-49.2-866.7-298-946.6-602.2S682,0,682,0h1238V975z"/>

<animate xlink:href="#shape"
    attributeName="d"
    attributeType="XML"
    from="M 1920,975 c-611.4-49.2 -866.7-298 -946.6-602.2 C 893.5,68.6 682,0 682,0 h 1238 V 975z"
        to="M 1920,119 c0,0 -1920-1 -1920-1 C 0 118 0,0 0,0 h 1920 V 119z"
    dur="5s"
    fill="freeze"/>
</svg>

IF that does not look like you want it to, remember you can play around with the numbers, but not with the letters.