问:
animation CSS3+jquery
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

```<code><!doctype html>
<html>

  <head>
    <meta charset="UTF-8">
    <title>projekt powazny</title>
    <!--external style-sheet-->
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <!--external scripts, jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/custom.js"></script>
    <script src="https://use.fontawesome.com/39b504251e.js"></script>
  </head>

  <body>
    <!--header with nav-->
    <header>
      <!--menu-->
      <div id="menu-click">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>
      <!--menu-hidden + add class show on click-->
      <div id="menu-hidden">
      </div>
    </header>
  </body>
</html>

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});
</code>```

答:
Combining CSS3 and jQuery to animate class transitions seems like it may be prone to error.  I would highly recommend using jQuery UI's animated toggleClass().

$("#menu-click").click(function () {
  $(".menu-hidden").toggleClass("open", 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

.menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  left: 0px;
}</code>```

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

```

Title: animation CSS3+jquery

Body:
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

<!doctype html>

    <meta charset="UTF-8">
    <title>projekt powazny</title>

    <link rel="stylesheet" type="text/css" href="css/custom.css">

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});

Body:
Combining CSS3 and jQuery to animate class transitions seems like it may be prone to error.  I would highly recommend using jQuery UI's animated toggleClass().

$("#menu-click").click(function () {
  $(".menu-hidden").toggleClass("open", 500);
});

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

.menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  left: 0px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://use.fontawesome.com/39b504251e.js"></script>
<!--menu-->
<div id="menu-click">
  <i class="fa fa-bars" aria-hidden="true"></i>
</div>

<!--menu-hidden + add class show on click-->
<div class="menu-hidden">

</div>


来源: stackexchange

问:
Excel VBA: Maintaining number formatting with digits and letters
I am writing a code where basically I need to follow the sequence in logic. I am going through all the lines

```<code>Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & o - 1
End If
Next i
</code>```

So this the last line (there are more than 50 in original code) returns me a value of the cell C5 (20170331) & AB & the o minus 1 (because I have started at 2 (1st line header)). So this is giving 20170331AB1, but it should give 20170331AB01 (zero before the 0). This sequence works like a charm after 10, but before ten when I need to add a zero - I got stuck.

Any ideas? Thank you.

答:
Try this:</p>

```<code>rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a code where basically I need to follow the sequence in logic. I am going through all the lines

Set rep = Sheets("Details")
For i = 2 To n
If Sheets("Work").Range("A:A").Find(Worksheets("Work_report").Range("E" & i).Value, lookat:=xlWhole) Is Nothing Then
Else:
o = rep.Range("A" & Rows.Count).End(xlUp).Row + 1
rep.Range("A" & o).Value = "FT_EXCEL"
rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & o - 1
End If
Next i

So this the last line (there are more than 50 in original code) returns me a value of the cell C5 (20170331) & AB & the o minus 1 (because I have started at 2 (1st line header)). So this is giving 20170331AB1, but it should give 20170331AB01 (zero before the 0). This sequence works like a charm after 10, but before ten when I need to add a zero - I got stuck.

Any ideas? Thank you.

Body:
Try this:

rep.Range("B" & o).Value = Sheets("Start").Range("C5") & "AB" & Format(o - 1, "00")


问:
Capitalization standards in importing in python
There are a lot of standard abbreviations used for importing modules in python.  I frequently see

```<code>import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
</code>```

I notice that all of these are lower case.  I can't think of any exceptions.  However, it is case sensitive, so we certainly can use capital letters.  Is there any PEP standard about this?  In particular, would there be any problem with creating modules with capitalized names and importing them with capitalizations?

For example:

```<code>import MyClass as MC
import TomAndJerry as TaJ
</code>```

(please note - I'm not really interested in personal opinions - but rather whether there are official standards)

答:
PEP 8 covers package and module names specifically stating:

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Body:
There are a lot of standard abbreviations used for importing modules in python.  I frequently see

import matplotlib.pyplot as plt
import numpy as np
import networkx as nx

I notice that all of these are lower case.  I can't think of any exceptions.  However, it is case sensitive, so we certainly can use capital letters.  Is there any PEP standard about this?  In particular, would there be any problem with creating modules with capitalized names and importing them with capitalizations?

For example:

import MyClass as MC
import TomAndJerry as TaJ

(please note - I'm not really interested in personal opinions - but rather whether there are official standards)


答:
There are indeed official standards:

Modules should have short, all-lowercase names. Underscores can be
  used in the module name if it improves readability. Python packages
  should also have short, all-lowercase names, although the use of
  underscores is discouraged.

When an extension module written in C or C++ has an accompanying
  Python module that provides a higher level (e.g. more object oriented)
  interface, the C/C++ module has a leading underscore (e.g. _socket ).

Title: Capitalization standards in importing in python


问:
How can I make the navigation bar to show only at the very top?
How can I make the navigation bar re-appear only when the users scrolls at the very top? currently, the nav bar appears when the users scrolls up, irrelevant the position of the screen.

Html

```<code><header class="nav-down">
 <div> navigation </div>
</header>
</code>```

Javascript

```<code>var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('#navigation-container').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
var st = $(this).scrollTop();

// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
    return;

// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
    // Scroll Down
    $('header').removeClass('navigation-container').addClass('nav-up');
} else {
    // Scroll Up
    if(st + $(window).height() < $(document).height()) {
        $('header').removeClass('nav-up').addClass('nav-down');
    }
}

lastScrollTop = st;
}
</code>```

CSS

```<code>header {
height: 40px;
position: fixed;
top: 0;
transition: top 0.5s ease-in-out;
width: 100%;
z-index: 999;
padding-top: 50px;
}

.nav-up {
top: -70px;
}
</code>```

Thanks!

答:
There are two things you need to do in order to achieve that:

Delete / comment the entire navbar script.

Cleanup the header declaration in CSS by removing all but the following 2 lines:

header {
  height: 40px;
  width: 100%;
}
```

Body:
How can I make the navigation bar re-appear only when the users scrolls at the very top? currently, the nav bar appears when the users scrolls up, irrelevant the position of the screen.

Html

 navigation

Javascript

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('#navigation-container').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
var st = $(this).scrollTop();

// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
    return;

// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
    // Scroll Down
    $('header').removeClass('navigation-container').addClass('nav-up');
} else {
    // Scroll Up
    if(st + $(window).height() < $(document).height()) {
        $('header').removeClass('nav-up').addClass('nav-down');
    }
}

lastScrollTop = st;
}

CSS

header {
height: 40px;
position: fixed;
top: 0;
transition: top 0.5s ease-in-out;
width: 100%;
z-index: 999;
padding-top: 50px;
}

.nav-up {
top: -70px;
}

Thanks!


问:
WorkSheet_Change Event does not auto update
I am trying to auto update cell values in Column I based on values in column H.
- I want whenever user enters any value in column H then the first five characters should be copied in corresponding column I.

if I'm entering 123456789 in column H then 12345 should get auto updated immediately in column I

****Issues faced**

The values in column i does not get auto populated when values is entered in column H. Suppose there are 5 rows entered in column H the values would only get updated or populated after user enters any value in Column I

In the below code in the For Loop if i change the Target.Range("B" & i) and when i click on Column , values in column C gets updated and not in B. i understand the expected Target Range mentioned is column I, but why does Column C gets updated when i enter Column B in the for loop**

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
   If Intersect(Target, Range("I1:I20")) Is Nothing Then Exit Sub
   Application.EnableEvents = False
   'Set the values to be uppercase
      Dim i As Long
      'With Sheets("Sheet1")
       For i = 1 To 20
           Target.Range("A" & i).Value = Mid(Range("H" & i), 1, 5)

       Next i
      'End With
  Application.EnableEvents = True
End Sub
</code>```

答:
You do not really need to loop - To get the result immediately just simply do this

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False

    If Not Intersect(Target, Range("H1:H20")) Is Nothing Then

        Target.Offset(0, 1) = Mid(Target.Value, 1, 5)

    End If

    Application.EnableEvents = True

End Sub
</code>```

Mid Function Returns a string containing a specified number of characters from a string.

Body:
I am trying to auto update cell values in Column I based on values in column H.
- I want whenever user enters any value in column H then the first five characters should be copied in corresponding column I.

if I'm entering 123456789 in column H then 12345 should get auto updated immediately in column I

****Issues faced**

The values in column i does not get auto populated when values is entered in column H. Suppose there are 5 rows entered in column H the values would only get updated or populated after user enters any value in Column I

In the below code in the For Loop if i change the Target.Range("B" & i) and when i click on Column , values in column C gets updated and not in B. i understand the expected Target Range mentioned is column I, but why does Column C gets updated when i enter Column B in the for loop**

Private Sub Worksheet_Change(ByVal Target As Range)
   If Intersect(Target, Range("I1:I20")) Is Nothing Then Exit Sub
   Application.EnableEvents = False
   'Set the values to be uppercase
      Dim i As Long
      'With Sheets("Sheet1")
       For i = 1 To 20
           Target.Range("A" & i).Value = Mid(Range("H" & i), 1, 5)

       Next i
      'End With
  Application.EnableEvents = True
End Sub

Body:
You do not really need to loop - To get the result immediately just simply do this

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False

    If Not Intersect(Target, Range("H1:H20")) Is Nothing Then

        Target.Offset(0, 1) = Mid(Target.Value, 1, 5)

    End If

    Application.EnableEvents = True

End Sub

Mid Function Returns a string containing a specified number of characters from a string.


问:
C++ getline(cin, variable) is misbehaving. No solutions on the site have helped
My code is rather simple. I have a method called promptUserInput that is defined in UtilityFunctions.h; it is implemented in UtilityFunctions.cpp.

My main method includes UtilityFunctions.h. I've correctly written my makefile, and it compiles without issue.

My main method's first line reads:

string input = promptUserInput();

And here's the actual implementation of the promptUserInput function:

```<code>/* Prompts user to enter expression */
string promptUserInput()
{
    string userInput;
    cout << "> ";
    getline(cin, userInput);

    return userInput;
}
</code>```

But when the program runs, it doesn't display the > symbol. Instead, there's an empty line waiting for user input. I enter some arbitrary character, hit Enter, and the > symbol appears afterwards. None of this makes sense to me. What's going on?

答:
std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.

You can also use std::cout << std::endl, which writes a line break and then flushes, but the line break might not satisfy your intention.

Body:
My code is rather simple. I have a method called promptUserInput that is defined in UtilityFunctions.h; it is implemented in UtilityFunctions.cpp.

My main method includes UtilityFunctions.h. I've correctly written my makefile, and it compiles without issue.

My main method's first line reads:

string input = promptUserInput();

And here's the actual implementation of the promptUserInput function:

/* Prompts user to enter expression */
string promptUserInput()
{
    string userInput;
    cout << "> ";
    getline(cin, userInput);

    return userInput;
}

But when the program runs, it doesn't display the > symbol. Instead, there's an empty line waiting for user input. I enter some arbitrary character, hit Enter, and the > symbol appears afterwards. None of this makes sense to me. What's going on?


问:
How to create an array of references
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

```<code>Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a
</code>```

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

答:
A "reference" in Java is what all other languages call a "pointer". Pointers only point to objects; Java also has primitive values of numeric and boolean types. When you assigned 'a' and 'x' to c1, you cause "autoboxing" to insert a pointer to Character.valueOf('a') and Character.valueOf('x'), respectively, into the two slots of c1.

Then c2[0] = c1[0]; put a pointer to Character.valueOf('a') into c2.

Note that c2 does not have any relationship to c1. Changes to one array have no effect on the other. It's just that now c1[0] and c2[0] both point to the Character containing 'a'.

Then c1[0] = 'b'; loads Character.valueOf('b') into c1[0]. Now c1[0] and c2[0] contain different pointers. Changing the pointer in one has no effect on the pointer in the other.

If you had defined an array variable to point to the same array as c1 then you'd affect "both" arrays, since they're really only one array.

```<code>Character[] cX = c1;
c1[0] = 'b'
</code>```

then cX[0] and c1[0], and indeed every index, will point to the same value because they're the same array.

Title: How to create an array of references

Body:
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

Body:
A "reference" in Java is what all other languages call a "pointer". Pointers only point to objects; Java also has primitive values of numeric and boolean types. When you assigned 'a' and 'x' to c1, you cause "autoboxing" to insert a pointer to Character.valueOf('a') and Character.valueOf('x'), respectively, into the two slots of c1.

Then c2[0] = c1[0]; put a pointer to Character.valueOf('a') into c2.

Note that c2 does not have any relationship to c1. Changes to one array have no effect on the other. It's just that now c1[0] and c2[0] both point to the Character containing 'a'.

Then c1[0] = 'b'; loads Character.valueOf('b') into c1[0]. Now c1[0] and c2[0] contain different pointers. Changing the pointer in one has no effect on the pointer in the other.

If you had defined an array variable to point to the same array as c1 then you'd affect "both" arrays, since they're really only one array.

Character[] cX = c1;
c1[0] = 'b'

then cX[0] and c1[0], and indeed every index, will point to the same value because they're the same array.


问:
Export from excel to multiple text files
I have an excel sheet with more than a 1000 rows.
Row are divided into groups like there are some blank rows between each group.
Each first row of a group contains the group title.
How can I save each group to a separate txt file with the file name as the same as the title in the first row of the group.
P.s. all the rows are 1 column only</p>

答:
You can use a loop statement like ForNext, Do-While, While-Wend.

Then you can use the Open method
Open "yourTextFileFullPath" For Append As #1

and "print" or write the lines (the values of each cell) in the .txt file with:
Print #1, cell.value

Then you can close it with
Close #1

And your text file will be filled with te cell values in each line.


问:
C++ Why I make new struct and get error ? (Double linked list circular)
First, I make double linked list circular like this :

1 3 9 11 13

After that, I want to insert 99 after 3. So I must make a variable struct like this :

```<code>node *baru;
baru = new node;
</code>```

BUT the fact Stop there.
Here is my full code :

```<code>#include <iostream>

using namespace std;

struct node
{
    int item;
    node *next;
    node *prev;
};
int main()
{
    node* list = new node;

    list->item = 1;
    list->next->item = 3;
    list->next->next->item = 9;
    list->next->next->next->item = 11;
    list->next->next->next->next->item = 13;
    list->next->next->next->next->next = list;
    list->prev = list->next->next->next->next;
    list->next->prev = list;
    list->next->next->prev = list->next;
    list->next->next->next->prev = list->next->next;
    list->next->next->next->next->prev = list->next->next->next;
    node *bantu = list;

    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;

    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }

    node *baru;
    baru = new node;

    cout << "go !" << endl;

    baru->item = 99;

    baru->next = list->next->next;
    baru->prev = list->next;
    list->next->next = baru;
    list->next->next->next->prev = baru;

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }
    cout << "SELESAI" << endl;
    return 0;
}
</code>```

if successful, the program definitely will output the "go". But in this case, the program does not output the "go". This means that there is an error when creating a new struct. But why is the error?

sorry bad english :D
thanks you

答:
The node* next; pointer is never initialized and is there for not pointing towards any instance of a node. Trying to set a variable inside an non-existing object doesn't make sense and will throw an error. In order to make it work you will have to set next to point to a node before you try to assign next->item a value.

As someone already mentioned you really should consider to implement an insert function. If you want to insert into the last node (which you seem to want according to your code) something like this should work:

```<code>void insert(node* root, int value)
{
    node* temp = root;
    while(temp->next != NULL)
    {
        temp = temp->next;
    }
    temp->next = new node(value);
    temp->next->prev = temp;
}
</code>```

You should also change your node struct to:

```<code>struct node
{
    node(int item)
    {
        this->item = item;
    }
    int item;
    node *next = nullptr;
    node *prev = nullptr;
};
</code>```

Body:
First, I make double linked list circular like this :

1 3 9 11 13

After that, I want to insert 99 after 3. So I must make a variable struct like this :

node *baru;
baru = new node;

BUT the fact Stop there.
Here is my full code :

#include <iostream>

using namespace std;

struct node
{
    int item;
    node *next;
    node *prev;
};
int main()
{
    node* list = new node;

    list->item = 1;
    list->next->item = 3;
    list->next->next->item = 9;
    list->next->next->next->item = 11;
    list->next->next->next->next->item = 13;
    list->next->next->next->next->next = list;
    list->prev = list->next->next->next->next;
    list->next->prev = list;
    list->next->next->prev = list->next;
    list->next->next->next->prev = list->next->next;
    list->next->next->next->next->prev = list->next->next->next;
    node *bantu = list;

    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;

    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }

    node *baru;
    baru = new node;

    cout << "go !" << endl;

    baru->item = 99;

    baru->next = list->next->next;
    baru->prev = list->next;
    list->next->next = baru;
    list->next->next->next->prev = baru;

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }
    cout << "SELESAI" << endl;
    return 0;
}

if successful, the program definitely will output the "go". But in this case, the program does not output the "go". This means that there is an error when creating a new struct. But why is the error?

sorry bad english :D
thanks you

Body:
The node* next; pointer is never initialized and is there for not pointing towards any instance of a node. Trying to set a variable inside an non-existing object doesn't make sense and will throw an error. In order to make it work you will have to set next to point to a node before you try to assign next->item a value.

As someone already mentioned you really should consider to implement an insert function. If you want to insert into the last node (which you seem to want according to your code) something like this should work:

void insert(node* root, int value)
{
    node* temp = root;
    while(temp->next != NULL)
    {
        temp = temp->next;
    }
    temp->next = new node(value);
    temp->next->prev = temp;
}

You should also change your node struct to:

struct node
{
    node(int item)
    {
        this->item = item;
    }
    int item;
    node *next = nullptr;
    node *prev = nullptr;
};


问:
Is there any benefit to using getters/setters inside a class for its own fields?
Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

答:
Some of us are web developers so, we resort to creating JavaBeans and JavaBeans has its own specification. In the specification, it clearly states:

The class must have a public default constructor (no-argument).

The class properties must be accessible using get, set, is (used for boolean properties instead of get) and other methods.

The class should be serializable.

The reason being, JavaBeans were designed for Reusability where JavaBeans could travel through any Java technologies (e.g. Servlets, JSPs, RMI, Web Services, etc.).

That's my 2cent worth on why we have getters/setters. I mostly create JavaBeans.

ContentLicense: CC BY-SA 2.5


问:
python Flask RuntimeError: Working outside of request context
I looked at all related questions but could not found what I want for.
I have a flask app app.py that also includes celery task in it

```<code>from flask import Flask, request, current_app
from celery import Celery
from mongoalchemy.session import Session
from PIL import Image
from model import the_data

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'

celery = Celery('app', broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

@celery.task
def process_image():
    with app.app_context():
        session = Session.connect('mydb')
        session.clear_collection(the_data)
        image = Image.open(request.files['file'])
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay()
    return 'Processing image...'

if __name__ == '__main__':
    app.run(debug=True, port=8008)
</code>```

In short, app.py will receive an image file sent via requests.post from other script and pass it to queue for processing using celery.

I use app.app_context() as what I found out to be the solution for the RuntimeError: Working outside of request context but unfortunately even after I edited my code, the error still there.

What should I do to solve this type of error?

Thank you for your help.

答:
It looks like you can pass *args and **kwargs to your task by including them as arguments in you delay call. Pass the file to your process_image function. The reason this doesn't work is that you're accessing request outside of the context. Once return 'Processing image...' executes that context is closed.

EDIT: Basically, it appears from the documentation that I linked to that you can add an argument to your process_image function and pass it to it in the delay call. This is untested, so it may take some tweaking.

```<code>@celery.task
def process_image(file=None):
    if file is None:
        return False
    image = Image.open(file)
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay(request.files['file'])
    return 'Processing image...'
</code>```

Body:
I looked at all related questions but could not found what I want for.
I have a flask app app.py that also includes celery task in it

from flask import Flask, request, current_app
from celery import Celery
from mongoalchemy.session import Session
from PIL import Image
from model import the_data

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'

celery = Celery('app', broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

@celery.task
def process_image():
    with app.app_context():
        session = Session.connect('mydb')
        session.clear_collection(the_data)
        image = Image.open(request.files['file'])
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay()
    return 'Processing image...'

if __name__ == '__main__':
    app.run(debug=True, port=8008)

In short, app.py will receive an image file sent via requests.post from other script and pass it to queue for processing using celery.

I use app.app_context() as what I found out to be the solution for the RuntimeError: Working outside of request context but unfortunately even after I edited my code, the error still there.

What should I do to solve this type of error?

Thank you for your help.

Body:
It looks like you can pass *args and **kwargs to your task by including them as arguments in you delay call. Pass the file to your process_image function. The reason this doesn't work is that you're accessing request outside of the context. Once return 'Processing image...' executes that context is closed.

EDIT: Basically, it appears from the documentation that I linked to that you can add an argument to your process_image function and pass it to it in the delay call. This is untested, so it may take some tweaking.

@celery.task
def process_image(file=None):
    if file is None:
        return False
    image = Image.open(file)
        ### do something ###

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' in request.files:
            process_image.delay(request.files['file'])
    return 'Processing image...'


问:
Safari (Mac OS X) - Custom extension (or script) with no key / no certificate, only for MY browser
So the situation is something like this:

Pinterest blocks content if you are not a member.

Wired blocks content if you have an ad blocker.

And so on.

Conveniently, you can get rid of said blocks with a few simple CSS overrides.

I'm trying to do one of the following:

Create a Safari extension (WITHOUT a certificate or key)

I've made a couple extensions that work exactly as I'd like (without paying $150 or whatever to become a developer), but the extensions disappear when I close Safari and later reopen it. I then have to go through the Develop>Show Extensions Editor menus and re-install it. Every. Single. Time.

I found this post that said it's to do with the keychain, but mine does not have anthing related to extensions.

I tried adding the custom extension directly to ~/Library/Safari/Extensions/, as well as modifying ~/Library/Safari/Extensions/Extensions.plist to reflect the addition, but that didn't work out. The zipped extension remained in the Extensions folder, but my attempt at modifying the .plist obviously fell short. Probably due to the missing key in the xml for the extension.

I have no interest in publishing these extensions. They are solely to improve my own person user experience. I don't see why I shouldn't be able to install as many of my own custom extensions as I'd like, without the need to fork out cash.

The other option is to write a script, in my local environment (i.e. on my computer), that Safari can call every time the page loads.

It's like it sounds. Either write a custom script that Safari calls after the page has loaded, or modify Safari itself at the source to perform the operations.

I'm not sure how to go about this route. I tried messing around with various applescripts, but I'm still not quite in the right place.

Any thoughts on how I can either a) inject JS into the page or b) override the CSS, all without jumping through hoops and dishing out my month's food.

答:
I think what you want to do is not possible without any certificate.

However, you could use Xcode to create a JS or CSS injecting Safari App Extension. The extension will be signed with an ad-hoc certificate, which only lasts one Safari session. You can replace the ad-hoc certificate with a (free) Mac Development certificate (can be created via Xcode for a limited number of devices, but you'll need a free developer account). Your extension will then be permanent as long as your Mac Development certificate is valid.


问:
Wordpress add code to specific page  tag
I'm on wordpress. I'm trying to add an opengraph tag just to my homepage (my other pages use a plugin to add these tags).

I found this from another question but it doesn't work. I'm pasting this in my header.php file.

```<code>if (is_page('home')) { <meta property="og:image" content="<?php echo $img_src; ?>"/> }
</code>```

答:
You need to validate and check for page using wordpress conditional tags, for more information check this link out https://codex.wordpress.org/Conditional_Tags

For Static Page selected from Administration > Settings > Reading. use is_front_page(). They can be used in template files.

Title: Wordpress add code to specific page <head> tag

Body:
I'm on wordpress. I'm trying to add an opengraph tag just to my homepage (my other pages use a plugin to add these tags).

I found this from another question but it doesn't work. I'm pasting this in my header.php file.

if (is_page('home')) { <meta property="og:image" content="<?php echo $img_src; ?>"/> }


问:
VB - Count how many times a string appears in .CSV file
New user and new coder here.

I am trying to find a way of counting how many times a particular string appears in a .CSV file that is located on the Desktop, and storing that number as a variable for further use.

An example of the .CSV would be:

REF,STATUS,NAME

99991,WordA,CustName1

99992,WordA,CustName2

99993,WordA,CustName3

99994,WordA,CustName4

99995,WordB,CustName5

99996,WordB,CustName6

99997,WordB,CustName7

I basically want to find out how many times WordA appears in the .CSV file, or how many rows in the sheet contain WordA. In my case this figure would be the same.

Any help would be greatly appreciated.

答:
You can put it in a list.

```<code>Dim l As New List(Of String)
l.Add(lines)
Dim i As Integer = l.FindAll(WordA).Count()
</code>```

There are probably 100 ways to do this. It would be more helpful if you attempted a method of doing it and then asked questions on the specific method.

Body:
You can put it in a list.

Dim l As New List(Of String)
l.Add(lines)
Dim i As Integer = l.FindAll(WordA).Count()

There are probably 100 ways to do this. It would be more helpful if you attempted a method of doing it and then asked questions on the specific method.


问:
Rails Accepts Nested Attributes Uniqueness Validations
I've got a simple form that allows managing the positions at a company. I'm using the accepts_nested_attributes API to achieve this. Users are able to add / remove positions using plus / minus buttons and select the user and position for each. The one validation I'd like to enforce is that a user can not have multiple positions for the same company. I enforced this like this:

```<code>class User < ActiveRecord::Base
  has_many :positions
end

class Position < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
  validates :title, presence: true
  validates :user, presence: true
  validates :company, presence: :true
  validates :user, uniqueness: { scope: :company }
end

class Company < ActiveRecord::Base
  has_many :positions
  accepts_nested_attributes_for :positions, allow_destroy: true
end
</code>```

However, I've noticed an error if a person is removed - then re-added to the same company without saving in between. This is sample illustrates the problem:

```<code>company = Company.create(name: "Widgets")
mark = User.create(name: "Mark")
luke = User.create(name: "Luke")
mark_position = Position.create(company: company, user: mark, title: "CTO")
luke_position = Position.create(company: company, user: luke, title: "CFO")

company.positions_attributes = [
  { id: mark_position.id, _destroy: true },
  { id: john_position.id, _destroy: true },
  { user_id: mark.id, title: "CPO" },
  { user_id: john.id, title: "CMO" },
]

company.save!
</code>```

Validation failed: Positions user duplicate position to company for user

Can I do anything to allow changes like these without causing the validations on assignments to fail (I also enforce at the database level - meaning these raise 5xx errors on the server)?

答:
While it isn't pretty - you can potentially override positions_attributes= to re-map your data:

```<code>def positions_attributes=(attributes)
  existing = Array(positions)

  attributes.each do |iteration|
    position = existing.find { |position| position.user_id.eql?(iteration[:user_id]) }
    if position
      attributes.select{ |iteration| iteration[:id].eql?(position.id) }.each{ |iteration| iteration.delete(:id) }
      iteration[:id] = position.id
    end
  end

  super attributes
end
</code>```

Body:
I've got a simple form that allows managing the positions at a company. I'm using the accepts_nested_attributes API to achieve this. Users are able to add / remove positions using plus / minus buttons and select the user and position for each. The one validation I'd like to enforce is that a user can not have multiple positions for the same company. I enforced this like this:

class User < ActiveRecord::Base
  has_many :positions
end

class Position < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
  validates :title, presence: true
  validates :user, presence: true
  validates :company, presence: :true
  validates :user, uniqueness: { scope: :company }
end

class Company < ActiveRecord::Base
  has_many :positions
  accepts_nested_attributes_for :positions, allow_destroy: true
end

However, I've noticed an error if a person is removed - then re-added to the same company without saving in between. This is sample illustrates the problem:

company = Company.create(name: "Widgets")
mark = User.create(name: "Mark")
luke = User.create(name: "Luke")
mark_position = Position.create(company: company, user: mark, title: "CTO")
luke_position = Position.create(company: company, user: luke, title: "CFO")

company.positions_attributes = [
  { id: mark_position.id, _destroy: true },
  { id: john_position.id, _destroy: true },
  { user_id: mark.id, title: "CPO" },
  { user_id: john.id, title: "CMO" },
]

company.save!

Validation failed: Positions user duplicate position to company for user

Can I do anything to allow changes like these without causing the validations on assignments to fail (I also enforce at the database level - meaning these raise 5xx errors on the server)?

Body:
While it isn't pretty - you can potentially override positions_attributes= to re-map your data:

def positions_attributes=(attributes)
  existing = Array(positions)

  attributes.each do |iteration|
    position = existing.find { |position| position.user_id.eql?(iteration[:user_id]) }
    if position
      attributes.select{ |iteration| iteration[:id].eql?(position.id) }.each{ |iteration| iteration.delete(:id) }
      iteration[:id] = position.id
    end
  end

  super attributes
end


问:
ASP.NET GridView control with MySQL - UpdateQuery with spaces in parameters
I have a project I'm making with Visual Studio 2010 and ASP.NET Web Forms. In it, I have a GridView control that I bound to a MySQL table. It displays my table in the control without a problem, but after I enabled editing on the control I found I had problems updating fields in the table when the field has a space in it.

For example, I have the following table defined:

```<code>CREATE TABLE `test_table` (
  `oid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `first_column` varchar(20) NOT NULL,
  `second_column` varchar(20) NOT NULL,
  `third column` varchar(20) NOT NULL,
  PRIMARY KEY (`oid`)
)
</code>```

Note one of the fields has a space in the name. This is where I have problems. In my page, I have the following code:

```<code>    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="oid" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:CommandField ShowEditButton="True" />
            <asp:BoundField DataField="oid" HeaderText="oid" ReadOnly="True"
                SortExpression="oid" />
            <asp:BoundField DataField="first_column" HeaderText="first_column"
                SortExpression="first_column" />
            <asp:BoundField DataField="second_column" HeaderText="second_column"
                SortExpression="second_column" />
            <asp:BoundField DataField="third column" HeaderText="third column"
                SortExpression="third column" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:testcon %>"
        ProviderName="<%$ ConnectionStrings:testcon.ProviderName %>"
        SelectCommand="select * from test_table" UpdateCommand="update `test_table` set
    `first_column`   = @first_column,
    `second_column`  = @second_column
where
    `oid` = @oid"></asp:SqlDataSource>
</code>```

By way of the UpdateCommand, I am able to update first_column and second_column on this table just fine. Now I want it to update third column the same way, but it doesn't work. If I change the query to this:

```<code>update `test_table` set
    `first_column`   = @first_column,
    `second_column`  = @second_column,
    `third column`   = @third column
where
    `oid` = @oid
</code>```

It will give me this error when the query runs:

```<code>Parameter '@third' must be defined.
</code>```

I've also tried @third\ column, @{third column}, @[third column], {@third column} - obviously none of these work. Therefore my question is: what do I put for my update query to be able to update my MySQL field that has a space in it?

答:
A solution to this situation is to provide an alias name to the column in the Select statement that populates the Gridview. For example:

```<code>SELECT ..., [third column] AS third_column, ...
FROM ...
</code>```

And then you can use @third_column as the parameter name. Since I anticipate that you may want to show the column header with a space instead of an underscore, you can set the HeaderText property of this field to what you want.

With this approach, the Update command of the GridView will easily map to the corresponding parameter (since they have the same name) and you don't have to change the definitions in your database. I also recommend using SQLServer Profiler to see the actual T-SQL code that is executed in the server.

Good luck!

Body:
I have a project I'm making with Visual Studio 2010 and ASP.NET Web Forms. In it, I have a GridView control that I bound to a MySQL table. It displays my table in the control without a problem, but after I enabled editing on the control I found I had problems updating fields in the table when the field has a space in it.

For example, I have the following table defined:

CREATE TABLE `test_table` (
  `oid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `first_column` varchar(20) NOT NULL,
  `second_column` varchar(20) NOT NULL,
  `third column` varchar(20) NOT NULL,
  PRIMARY KEY (`oid`)
)

Note one of the fields has a space in the name. This is where I have problems. In my page, I have the following code:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="oid" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:CommandField ShowEditButton="True" />
            <asp:BoundField DataField="oid" HeaderText="oid" ReadOnly="True"
                SortExpression="oid" />
            <asp:BoundField DataField="first_column" HeaderText="first_column"
                SortExpression="first_column" />
            <asp:BoundField DataField="second_column" HeaderText="second_column"
                SortExpression="second_column" />
            <asp:BoundField DataField="third column" HeaderText="third column"
                SortExpression="third column" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:testcon %>"
        ProviderName="<%$ ConnectionStrings:testcon.ProviderName %>"
        SelectCommand="select * from test_table" UpdateCommand="update `test_table` set
    `first_column`   = @first_column,
    `second_column`  = @second_column
where
    `oid` = @oid"></asp:SqlDataSource>

By way of the UpdateCommand, I am able to update first_column and second_column on this table just fine. Now I want it to update third column the same way, but it doesn't work. If I change the query to this:

update `test_table` set
    `first_column`   = @first_column,
    `second_column`  = @second_column,
    `third column`   = @third column
where
    `oid` = @oid

It will give me this error when the query runs:

Parameter '@third' must be defined.

I've also tried @third\ column, @{third column}, @[third column], {@third column} - obviously none of these work. Therefore my question is: what do I put for my update query to be able to update my MySQL field that has a space in it?

Body:
A solution to this situation is to provide an alias name to the column in the Select statement that populates the Gridview. For example:

SELECT ..., [third column] AS third_column, ...
FROM ...

And then you can use @third_column as the parameter name. Since I anticipate that you may want to show the column header with a space instead of an underscore, you can set the HeaderText property of this field to what you want.

With this approach, the Update command of the GridView will easily map to the corresponding parameter (since they have the same name) and you don't have to change the definitions in your database. I also recommend using SQLServer Profiler to see the actual T-SQL code that is executed in the server.

Good luck!


问:
How to chain promises in for loop in vanilla javascript
If I am doing an async call like the following, how can chain them with promises, so i can do stuff in order? In this example, what ends up happening is that arr will push the items out of order. I'd prefer an answer with promises, but anything will do as long as it works

```<code>var fbArrOfAlbumNames = ['Profile Pictures', 'Cover Photos', 'Mobile Uploads'];
var arr = [];
for(var x = 0; x < fbArrOfAlbumNames.length; x++) {
  (function(cntr) {
    FB.api('/' + fbArrOfAlbumNames[cntr] + '/photos/', {fields: 'picture,album'}, function(response) {
      arr.push(response);
    }
  })(x);
}
</code>```

答:
Assuming your ajax calls can actually be run in parallel and you just want the results in order, then you can promisify the ajax function and use Promise.all() to get all the results in order:

```<code>// promisify the ajax call
function fbAPIPromise(path, args) {
    return new Promise(function(resolve, reject) {
        FB.api(path, args, function(results) {
            if (!result) return resolve(null);
            if (result.error) return reject(result.error);
            resolve(result);
        });
    });
}

var promises = [];
for (var x = 0; x < 10; x++) {
     promises.push(fbAPIPromise('/' + fbArrOfAlbumNames[x] + '/photos/', {fields: 'picture,album'});
}
Promise.all(promises).then(function(results) {
     // results is an array of results in original order
}).catch(function(err) {
     // an error occurred
});
</code>```

Body:
If I am doing an async call like the following, how can chain them with promises, so i can do stuff in order? In this example, what ends up happening is that arr will push the items out of order. I'd prefer an answer with promises, but anything will do as long as it works

var fbArrOfAlbumNames = ['Profile Pictures', 'Cover Photos', 'Mobile Uploads'];
var arr = [];
for(var x = 0; x < fbArrOfAlbumNames.length; x++) {
  (function(cntr) {
    FB.api('/' + fbArrOfAlbumNames[cntr] + '/photos/', {fields: 'picture,album'}, function(response) {
      arr.push(response);
    }
  })(x);
}

Body:
Assuming your ajax calls can actually be run in parallel and you just want the results in order, then you can promisify the ajax function and use Promise.all() to get all the results in order:

// promisify the ajax call
function fbAPIPromise(path, args) {
    return new Promise(function(resolve, reject) {
        FB.api(path, args, function(results) {
            if (!result) return resolve(null);
            if (result.error) return reject(result.error);
            resolve(result);
        });
    });
}

var promises = [];
for (var x = 0; x < 10; x++) {
     promises.push(fbAPIPromise('/' + fbArrOfAlbumNames[x] + '/photos/', {fields: 'picture,album'});
}
Promise.all(promises).then(function(results) {
     // results is an array of results in original order
}).catch(function(err) {
     // an error occurred
});


答:
You can't really do that in Java as Java uses pass by value and not pass by reference. Consider the following scenario:

```<code>Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
</code>```

After these lines get executed, 1st element in c1 array points to value a and first element in c2 array points to value \0. Now,

```<code>c2[0] = c1[0];
c1[0] = 'b';
</code>```

After first line gets executed, c2[0] points to the same value as c1[0] (which is a). However, after the second line gets executed, c1[0] points to value b.

This does not change the value of c2[0] as c2[0] was pointing to the value referenced by c1[0] and not the actual c1[0] reference . Hence, c2[0] still points to a and prints a when print statement gets executed.

Title: How to create an array of references

Body:
You can't really do that in Java as Java uses pass by value and not pass by reference. Consider the following scenario:

Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];

After these lines get executed, 1st element in c1 array points to value a and first element in c2 array points to value \0. Now,

c2[0] = c1[0];
c1[0] = 'b';

After first line gets executed, c2[0] points to the same value as c1[0] (which is a). However, after the second line gets executed, c1[0] points to value b.

This does not change the value of c2[0] as c2[0] was pointing to the value referenced by c1[0] and not the actual c1[0] reference . Hence, c2[0] still points to a and prints a when print statement gets executed.


问:
Code studio javascript
So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out. </p>

```<code>setScreen('LogIn');
      var balance;
      var curbal = [];
      var totalAccts=[];
      onEvent("saveAcct", "click", function() {
        var username = getText('createUserInput');
        var password = getText('createPassInput');
        appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
        console.log("Username: " + username + " Password: " + password);
        console.log(totalAccts);
        setScreen('LogIn');
      });

      onEvent('makeAcct', 'click', function(){
        setScreen('CreateAcct');
        setText('createUserInput', "");
        setText('createPassInput', "");
        setText("userInput", "");
        setText("passInput", "");
        hideElement('alert');
      });

      onEvent('addMoney', 'click', function(){
        setNumber('balance', balance + getNumber('addInput'));
        balance = balance + getNumber('addInput');
        setNumber('addInput', '');
        console.log(balance);
      });

      onEvent('subMoney', 'click', function(){
        setNumber('balance', balance - getNumber('subInput'));
        balance = balance - getNumber('subInput');
        setNumber('subInput', '');
        console.log(balance);
      });

      onEvent('login', 'click', function(){
        balance = 0;
        changeEnBal(totalAccts, curbal);
      });

      onEvent('logout', 'click', function(){
        changeExBal(totalAccts, getNumber('balance'), curbal);
        hideElement('alert');
        setText('balance', 0);
        setText("userInput", "");
        setText("passInput", "");
        setScreen('LogIn');
      });

      onEvent("goBack", "click", function() {
        setScreen('LogIn');
      });

      function changeEnBal(list, balList) {
        var user = getText('userInput');
        var pass = getText('passInput');
        for (var i = 0; i < list.length; i++) {
            if (list[i] === (user + " " + pass + " ")) {
              setScreen('Account');
            } else {
              for (var a = 0; a < balList.length; a++) {
              if (list[i] === (user + " " + pass + " " + balList[a])) {
                balance = balList[a];
                setNumber('balance', balList[a]);
                setScreen('Account');
                console.log(balList[a]);
              }
            }
          }
        }

        for (var b = 0; b < balList.length; b++) {
          if (balList[b] != (user + " " + pass + " " + balList[b])){
            showElement('alert');
          }
        }
      }
      function changeExBal(list, curBal, balList) {
        var user = getText('userInput');
        var pass = getText('passInput');
        for (var i = 0; i < list.length; i++) {
            if (list[i] === (user + " " + pass + " ")) {
              list[i] = user + " " + pass + " " + curBal;
              appendItem(curbal, curBal);
              console.log(curbal);
              console.log(list[i]);
            } else {
                for (var a = 0; a < balList.length; a++) {
                if (list[i] === (user + " " + pass + " " + balList[a])) {
                  balList[a] = curbal;
                  list[i] = user + " " + pass + " " + curBal;
                }
              }
            }
        }
        console.log(totalAccts);
      }
</code>```

答:
As suggested in some of the comments I would change your for loops to start with a zero index:

```<code>for (var i = 0; i < list.length; i++)
</code>```

and

```<code>for (var a = 0; a < balList.length; a++)
</code>```

Title: Code studio javascript

Body:
So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.

setScreen('LogIn');
      var balance;
      var curbal = [];
      var totalAccts=[];
      onEvent("saveAcct", "click", function() {
        var username = getText('createUserInput');
        var password = getText('createPassInput');
        appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
        console.log("Username: " + username + " Password: " + password);
        console.log(totalAccts);
        setScreen('LogIn');
      });

      onEvent('makeAcct', 'click', function(){
        setScreen('CreateAcct');
        setText('createUserInput', "");
        setText('createPassInput', "");
        setText("userInput", "");
        setText("passInput", "");
        hideElement('alert');
      });

      onEvent('addMoney', 'click', function(){
        setNumber('balance', balance + getNumber('addInput'));
        balance = balance + getNumber('addInput');
        setNumber('addInput', '');
        console.log(balance);
      });

      onEvent('subMoney', 'click', function(){
        setNumber('balance', balance - getNumber('subInput'));
        balance = balance - getNumber('subInput');
        setNumber('subInput', '');
        console.log(balance);
      });

      onEvent('login', 'click', function(){
        balance = 0;
        changeEnBal(totalAccts, curbal);
      });

      onEvent('logout', 'click', function(){
        changeExBal(totalAccts, getNumber('balance'), curbal);
        hideElement('alert');
        setText('balance', 0);
        setText("userInput", "");
        setText("passInput", "");
        setScreen('LogIn');
      });

      onEvent("goBack", "click", function() {
        setScreen('LogIn');
      });

      function changeEnBal(list, balList) {
        var user = getText('userInput');
        var pass = getText('passInput');
        for (var i = 0; i < list.length; i++) {
            if (list[i] === (user + " " + pass + " ")) {
              setScreen('Account');
            } else {
              for (var a = 0; a < balList.length; a++) {
              if (list[i] === (user + " " + pass + " " + balList[a])) {
                balance = balList[a];
                setNumber('balance', balList[a]);
                setScreen('Account');
                console.log(balList[a]);
              }
            }
          }
        }

        for (var b = 0; b < balList.length; b++) {
          if (balList[b] != (user + " " + pass + " " + balList[b])){
            showElement('alert');
          }
        }
      }
      function changeExBal(list, curBal, balList) {
        var user = getText('userInput');
        var pass = getText('passInput');
        for (var i = 0; i < list.length; i++) {
            if (list[i] === (user + " " + pass + " ")) {
              list[i] = user + " " + pass + " " + curBal;
              appendItem(curbal, curBal);
              console.log(curbal);
              console.log(list[i]);
            } else {
                for (var a = 0; a < balList.length; a++) {
                if (list[i] === (user + " " + pass + " " + balList[a])) {
                  balList[a] = curbal;
                  list[i] = user + " " + pass + " " + curBal;
                }
              }
            }
        }
        console.log(totalAccts);
      }

Body:
As suggested in some of the comments I would change your for loops to start with a zero index:

for (var i = 0; i < list.length; i++)

and

for (var a = 0; a < balList.length; a++)


问:
Static javascript tag with dynamically constructed URL
I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?

```<code><script async src='https://my-known-host.com/script.js?param1=<dynamicValue>'
</script>
</code>```

This parameter is generated on the client and let's say I want it to be just a random number.

I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)

I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)

Is it possible?

答:
```<code><head>
    <script>
            $("head").append($("<script>", {async: true, src: "test.js?params=" + Math.random()}));
    </script>
    <script async src="test.js?params=0.524902342"></script> <!-- parse-able result from the script below -->
</head>
</code>```

Sorry, I provided jQuery, but this or a vanilla approach should get the job done. The trick is to run JavaScript in head that would append  to head.

After the browser runs that, it would parse your parameterized  first.

```<code><script id="randScript" async></script>
<script>
    $("#randScript").prop("src", "test.js" + Math.random()); //jQuery
    document.getElementById("randScript").src = "test.js" + Math.random(); //vanilla
</script>
</code>```

Body:
I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?

This parameter is generated on the client and let's say I want it to be just a random number.

I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)

I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)

Is it possible?

Body:
<head>
    <script>
            $("head").append($("<script>", {async: true, src: "test.js?params=" + Math.random()}));
    </script>
    <script async src="test.js?params=0.524902342"></script> <!-- parse-able result from the script below -->
</head>

Sorry, I provided jQuery, but this or a vanilla approach should get the job done. The trick is to run JavaScript in head that would append <script src="example.js?" + random></script> to head.

After the browser runs that, it would parse your parameterized <script> at the end of the head tag.

I tested it myself and my browser made a request to test.js?params=0.3607864086033945

Hope that solves it!

EDIT:

If you don't want the script to be at the end of head, you can also do this. Very important that you let the browser parse <script id="randScript" async></script> first.

<script id="randScript" async></script>
<script>
    $("#randScript").prop("src", "test.js" + Math.random()); //jQuery
    document.getElementById("randScript").src = "test.js" + Math.random(); //vanilla
</script>


问:
nUnit 3 C# - TestCaseSource - TestCaseData - Testing that exceptions are thrown
In scenarios where I am testing methods that receive more complex objects, I normally use something similar to this to test the method against many test cases:

```<code>[TestFixture()]
public class DataTransmitterFactoryTests
{
    [Test, TestCaseSource(typeof(DataTransmitterFactoryTestCases), "CreateDataTransmitterFactoryTestCases")]
    public void CreateTransmitterForStateTest(bool isException, Type type, IDataConfigurationData config)
    {
        var vtf = new DataTransmitterFactory();
        if (isException)
        {
            Assert.That(() => vtf.CreateTransmitterForState(config), Throws.TypeOf(type));
        }
        else
        {
            var xmitter = vtf.CreateTransmitterForState(config);
            Assert.IsInstanceOf(type, xmitter);
        }
    }
}
</code>```

I use an IEnumerable to feed the test cases into my test:

```<code>public class DataTransmitterFactoryTestCases
{
    public static IEnumerable CreateDataTransmitterFactoryTestCases
    {
        get
        {
            yield return new TestCaseData(false, typeof(DataFileTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.File);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - FileTransmitter");
            yield return new TestCaseData(false, typeof(DataWebServicePostTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.RunMode.Returns(DataRunMode.Production);
                    x.TransmissionType.Returns(DataTransmissionType.WebServicePost);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - WebServicePost");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.RestWebService);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - RestWebService");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.Unknown);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - Unknown");
        }
    }
}
</code>```

However, often, I would like to include a test case that throws an Exception.  In nUnit 2, it appears that you could just add .Throws(typeof(ArgumentException) as an extension method, and the TestCase would look for that.

In this case, I am testing to make sure that the resulting factory object throws an Exception if it gets bad data from the factory.  The resulting object only has an internal constructor.

Now, it appears that nUnit 3 wants you to use "Assert.That(Func..." to test exceptions.  In this case, I would have to have a separate test data source for exceptions.

My hack is to pass bool isException, Type type.. into the method and use an if statement to decide if I am using an Assert.That() or Assert.IsInstance().  This seems pretty hacky, but I have not been able to find a better way.

Is there a better way to feed mixed test data (working / throws an exception) into a test without using the above hack?  Something like:

```<code>public static IEnumerable TestCases
{
    get
    {
        yield return new TestCaseData(xyz).Returns(5);
        yield return new TestCaseData(xyz).Throws(typeof(ArgumentException);
    }
}
</code>```

答:
When we tossed out ExpectedExceptionAttribute in the NUnit 3 design, the Throws property of TestCaseData was collateral damage. Essentially, it allowed doing the same thing as ExpectedException in a TestCase rather than a test.

I won't rehash the reasons why ExpectedExceptionAttribute was removed here - it's discussed at great length in other forums - but I will add that one common theme in all the discussion is that it makes better sense to separate the tests that throw an exception from those that test the happy path.

ContentLicense: CC BY-SA 4.0

Body:
In scenarios where I am testing methods that receive more complex objects, I normally use something similar to this to test the method against many test cases:

[TestFixture()]
public class DataTransmitterFactoryTests
{
    [Test, TestCaseSource(typeof(DataTransmitterFactoryTestCases), "CreateDataTransmitterFactoryTestCases")]
    public void CreateTransmitterForStateTest(bool isException, Type type, IDataConfigurationData config)
    {
        var vtf = new DataTransmitterFactory();
        if (isException)
        {
            Assert.That(() => vtf.CreateTransmitterForState(config), Throws.TypeOf(type));
        }
        else
        {
            var xmitter = vtf.CreateTransmitterForState(config);
            Assert.IsInstanceOf(type, xmitter);
        }
    }
}

I use an IEnumerable to feed the test cases into my test:

public class DataTransmitterFactoryTestCases
{
    public static IEnumerable CreateDataTransmitterFactoryTestCases
    {
        get
        {
            yield return new TestCaseData(false, typeof(DataFileTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.File);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - FileTransmitter");
            yield return new TestCaseData(false, typeof(DataWebServicePostTransmitter),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.RunMode.Returns(DataRunMode.Production);
                    x.TransmissionType.Returns(DataTransmissionType.WebServicePost);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - WebServicePost");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.RestWebService);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - RestWebService");
            yield return new TestCaseData(true, typeof(NotImplementedException),
                FuncMocks.DataConfigurationDataMock(x =>
                {
                    x.DataState.Returns(DataState.PA);
                    x.TransmissionType.Returns(DataTransmissionType.Unknown);
                    return x;
                })).SetName("CreateDataTransmitterFactoryTest - PA - Unknown");
        }
    }
}

However, often, I would like to include a test case that throws an Exception.  In nUnit 2, it appears that you could just add .Throws(typeof(ArgumentException) as an extension method, and the TestCase would look for that.

In this case, I am testing to make sure that the resulting factory object throws an Exception if it gets bad data from the factory.  The resulting object only has an internal constructor.

Now, it appears that nUnit 3 wants you to use "Assert.That(Func..." to test exceptions.  In this case, I would have to have a separate test data source for exceptions.

My hack is to pass bool isException, Type type.. into the method and use an if statement to decide if I am using an Assert.That() or Assert.IsInstance().  This seems pretty hacky, but I have not been able to find a better way.

Is there a better way to feed mixed test data (working / throws an exception) into a test without using the above hack?  Something like:

public static IEnumerable TestCases
{
    get
    {
        yield return new TestCaseData(xyz).Returns(5);
        yield return new TestCaseData(xyz).Throws(typeof(ArgumentException);
    }
}


问:
animation CSS3+jquery
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

```<code><!doctype html>
<html>

  <head>
    <meta charset="UTF-8">
    <title>projekt powazny</title>
    <!--external style-sheet-->
    <link rel="stylesheet" type="text/css" href="css/custom.css">
    <!--external scripts, jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/custom.js"></script>
    <script src="https://use.fontawesome.com/39b504251e.js"></script>
  </head>

  <body>
    <!--header with nav-->
    <header>
      <!--menu-->
      <div id="menu-click">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>
      <!--menu-hidden + add class show on click-->
      <div id="menu-hidden">
      </div>
    </header>
  </body>
</html>

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});
</code>```

答:
I suggest you use transition instead of animation, it is more suitable for this kind of task

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
  transition: left 300ms ease;
}

#menu-hidden.open {
  left: 0;
}</code>```

    ```

Title: animation CSS3+jquery

Body:
https://jsfiddle.net/8953ob8g/

I am a bit confused why the animation doesn't occur BOTH whenever I reveal/close the menu but only when I reveal it? I'd really love to hear some tips regarding the issue, thank you very much in advance for any sort of reply.

<!doctype html>

    <meta charset="UTF-8">
    <title>projekt powazny</title>

    <link rel="stylesheet" type="text/css" href="css/custom.css">

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
}

.open {
  animation: slide-in 300ms ease forwards;
}

@keyframes slide-in {
  0% {
    left: -200px;
  }
  100% {
    left: 0px;
  }
}

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});

Body:
I suggest you use transition instead of animation, it is more suitable for this kind of task

$(document).ready(function() {
  $("#menu-click").click(function() {
    $("#menu-hidden").toggleClass("open");
  });
});

body {
  margin: 0px auto;
  background-color: #233D4D;
}

#menu-click {
  position: absolute;
  right: 30px;
  top: 20px;
  width: 50px;
  height: 50px;
  cursor: pointer;
  font-size: 32px;
  color: white;
}

#menu-hidden {
  position: absolute;
  left: -200px;
  height: 100%;
  background-color: #FE7F2D;
  width: 200px;
  transition: left 300ms ease;
}

#menu-hidden.open {
  left: 0;
}

<script src="https://use.fontawesome.com/39b504251e.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header>
      <!--menu-->
      <div id="menu-click">
        <i class="fa fa-bars" aria-hidden="true"></i>
      </div>

      <!--menu-hidden + add class show on click-->
      <div id="menu-hidden">

      </div>

    </header>


问:
Java quartz scheduler: convert unix cron format to quartz cron format
I want to check if given DateTime matches unix cron format or not. I was trying to use Quartz, but Quartz doesn't support "Day of Month" and "Day of Week" are both "*".

For example:

```<code>0 * * * * * (which means run every minutes) is not supported in Quartz
</code>```

because it must be

```<code>0 * * * * ? or 0 * * ? * *.
</code>```

Can someone tell me why and also tell me how can I match a given DateTime to Unix cron format?

Thanks

答:
Why the cron syntax is different is not a question I can answer, but if all you're looking for is a means to convert from unix to quartz syntax, https://github.com/jmrozanec/cron-utils has helped me in the past.

As far as I know, matching a given date time to a cron syntax is not exactly a simple task, because cron implies a certain frequency of repetition, where as a date/time is a moment in time.

If you're trying to schedule a job to execute once, I suggest using a simple trigger.

If you really want a cron job that executes on some schedule, the above cron-utils library, combined with a cron trigger should do the trick.

Implementations of both triggers (and more) can be found here:
http://www.quartz-scheduler.org/api/2.2.1/index.html

Body:
I want to check if given DateTime matches unix cron format or not. I was trying to use Quartz, but Quartz doesn't support "Day of Month" and "Day of Week" are both "*".

For example:

0 * * * * * (which means run every minutes) is not supported in Quartz

because it must be

0 * * * * ? or 0 * * ? * *.

Can someone tell me why and also tell me how can I match a given DateTime to Unix cron format?

Thanks


问:
Problems with ng-show within ng-repeat
I need to show or hide one item of the list

```<code><div class="row">
    <ul  ng-repeat="event in events">
        <div ng-show="event.name == event.name" ng-model="event.id">
        <p ><a href="list_stand.html#/home/{{event.id}}">{{event.name}}</a> <a ng-click="showScope($event)">show scope</a></p>
        <p>{{ event.address }}</p>
        <p>{{ event.init_date }}</p>
        <p>{{ event.final_date }}</p>
        <p><!--button type="button" name="btnBook2" class="btn btn-primary" ng-click="book()">Book your place</button --></p>
        </div>
    </ul>
    <ul  ng-repeat-end></ul>
</div>
</code>```

How can I access one of this event form the controller, so I can change the variable "event.name", so I can hide?

答:
You can put some variable in your controller like, completedEvent.name = someEvent;

and change your HTML like below:

```<code><div ng-show="completedEvent.name == event.name" ng-model="event.id">
</code>```

Title: Problems with ng-show within ng-repeat

Body:
I need to show or hide one item of the list

{{event.name}} show scope

{{ event.address }}

{{ event.init_date }}

{{ event.final_date }}

How can I access one of this event form the controller, so I can change the variable "event.name", so I can hide?

Body:
You can put some variable in your controller like, completedEvent.name = someEvent;

and change your HTML like below:

<div ng-show="completedEvent.name == event.name" ng-model="event.id">


问:
Search text based on column values and return adjacent rows into a single cell
I need some help with a Google Sheets formula.

My spreadsheet is set up as follows:

The result I need should be like in G2:

IF the text in E:E contains any of the values from A:A then return the corresponding values from B:B into G:G separated by a comma (case insensitive).

Thanks very much!

答:
Try this:

```<code>=join(",",query(filter(A2:B4,arrayformula(regexmatch(LOWER($E$2),lower(A2:A4))),B2:B4),"select Col2"))
</code>```

To return numbers or text use:

=join(",",query(filter(A2:L4,arrayformula(regexmatch(LOWER($E$2),lower(A2:A4)))),"select Col2"))

Body:
Try this:

=join(",",query(filter(A2:B4,arrayformula(regexmatch(LOWER($E$2),lower(A2:A4))),B2:B4),"select Col2"))

To return numbers or text use:

=join(",",query(filter(A2:L4,arrayformula(regexmatch(LOWER($E$2),lower(A2:A4)))),"select Col2"))


问:
How make caching work with pagination and search form?
I working with ruby on rails and my products views is cached and I can find products with search form. I want to use pagination as well, but when added, it didn't worked and also search form. Found code line ,but not sure how to use it, code below.

```<code><% cache ["v1-#{params[:page]-#{params[:q]", cache_key_for_products]
> do %>
</code>```

My code

Index.html.erb

```<code><div class="products">
  <div class="container">
    <center><h1>All products</h1></center>
    <div class="row">
      <% cache(cache_key_for_products) do %>
      <%= render @products %>
      <% end %>
    </div>
    <%= will_paginate @comments, :container => false %>
  </div>
</div>
</code>```

_product.html.erb

```<code><% cache product do %>
<div class="col-md-3 col-lg-3 col-sm-6 col-xs-12">
  <div class="product-block">
    <h4 id="product-name"><%= product.name %></h4>
    <%= link_to product_path(product), class: 'product_link' do %>
      <%= image_tag(product.image_url, class: "img-responsive") %>
    <% end %>
    <div class="price">
      <h4>£ <%= product.price %></h4>
    </div>
  </div>
</div>
<% end %>
</code>```

products_helper.rb

```<code>module ProductsHelper
  def cache_key_for_products
    count          = Product.count
    max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
    "products/#{params[:q] || "all"}-#{count}-#{max_updated_at}#{signed_in? && current_user.admin? ? "-admin" : "normal"}"
  end
end
</code>```

products_controller.rb

```<code>def index
    if params[:q].present?
      search_term = params[:q]
      if Rails.env.development?
        @products = Product.where("name LIKE ?", "%#{search_term}%")
      else
        @products = Product.where("name ilike ?", "%#{search_term}%")
      end
    else
      @products = Product.all.paginate(:page => params[:page], :per_page => 30)
    end
  end
</code>```

答:
In your controller, looks like you are paginating correctly when not performing a search, but need to add the pagination to your search query also:

```<code>  def index
    if params[:q].present?
      search_term = params[:q]
      if Rails.env.development?
        @products = Product.where("name LIKE ?", "%#{search_term}%").paginate(:page => params[:page], :per_page => 30)
      else
        @products = Product.where("name ilike ?", "%#{search_term}%").paginate(:page => params[:page], :per_page => 30)
      end
    else
      @products = Product.all.paginate(:page => params[:page], :per_page => 30)
    end
  end
</code>```

Also you are caching each search result set, this means that the same products could be potentially cached multiple times in many different searches. This will quickly bloat your cache. It would be better to cache each product once and fetch these products from cache regardless of the search.

I see you are caching each product (in _product.html.erb partial). In index.html.erb change the code to this:

```<code><div class="products">
  <div class="container">
    <center><h1>All products</h1></center>
    <div class="row">
      <%= render @products, cache: true %>
    </div>
    <%= will_paginate @comments, :container => false %>
  </div>
</div>
</code>```

This will take advantage of multi fetch fragment caching which Rails 5 has built in:

1.3.1 Collection caching

The render helper can also cache individual templates rendered for a
  collection. It can even one up the previous example with each by
  reading all cache templates at once instead of one by one. This is
  done by passing cached: true when rendering the collection:

<%= render partial: 'products/product', collection: @products, cached:
  true %> All cached templates from previous renders will be fetched at
  once with much greater speed. Additionally, the templates that haven't
  yet been cached will be written to cache and multi fetched on the next
  render.

Otherwise if you are < Rails 5, use the Multi Fetch Fragments gem to enable this functionality.

In index.html.erb you could modify the collection cache rendering to something this to use a custom cache key:

```<code><%= render @products, cache: Proc.new{|item| [item, 'show']} %>
</code>```

Body:
I working with ruby on rails and my products views is cached and I can find products with search form. I want to use pagination as well, but when added, it didn't worked and also search form. Found code line ,but not sure how to use it, code below.

<% cache ["v1-#{params[:page]-#{params[:q]", cache_key_for_products]
> do %>

My code

Index.html.erb

All products

      <% cache(cache_key_for_products) do %>
      <%= render @products %>
      <% end %>

    <%= will_paginate @comments, :container => false %>

_product.html.erb

<% cache product do %>

<%= product.name %>

    <%= link_to product_path(product), class: 'product_link' do %>
      <%= image_tag(product.image_url, class: "img-responsive") %>
    <% end %>

£ <%= product.price %>

<% end %>

products_helper.rb

module ProductsHelper
  def cache_key_for_products
    count          = Product.count
    max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
    "products/#{params[:q] || "all"}-#{count}-#{max_updated_at}#{signed_in? && current_user.admin? ? "-admin" : "normal"}"
  end
end

products_controller.rb

def index
    if params[:q].present?
      search_term = params[:q]
      if Rails.env.development?
        @products = Product.where("name LIKE ?", "%#{search_term}%")
      else
        @products = Product.where("name ilike ?", "%#{search_term}%")
      end
    else
      @products = Product.all.paginate(:page => params[:page], :per_page => 30)
    end
  end

Body:
In your controller, looks like you are paginating correctly when not performing a search, but need to add the pagination to your search query also:

  def index
    if params[:q].present?
      search_term = params[:q]
      if Rails.env.development?
        @products = Product.where("name LIKE ?", "%#{search_term}%").paginate(:page => params[:page], :per_page => 30)
      else
        @products = Product.where("name ilike ?", "%#{search_term}%").paginate(:page => params[:page], :per_page => 30)
      end
    else
      @products = Product.all.paginate(:page => params[:page], :per_page => 30)
    end
  end

Also you are caching each search result set, this means that the same products could be potentially cached multiple times in many different searches. This will quickly bloat your cache. It would be better to cache each product once and fetch these products from cache regardless of the search.

I see you are caching each product (in _product.html.erb partial). In index.html.erb change the code to this:

<div class="products">
  <div class="container">
    <center><h1>All products</h1></center>
    <div class="row">
      <%= render @products, cache: true %>
    </div>
    <%= will_paginate @comments, :container => false %>
  </div>
</div>

This will take advantage of multi fetch fragment caching which Rails 5 has built in:

1.3.1 Collection caching

The render helper can also cache individual templates rendered for a
  collection. It can even one up the previous example with each by
  reading all cache templates at once instead of one by one. This is
  done by passing cached: true when rendering the collection:

<%= render partial: 'products/product', collection: @products, cached:
  true %> All cached templates from previous renders will be fetched at
  once with much greater speed. Additionally, the templates that haven't
  yet been cached will be written to cache and multi fetched on the next
  render.

Otherwise if you are < Rails 5, use the Multi Fetch Fragments gem to enable this functionality.

In index.html.erb you could modify the collection cache rendering to something this to use a custom cache key:

<%= render @products, cache: Proc.new{|item| [item, 'show']} %>


问:
Django - Tag inside a Template tag
So I'm using the django-jcrop plugin to crop an image. Inside my HTML file I have this line:

```<code><img src="{% cropped_thumbnail order 'cropping' max_size='{{ ratio }}' %}">
</code>```

When this is passed, I get the following error:

```<code>TemplateSyntaxError: max_size must match INTxINT
</code>```

{{ ratio }} is passed correctly outside of the tag, and gives the correct intended value, 400x400. When I remove the single quotes from the max_size='{{ ratio }}' I then get the following error:

```<code>TemplateSyntaxError: Could not parse the remainder: '{{' from '{{'
</code>```

So I am pretty sure ratio is not parsing correctly within the tag. Any ideas why?

答:
inside a template tag you don't need to use the "{{}}", you can try the next code:</p>

```<code><img src="{% cropped_thumbnail order 'cropping' max_size=ratio %}">
</code>```

Title: Django - Tag inside a Template tag

Body:
So I'm using the django-jcrop plugin to crop an image. Inside my HTML file I have this line:

When this is passed, I get the following error:

TemplateSyntaxError: max_size must match INTxINT

{{ ratio }} is passed correctly outside of the tag, and gives the correct intended value, 400x400. When I remove the single quotes from the max_size='{{ ratio }}' I then get the following error:

TemplateSyntaxError: Could not parse the remainder: '{{' from '{{'

So I am pretty sure ratio is not parsing correctly within the tag. Any ideas why?

Body:
inside a template tag you don't need to use the "{{}}", you can try the next code:

<img src="{% cropped_thumbnail order 'cropping' max_size=ratio %}">


问:
Yelp Fusion API - Pulling Specific Business Data Using PHP And JSON
I'm trying to figure out how to use the Yelp Fusion API with PHP to return the Yelp rating and location for a specific business.

I've looked for a code sample for the Yelp Fusion Business API in action, but I can't find one. I did find an example for the Yelp Fusion Search API (https://github.com/Yelp/yelp-fusion/blob/master/fusion/php/sample.php), but I'm not a developer and I'm struggling modifying it to work for my needs.

Can someone please show me how to develop a php file that will get the business data for a specific business (pick anyone or use the-crack-shack-encinitas) and how to echo these individual pieces of data (ratings and location)?

Thank you for your time and assistance.

Todd

High School Web Design Teacher and Life Long Learner

Documentation

https://www.yelp.com/developers/documentation/v3/business

答:
I am not sure, but i suspect based on my understanding you might not be using authentication for calling APIs. There might be issues with client_id, token and client secret. Please go through this documentation

https://www.yelp.com/developers/documentation/v3/get_started

and scroll to section Get an access token


问:
C++ Why I make new struct and get error ? (Double linked list circular)
First, I make double linked list circular like this :

1 3 9 11 13

After that, I want to insert 99 after 3. So I must make a variable struct like this :

```<code>node *baru;
baru = new node;
</code>```

BUT the fact Stop there.
Here is my full code :

```<code>#include <iostream>

using namespace std;

struct node
{
    int item;
    node *next;
    node *prev;
};
int main()
{
    node* list = new node;

    list->item = 1;
    list->next->item = 3;
    list->next->next->item = 9;
    list->next->next->next->item = 11;
    list->next->next->next->next->item = 13;
    list->next->next->next->next->next = list;
    list->prev = list->next->next->next->next;
    list->next->prev = list;
    list->next->next->prev = list->next;
    list->next->next->next->prev = list->next->next;
    list->next->next->next->next->prev = list->next->next->next;
    node *bantu = list;

    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;

    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }

    node *baru;
    baru = new node;

    cout << "go !" << endl;

    baru->item = 99;

    baru->next = list->next->next;
    baru->prev = list->next;
    list->next->next = baru;
    list->next->next->next->prev = baru;

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }
    cout << "SELESAI" << endl;
    return 0;
}
</code>```

if successful, the program definitely will output the "go". But in this case, the program does not output the "go". This means that there is an error when creating a new struct. But why is the error?

sorry bad english :D
thanks you

答:
```<code>node *next;
</code>```

declares next to be a pointer to a node. To abuse an old quote, "Pointers gonna point." but it doesn't point to anything useful without help.

```<code>node* list = new node;
</code>```

makes a node pointer named list and points it at a brand-new node. No additional nodes are created so list's next has nowhere to point. That means

```<code>list->next->item = 3;
</code>```

wanders into undefined behaviour trying to access list->next to get the item.

The solution is to make an insert function to create a new node and perform the linking.

```<code>node * insertAfter(node * top, int value)
{
    node * temp = new node;
    temp->item = value;
    temp->next = nullptr; // so we know there is nothing next.
                          // But what if there is something next? Hmmm....
    temp->prev = top;     // point back at top
    top->next = temp;     // point at temp, but what if next already pointed at something?
                          // Wowzers! This is harder than it looks!
    return temp; // return the new node so caller can do something with it if they want
}
</code>```

Body:
First, I make double linked list circular like this :

1 3 9 11 13

After that, I want to insert 99 after 3. So I must make a variable struct like this :

node *baru;
baru = new node;

BUT the fact Stop there.
Here is my full code :

#include <iostream>

using namespace std;

struct node
{
    int item;
    node *next;
    node *prev;
};
int main()
{
    node* list = new node;

    list->item = 1;
    list->next->item = 3;
    list->next->next->item = 9;
    list->next->next->next->item = 11;
    list->next->next->next->next->item = 13;
    list->next->next->next->next->next = list;
    list->prev = list->next->next->next->next;
    list->next->prev = list;
    list->next->next->prev = list->next;
    list->next->next->next->prev = list->next->next;
    list->next->next->next->next->prev = list->next->next->next;
    node *bantu = list;

    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;

    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }

    node *baru;
    baru = new node;

    cout << "go !" << endl;

    baru->item = 99;

    baru->next = list->next->next;
    baru->prev = list->next;
    list->next->next = baru;
    list->next->next->next->prev = baru;

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->next;
    }

    cout << endl;
    bantu = list;
    for (int i = 1; i <= 10; i++)
    {
        cout << bantu->item << endl;
        bantu = bantu->prev;
    }
    cout << "SELESAI" << endl;
    return 0;
}

if successful, the program definitely will output the "go". But in this case, the program does not output the "go". This means that there is an error when creating a new struct. But why is the error?

sorry bad english :D
thanks you

Body:
node *next;

declares next to be a pointer to a node. To abuse an old quote, "Pointers gonna point." but it doesn't point to anything useful without help.

node* list = new node;

makes a node pointer named list and points it at a brand-new node. No additional nodes are created so list's next has nowhere to point. That means

list->next->item = 3;

wanders into undefined behaviour trying to access list->next to get the item.

The solution is to make an insert function to create a new node and perform the linking.

node * insertAfter(node * top, int value)
{
    node * temp = new node;
    temp->item = value;
    temp->next = nullptr; // so we know there is nothing next.
                          // But what if there is something next? Hmmm....
    temp->prev = top;     // point back at top
    top->next = temp;     // point at temp, but what if next already pointed at something?
                          // Wowzers! This is harder than it looks!
    return temp; // return the new node so caller can do something with it if they want
}