问:
SQL time intervals from seperate tables
I have 2 different tables called observations and intervals.

observations:

```<code>id, type, start
----------
1 classroom 2017-06-07 16:18:40
2 classroom 2017-06-01 15:12:00
----------
</code>```

intervals:

```<code>id, observation id, number, task, time
----------
1 1 1 1 2017-06-07 16:18:48
2 1 2 0 2017-06-07 16:18:55
3 1 3 1 2017-06-07 16:19:00
4 2 1 3 2017-06-01 15:12:10
5 2 2 1 2017-06-01 15:12:15
----------
</code>```

I want a view that will display:

observation_id

```<code>time_on_task (total time in seconds where task = 1)
----------
1 13
2 5
----------
</code>```

So I must first check to see if the first observation has task = 1, if it is I must record the difference between the current interval and the start from the observations table, then add that to the total time. From there on after if the task = 1, I just add the time difference from the current interval and previous interval.

I know I can use TIMESTAMPDIFF() or TIMEDIFF() to get the difference in dates.

I believe I will have to use an inner join but do not know the best way to approach this query. Any help would be appreciated.

答:
You can get your expected output by using this query.

```<code>select observation_id, TIME_TO_SEC(TIMEDIFF(max(time),min(time)))
from your_table
group by observation_id
</code>```

Edited as per comment added:

```<code>set @preObservationid= 0;
set @row_number= 0;
set @preTime = '';
select observation_id ,
sum(if(rownumber = 1, TIME_TO_SEC(TIMEDIFF(time,start)) ,TIME_TO_SEC(TIMEDIFF(time,pretime))))
from
( select observation_id, task, rownumber, time, start ,pretime
from ( select observation_id, task, time, start, @preTime as pretime, @preTime:= time,
if(@preObservationid = observation_id, @row_number:= @row_number + 1, @row_number:= 1) as rownumber ,

@preObservationid := observation_id
from observations o join intervals i on o.id = i.observation_id
order by observation_id,time ) innertable
where task = 1 ) final
group by observation_id
</code>```

I hope this will help you. Let me explain logic.

Add rownumber in order to find first record as you said if first
record has task = 1 then we have to use start as time.

Add one more column pretime which is nothing but giving one extra
column with previous date this is used for your seconnd case. if it
is task = 1 but not first record.

Now you have all data to calculate your time.

you can debug at your own by removing each subquery and run it.

There is no need of final subquery you can remove it.

Title: SQL time intervals from seperate tables

Body:
I have 2 different tables called observations and intervals.

observations:

id, type, start
----------
1 classroom 2017-06-07 16:18:40
2 classroom 2017-06-01 15:12:00
----------

intervals:

id, observation id, number, task, time
----------
1 1 1 1 2017-06-07 16:18:48
2 1 2 0 2017-06-07 16:18:55
3 1 3 1 2017-06-07 16:19:00
4 2 1 3 2017-06-01 15:12:10
5 2 2 1 2017-06-01 15:12:15
----------

I want a view that will display:

observation_id

time_on_task (total time in seconds where task = 1)
----------
1 13
2 5
----------

So I must first check to see if the first observation has task = 1, if it is I must record the difference between the current interval and the start from the observations table, then add that to the total time. From there on after if the task = 1, I just add the time difference from the current interval and previous interval.

I know I can use TIMESTAMPDIFF() or TIMEDIFF() to get the difference in dates.

I believe I will have to use an inner join but do not know the best way to approach this query. Any help would be appreciated.

Body:
You can get your expected output by using this query.

select observation_id, TIME_TO_SEC(TIMEDIFF(max(time),min(time)))
from your_table
group by observation_id

Edited as per comment added:

set @preObservationid= 0;
set @row_number= 0;
set @preTime = '';
select observation_id ,
sum(if(rownumber = 1, TIME_TO_SEC(TIMEDIFF(time,start)) ,TIME_TO_SEC(TIMEDIFF(time,pretime))))
from
( select observation_id, task, rownumber, time, start ,pretime
from ( select observation_id, task, time, start, @preTime as pretime, @preTime:= time,
if(@preObservationid = observation_id, @row_number:= @row_number + 1, @row_number:= 1) as rownumber ,

@preObservationid := observation_id
from observations o join intervals i on o.id = i.observation_id
order by observation_id,time ) innertable
where task = 1 ) final
group by observation_id

I hope this will help you. Let me explain logic.

Add rownumber in order to find first record as you said if first
record has task = 1 then we have to use start as time.

Add one more column pretime which is nothing but giving one extra
column with previous date this is used for your seconnd case. if it
is task = 1 but not first record.

Now you have all data to calculate your time.

you can debug at your own by removing each subquery and run it.

There is no need of final subquery you can remove it.


来源: stackexchange

问:
Strings and input files, Assign several variables values from txt file that contains strings
I'm new to programming in C++ and I'm not sure how exactly the input and output stream work. I want to take a txt file, which contains strings and characters that are separated by a delimiter (': '), to assign class member variables.

So far I been able to have a txt file that contains a single double or integer per line and assigned them to variables. Currently what I have:

Current "Default.txt"

10

3

0.80

1.5

The code that I'm currently using for variable assignment:

```<code>#include <iostream>
#include <fstream>

RandomObject::RandomObject(){ //The Default Constructor

std::ifstream my_file;

my_file.open("Default.txt");

//Not sure if this the most effective way to do this...
    if (my_file.is_open())
    {
        while (~my_file.eof())
        {   my_file >> Var1;   //Var1 is now an int with value 10
            my_file >> Var2;   //Var2 is now an int with value 3
            my_file >> Var3;   //Var3 is now double with value 0.80
            my_file >> Var4;   //Var4 is now double with value 1.5
            break;
        }

    }
    my_file.close();
}
</code>```

Now I want the txt file to be:

The new "Default.txt"

Number Per Dimension: 10

Number of Dimensions: 3

Number Density: 0.80

Initial Temperature: 1.5

I want the value after the colon to be assigned to a member variable:

```<code>int Var1 = 10;
int Var2 = 3;
double Var3 = 0.80;
double Var4 = 1.5;
</code>```

and some output text indicating variable intialization of either:

"Variable 1 is set to 10"

or

"Number Per Dimension is 10".

How do I go about doing this? The txt file will have all the values in the same order, although it might be useful to have program read "Number Per Dimension" as the first string to automatically assign 10 to Var1 if thats possible.

I'm guessing the first step is somehow to split it into two strings with ': ' as the delimiter and store it in some temporary string array variable? I'm not sure what exactly is going on with the reading the line and storing the value in my code above.

I would like to understand how the file stream actually works. Sorry that the formatting is bad.

答:
Try something more like this instead:</p>

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

RandomObject::RandomObject() //The Default Constructor
{
    std::ifstream my_file("Default.txt");
    std::string line;

    while (std::getline(my_file, line))
    {
        std::istringstream iss(line);
        std::string name;

        std::getline(iss, name, ':');

        if (name == "Number Per Dimension") {
            iss >> Var1;   //Var1 is now an int with value 10
            std::cout << name << " is " << Var1 << std::endl;
        }

        else if (name == "Number of Dimensions") {
            iss >> Var2;   //Var2 is now an int with value 3
            std::cout << name << " is " << Var2 << std::endl;
        }

        else if (name == "Number Density") {
            iss >> Var3;   //Var3 is now double with value 0.80
            std::cout << name << " is " << Var3 << std::endl;
        }

        else if (name == "Initial Temperature") {
            iss >> Var4;   //Var4 is now double with value 1.5
            std::cout << name << " is " << Var4 << std::endl;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to programming in C++ and I'm not sure how exactly the input and output stream work. I want to take a txt file, which contains strings and characters that are separated by a delimiter (': '), to assign class member variables.

So far I been able to have a txt file that contains a single double or integer per line and assigned them to variables. Currently what I have:

Current "Default.txt"

10

3

0.80

1.5

The code that I'm currently using for variable assignment:

#include <iostream>
#include <fstream>

RandomObject::RandomObject(){ //The Default Constructor

std::ifstream my_file;

my_file.open("Default.txt");

//Not sure if this the most effective way to do this...
    if (my_file.is_open())
    {
        while (~my_file.eof())
        {   my_file >> Var1;   //Var1 is now an int with value 10
            my_file >> Var2;   //Var2 is now an int with value 3
            my_file >> Var3;   //Var3 is now double with value 0.80
            my_file >> Var4;   //Var4 is now double with value 1.5
            break;
        }

    }
    my_file.close();
}

Now I want the txt file to be:

The new "Default.txt"

Number Per Dimension: 10

Number of Dimensions: 3

Number Density: 0.80

Initial Temperature: 1.5

I want the value after the colon to be assigned to a member variable:

int Var1 = 10;
int Var2 = 3;
double Var3 = 0.80;
double Var4 = 1.5;

and some output text indicating variable intialization of either:

"Variable 1 is set to 10"

or

"Number Per Dimension is 10".

How do I go about doing this? The txt file will have all the values in the same order, although it might be useful to have program read "Number Per Dimension" as the first string to automatically assign 10 to Var1 if thats possible.

I'm guessing the first step is somehow to split it into two strings with ': ' as the delimiter and store it in some temporary string array variable? I'm not sure what exactly is going on with the reading the line and storing the value in my code above.

I would like to understand how the file stream actually works. Sorry that the formatting is bad.

Body:
Try something more like this instead:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

RandomObject::RandomObject() //The Default Constructor
{
    std::ifstream my_file("Default.txt");
    std::string line;

    while (std::getline(my_file, line))
    {
        std::istringstream iss(line);
        std::string name;

        std::getline(iss, name, ':');

        if (name == "Number Per Dimension") {
            iss >> Var1;   //Var1 is now an int with value 10
            std::cout << name << " is " << Var1 << std::endl;
        }

        else if (name == "Number of Dimensions") {
            iss >> Var2;   //Var2 is now an int with value 3
            std::cout << name << " is " << Var2 << std::endl;
        }

        else if (name == "Number Density") {
            iss >> Var3;   //Var3 is now double with value 0.80
            std::cout << name << " is " << Var3 << std::endl;
        }

        else if (name == "Initial Temperature") {
            iss >> Var4;   //Var4 is now double with value 1.5
            std::cout << name << " is " << Var4 << std::endl;
        }
    }
}


问:
Replace backward slashes with forwards slashes or double backward slashes in C++
So I have a string:

```<code>string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
</code>```

I want to replace all backward slashes in it with forward ones so it looks like:

```<code>C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug
</code>```

This does not work:

```<code>string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");
</code>```

Obviously, \ is an escape character so that is probably causing the problem.

答:
I get a compiler error on your path string with g++, since it contains invalid escape codes. Apparently, MSVC produces warnings but no errors for that (see Michael Burr's answer). So if you are really using the path you have posted, change the backslashes to double backslashes.

Correcting that, I find that your code replaces only the first backslash and leaves the others. Maybe you want to use std::replace(), like so:

```<code>std::replace(path.begin(), path.end(), '\\', '/');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
So I have a string:

string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

I want to replace all backward slashes in it with forward ones so it looks like:

C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug

This does not work:

string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");

Obviously, \ is an escape character so that is probably causing the problem.

Body:
I get a compiler error on your path string with g++, since it contains invalid escape codes. Apparently, MSVC produces warnings but no errors for that (see Michael Burr's answer). So if you are really using the path you have posted, change the backslashes to double backslashes.

Correcting that, I find that your code replaces only the first backslash and leaves the others. Maybe you want to use std::replace(), like so:

std::replace(path.begin(), path.end(), '\\', '/');


问:
How can I hide a table until filtered/input entered in search
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

```<code>  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
     td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}
</code>```

on a basic search table with this html code:

```<code><input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
   <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
     <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
  <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
</code>```

....and so on.

答:
You could give the table default styles that hide it so when it renders, its default state will be hidden.</p>

```<code><input type="text" id="myInput" onkeyup="ContactsearchFX()" placeholder="Search for names..">

<table id="myTable" style="display:none;">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
   <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
     <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
  <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
</code>```

Body:
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}

on a basic search table with this html code:

<input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

    Name
    Number

    contact
    number

    contact
    number

    contact
    number

....and so on.

Body:
You could give the table default styles that hide it so when it renders, its default state will be hidden.

<input type="text" id="myInput" onkeyup="ContactsearchFX()" placeholder="Search for names..">

<table id="myTable" style="display:none;">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
   <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
     <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
  <tr>
    <td>contact</td>
    <td>number</td>
  </tr>


问:
Wrong button size
I have DialogFragment layout:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white"
android:orientation="vertical"
android:paddingTop="21dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:paddingBottom="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="@string/lbl_why_go_away"
    android:textStyle="bold"
    android:textColor="@color/whyGoAwayCaption"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/fontHuge"
    android:layout_marginBottom="5dp"
    android:layout_marginRight="18dp"
    android:layout_weight="0" />
<ListView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginRight="18dp"
    android:id="@+id/reasonsList" />
<EditText
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="108dp"
    android:layout_marginTop="18dp"
    android:layout_marginRight="18dp"
    android:layout_marginBottom="24dp"
    android:gravity="top|left"
    android:padding="16dp"
    android:background="@drawable/cancel_dialog_your_reason_bg"
    android:hint="@string/ph_your_reason"
    android:layout_weight="0"
    android:id="@+id/otherReasonEditText" />
<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="0"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right">
    <Button
        android:background="#CCCCCC"
        android:text="@string/btn_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/primaryRed"
        android:drawablePadding="0dp"
        android:gravity="center_vertical"
        android:layout_margin="0dp"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:id="@+id/returnButton" />
  <Button
        android:background="#CCCCCC"
        android:text="@string/btn_ready"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:drawablePadding="0dp"
        android:layout_margin="0dp"
        android:textColor="@color/primaryRed"
        android:gravity="center_vertical"
        android:id="@+id/readyButton" />
</LinearLayout>
</code>```

This looks like this (Android 4.2 Galaxy S4):

Problem with buttons size. They should have just padding 8dp around text and nothing else, but they are much bigger then text size. If i set background to @android:color/transparent view is the same. Tell me, what's wrong?

PS: Here's right view (screenshot from preview in VisualStudio)

答: Button has a fixed size. u can't change it. U can make it bigger but can't make it small. As u are using dialog u can use textview instead of button. them do operation with textview. if u want to give a button like shape u can use a LinearLayout and make that layout in a shape ...  </p>

Title: Wrong button size

Body:
I have DialogFragment layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white"
android:orientation="vertical"
android:paddingTop="21dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:paddingBottom="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:text="@string/lbl_why_go_away"
    android:textStyle="bold"
    android:textColor="@color/whyGoAwayCaption"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/fontHuge"
    android:layout_marginBottom="5dp"
    android:layout_marginRight="18dp"
    android:layout_weight="0" />
<ListView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginRight="18dp"
    android:id="@+id/reasonsList" />
<EditText
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="108dp"
    android:layout_marginTop="18dp"
    android:layout_marginRight="18dp"
    android:layout_marginBottom="24dp"
    android:gravity="top|left"
    android:padding="16dp"
    android:background="@drawable/cancel_dialog_your_reason_bg"
    android:hint="@string/ph_your_reason"
    android:layout_weight="0"
    android:id="@+id/otherReasonEditText" />
<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="0"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right">
    <Button
        android:background="#CCCCCC"
        android:text="@string/btn_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/primaryRed"
        android:drawablePadding="0dp"
        android:gravity="center_vertical"
        android:layout_margin="0dp"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:id="@+id/returnButton" />
  <Button
        android:background="#CCCCCC"
        android:text="@string/btn_ready"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="9dp"
        android:paddingRight="9dp"
        android:paddingTop="9dp"
        android:paddingBottom="9dp"
        android:drawablePadding="0dp"
        android:layout_margin="0dp"
        android:textColor="@color/primaryRed"
        android:gravity="center_vertical"
        android:id="@+id/readyButton" />
</LinearLayout>

This looks like this (Android 4.2 Galaxy S4):

Problem with buttons size. They should have just padding 8dp around text and nothing else, but they are much bigger then text size. If i set background to @android:color/transparent view is the same. Tell me, what's wrong?

PS: Here's right view (screenshot from preview in VisualStudio)


问:
Distinct command doesn't work
This is the command:

```<code>SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;
</code>```

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries

答: you have a missing join condition by usual convention.</p>

Title: Distinct command doesn't work

Body:
This is the command:

SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries


问:
Play sounds one after another with loop
I have four audios. Let’s say s1, s2, s3, and s4. I also have a variable with random integers between one and four, for example myVar = [2, 1, 3, 4]. It can be longer or shorter than four, but the integers in it will be always between one and four.

I want to make a cycle which will look on myVar and play my sounds in corresponding order (in this case: s2, s1, s3, s4). One sound after another, that is very important. Not all at once.

All my solutions play the sounds at once so far. I know there are several similar questions, but I am so bad at JavaScript that I was not able to use the answers. Anybody knows how to do it?

One of current solutions (does not work):

```<code>function recTime (i) {

  if (i === myVar.length) return;

  if (myVar[i] === 1) {
    setTimeout(function() {
      s1.play();
      return recTime(++i);
    },350);}
  else if (myVar[i] === 2) {
    setTimeout(function() {
      s2.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 3) {
    setTimeout(function() {
      s3.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 4) {
    setTimeout(function() {
      s4.play();
      return recTime(i++);
    },350);
  }
  }

I call it in this cycle:

  for (var i = 0; i < stimuli.length+1; ++i){
  recTime(i);
  }
</code>```

答:
use onended event to play the next song, something like this:

```<code>var musics = ['s1', 's2', 's3', 's4'];
var order = [2,1,3,4];
var player; //get your audio tag here
player.autoplay = true;

function playNext() {
    var current = order.shift();
    player.src = musics[current];
}

player.addEventListener('ended', playNext);
playNext();
</code>```

Title: Play sounds one after another with loop

Body:
I have four audios. Let’s say s1, s2, s3, and s4. I also have a variable with random integers between one and four, for example myVar = [2, 1, 3, 4]. It can be longer or shorter than four, but the integers in it will be always between one and four.

I want to make a cycle which will look on myVar and play my sounds in corresponding order (in this case: s2, s1, s3, s4). One sound after another, that is very important. Not all at once.

All my solutions play the sounds at once so far. I know there are several similar questions, but I am so bad at JavaScript that I was not able to use the answers. Anybody knows how to do it?

One of current solutions (does not work):

function recTime (i) {

  if (i === myVar.length) return;

  if (myVar[i] === 1) {
    setTimeout(function() {
      s1.play();
      return recTime(++i);
    },350);}
  else if (myVar[i] === 2) {
    setTimeout(function() {
      s2.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 3) {
    setTimeout(function() {
      s3.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 4) {
    setTimeout(function() {
      s4.play();
      return recTime(i++);
    },350);
  }
  }

I call it in this cycle:

  for (var i = 0; i < stimuli.length+1; ++i){
  recTime(i);
  }

Body:
use onended event to play the next song, something like this:

var musics = ['s1', 's2', 's3', 's4'];
var order = [2,1,3,4];
var player; //get your audio tag here
player.autoplay = true;

function playNext() {
    var current = order.shift();
    player.src = musics[current];
}

player.addEventListener('ended', playNext);
playNext();

ContentLicense: CC BY-SA 4.0


问:
When should one use Code contracts that comes with C# 4.0?
I was going through a question on SO which was about new features of c# 4.0 and jon skeet's answer had Code Contracts feature of C# 4.0.. But i really cant understand when to use them.. Any suggestion...</p>

答:
what's really beautiful with contracts is that you don't have to hard wire those ugly argument name strings...</p>

```<code>if(tw == null) throw new ArgumentNullException("tw");
</code>```

Body:
what's really beautiful with contracts is that you don't have to hard wire those ugly argument name strings...

if(tw == null) throw new ArgumentNullException("tw");


问:
Python gives me "None" when trying to print a function
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

```<code>import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()
</code>```

When I get to a fight encoutner with one of the two options, I get

```<code>You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>
</code>```

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.

答:
In Python, when you call a function, that function does its work and then returns a value. For instance,

```<code>def add(x, y):
   print("Working on it...")
   answer = x + y
   print("Got it!")
   return answer
</code>```

When called, this function will do four things. It will print "Working on it..." to the terminal. It will create a variable called answer, and assign it to the sum of x and y. It will print "Got it". And then, it will silently return that answer.

What does return mean? It means two things: it tells Python to return control to the place where the function was called, and it also says: wherever I was called, replace me with a certain value.

So if I write

```<code>print(add(2,3))
</code>```

the function will be called and do its thinking, printing "working" and "got it" to the terminal. It will return 5, so now Python comes back to the print call and replaces add(2, 3) with 5:

```<code>print(5)
</code>```

which will print 5. Similarly, I could do:

```<code> x = add(4,6) + add(5,2)
</code>```

This would print:
     Working on it...
     Got it!
     Working on it...
     Got it!

And then x would be set to 10 + 7, or 17.

In your code, since you don't explicitly return anything from your function, Python uses the default, implicit return of None when it reaches the last line of your function. That means that

```<code> print(MyFunc())
</code>```

actually is understood as, do the function, then

```<code> print(None)
</code>```

Hope that clears things up!

Body:
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()

When I get to a fight encoutner with one of the two options, I get

You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.

Body:
In Python, when you call a function, that function does its work and then returns a value. For instance,

def add(x, y):
   print("Working on it...")
   answer = x + y
   print("Got it!")
   return answer

When called, this function will do four things. It will print "Working on it..." to the terminal. It will create a variable called answer, and assign it to the sum of x and y. It will print "Got it". And then, it will silently return that answer.

What does return mean? It means two things: it tells Python to return control to the place where the function was called, and it also says: wherever I was called, replace me with a certain value.

So if I write

print(add(2,3))

the function will be called and do its thinking, printing "working" and "got it" to the terminal. It will return 5, so now Python comes back to the print call and replaces add(2, 3) with 5:

print(5)

which will print 5. Similarly, I could do:

 x = add(4,6) + add(5,2)

This would print:
     Working on it...
     Got it!
     Working on it...
     Got it!

And then x would be set to 10 + 7, or 17.

In your code, since you don't explicitly return anything from your function, Python uses the default, implicit return of None when it reaches the last line of your function. That means that

 print(MyFunc())

actually is understood as, do the function, then

 print(None)

Hope that clears things up!


问:
How to format only one table with css
I'm trying to select one specific table on one html page to be formatted with css. I do not want any other tables anywhere else, including on the same page, to be formatted this way.

I tried this inside the header but it did not work-

```<code><style>
    #table3 {
        td,th { padding: 10px }
        tr:hover { background-color: #f5f5f5 }
    }
</style>

<table id="table3">
...
</table>
</code>```

答:
The way you wrote it looks more like SCSS. If you need plain CSS, this is how it should look like:</p>

```<code><style>
    #table3 TD {
        padding: 10px;
    }
    #table3 TH {
        padding: 10px;
    }
    #table3 tr:hover {
        background-color: #f5f5f5;
    }
</style>

<table id="table3">
...
</table>
</code>```

Title: How to format only one table with css

Body:
I'm trying to select one specific table on one html page to be formatted with css. I do not want any other tables anywhere else, including on the same page, to be formatted this way.

I tried this inside the header but it did not work-

...

Body:
The way you wrote it looks more like SCSS. If you need plain CSS, this is how it should look like:

<style>
    #table3 TD {
        padding: 10px;
    }
    #table3 TH {
        padding: 10px;
    }
    #table3 tr:hover {
        background-color: #f5f5f5;
    }
</style>

<table id="table3">
...
</table>


问:
sw-precache, cache files with URL Parameters
I have a quick question.

I'm building a PWA with Polymer and Lighthouse reports, that the manifest's start_url is not cached by the ServiceWorker.

Since I want to track the users, which use the 'Add to homescreen' function, my manifest.json contains

"start_url": "index.html?homescreen=1",

I tried putting this exact string into my sw-precache config file, but the script generates a ServiceWorker, that just caches the index.html file.
 (I'm aware, that it's a bit redundant to cache index.html & index.html?homescreen=1)

Do you have any idea, how to fix this behaviour?

Thanks!

答:
The ignoreUrlParametersMatching option is sw-precache can help you here.

By default, it's set to [/^utm_/], meaning that if you configured your Web App Manifest like

```<code>{
  "start_url": "index.html?utm_source=homescreen"
}
</code>```

then things should work as expected. If you'd like to keep that ?homescreen=1, then, when generating your service worker, you can change explicitly set the ignoreUrlParametersMatching parameter to [/^homescreen/].

Body:
The ignoreUrlParametersMatching option is sw-precache can help you here.

By default, it's set to [/^utm_/], meaning that if you configured your Web App Manifest like

{
  "start_url": "index.html?utm_source=homescreen"
}

then things should work as expected. If you'd like to keep that ?homescreen=1, then, when generating your service worker, you can change explicitly set the ignoreUrlParametersMatching parameter to [/^homescreen/].


问:
Redirect from one route to another in Express
I have following routes in nodejs

here is users.js route

```<code>router.post('/users/login', function(request, response) {
    // let user login here and do all of the logic.

    // Once done then redirect user to dashboard in dashboard.js file
    response.redirect('/dashboard');
});
</code>```

here is dashboard.js route

```<code> router.get('/dashboard', function(request, response) {
     response.render('plans');
 });
</code>```

Now when I login as a user when it tries to redirect me it says following.

```<code>cannot get Cannot GET /users/dashboard
</code>```

I want users' to redirect to /dashboard/dashboard instead.

How can I redirect users from one route to another in Express?

答:
I had the same doubt as you had, I came here to look for the answer but found none so I had to do some digging in the docs myself for the solution, and I found one.

Using res.redirect('/dashboard') is taking to the path which is relative to the current route i.e users/dashboard, if you have a separate route for dashboard then you'll have to use it this way:
res.redirect('../dashboard/dashboard')

Just for reference here is my project structure:

```<code>routes/
> index.js
> user_home.js
> users.js
</code>```

Here are the contents of user_home.js:

```<code>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.send("Hello User, welcome to user_home page");
});

router.get('/dashboard', function(req, res, next) {
  res.send("Hello User, this your personal dashboard");
});

module.exports = router;
</code>```

and here is the code from the route from where i am redirecting :

```<code>else {
      console.log("Input validated!");
      res.redirect('../user_home/dashboard');
}
</code>```

Body:
I have following routes in nodejs

here is users.js route

router.post('/users/login', function(request, response) {
    // let user login here and do all of the logic.

    // Once done then redirect user to dashboard in dashboard.js file
    response.redirect('/dashboard');
});

here is dashboard.js route

 router.get('/dashboard', function(request, response) {
     response.render('plans');
 });

Now when I login as a user when it tries to redirect me it says following.

cannot get Cannot GET /users/dashboard

I want users' to redirect to /dashboard/dashboard instead.

How can I redirect users from one route to another in Express?

Body:
I had the same doubt as you had, I came here to look for the answer but found none so I had to do some digging in the docs myself for the solution, and I found one.

Using res.redirect('/dashboard') is taking to the path which is relative to the current route i.e users/dashboard, if you have a separate route for dashboard then you'll have to use it this way:
res.redirect('../dashboard/dashboard')

Just for reference here is my project structure:

routes/
> index.js
> user_home.js
> users.js

Here are the contents of user_home.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.send("Hello User, welcome to user_home page");
});

router.get('/dashboard', function(req, res, next) {
  res.send("Hello User, this your personal dashboard");
});

module.exports = router;

and here is the code from the route from where i am redirecting :

else {
      console.log("Input validated!");
      res.redirect('../user_home/dashboard');
}


问:
Angular2: is there a way to set an input as pristine, by accessing its $event?
I have a form on which I can access its controllers. I can run the markAsPristine method over it.

I can execute this.form.controls.password.markAsPristine(); and all working perfect for me.

The thing is that I want to markAsPristine the input directly when I receive it by an $event. Meaning something like that:

```<code><input
    [formControl]="password"
    type="password" class="form-control
    (input)="checkIfPasswordIsEmpty($event)">

checkIfPasswordIsEmpty(event): void {
    if (event.currentTarget.value === '') {
        this.form.controls.password.markAsPristine();
    }
}
</code>```

Right now, I'm marking the input as pristine by accessing it directly inside the controls object. I wish to avoid calling it specifically, and access it by the $event I receive from the method checkIfPasswordIsEmpty($event).

Does this kind of option exist?

答:
You can use control directive to achieve this. Here is how I did Angular 4, and I believe be similar in 2.

In Template:
    #password="ngModel"

In Component:
    export class SomeComponent {
        @ViewChild('password')
        password: NgModel;

In function that makes pristine:
     this.password.reset()

Body:
I have a form on which I can access its controllers. I can run the markAsPristine method over it.

I can execute this.form.controls.password.markAsPristine(); and all working perfect for me.

The thing is that I want to markAsPristine the input directly when I receive it by an $event. Meaning something like that:

<input
    [formControl]="password"
    type="password" class="form-control
    (input)="checkIfPasswordIsEmpty($event)">

checkIfPasswordIsEmpty(event): void {
    if (event.currentTarget.value === '') {
        this.form.controls.password.markAsPristine();
    }
}

Right now, I'm marking the input as pristine by accessing it directly inside the controls object. I wish to avoid calling it specifically, and access it by the $event I receive from the method checkIfPasswordIsEmpty($event).

Does this kind of option exist?


问:
Where can I get drm contents?
I Developing drm in Cobalt(RC_9). I want to develop and debug drm with drm contents.

where can I get drm contents?

答:
[Summary]
- Purchase movies from "YouTube Movies" channel: https://youtube.com/channel/UClgRkhTL3_hImCAmdLfDE4g
You can also purchase movies from Google Play Movies and watch them on YouTube with the same Google account.
- $0 movie "Sintel" is available: https://youtube.com/watch?v=MeFoUwes8nE
- Contact your YouTube partner manager for free coupons.</p>

Title: Where can I get drm contents?


问:
How can I check if a user's computer supports Emoji?
This question could be generalized to any character, I suppose; but my specific use-case are emoji.

I'm writing a command-line program, and I want to detect if the computer on which it is running has a font installed that can display emoji; and whether the current terminal application will display them in that font.

At the moment, I have a hack in place that simply filters them out on non-OS X; but I don't want to short-change Linux users who have an emoji-enabled setup. I'd prefer to do this the ‘right way.’

Thanks!

答:
Bash

I haven't tried these across environments, so I'm not positive they'll work -- but I think you can make this approach work. The basic approach is to try a hidden render and check if the render was successful. For instance:

```<code>echo -e '\xE0\xA5\xA5' | wc -m
</code>```

wc -m counts the number of characters that are rendered. If you find that failure to render causes your input string to print, then this should be a way to perform an expected length check. If you find that failure to render causes a default symbol to be rendered, then I would suggest piping the output of echo into an equality check:

```<code>echo -e '\xE0\xA5\xA5' | grep -q 'some-default-failure-symbol'
</code>```

A try-fail approach might seem hacky, but I don't think there's a standard for this so it's probably the most robust approach for now.

Node.js

Note: only works in browser, possibly a mock-browser. Not sure how or if a mock-browser would locate a local emoji package, but it's probably an easy thing to check.

There is a node.js module that uses very simple code to check if a system/browser supports an emoji. The code attempts to render the emoji and can tell whether the render was successful.

The npm package is called:
if-emoji

The source code is only a few lines long, and should be easy to understand if you're familiar with javascript (I won't copy and paste the full code here to leave Dafrok with the credit):
https://github.com/Dafrok/if-emoji

Body:
Bash

I haven't tried these across environments, so I'm not positive they'll work -- but I think you can make this approach work. The basic approach is to try a hidden render and check if the render was successful. For instance:

echo -e '\xE0\xA5\xA5' | wc -m

wc -m counts the number of characters that are rendered. If you find that failure to render causes your input string to print, then this should be a way to perform an expected length check. If you find that failure to render causes a default symbol to be rendered, then I would suggest piping the output of echo into an equality check:

echo -e '\xE0\xA5\xA5' | grep -q 'some-default-failure-symbol'

A try-fail approach might seem hacky, but I don't think there's a standard for this so it's probably the most robust approach for now.

Node.js

Note: only works in browser, possibly a mock-browser. Not sure how or if a mock-browser would locate a local emoji package, but it's probably an easy thing to check.

There is a node.js module that uses very simple code to check if a system/browser supports an emoji. The code attempts to render the emoji and can tell whether the render was successful.

The npm package is called:
if-emoji

The source code is only a few lines long, and should be easy to understand if you're familiar with javascript (I won't copy and paste the full code here to leave Dafrok with the credit):
https://github.com/Dafrok/if-emoji


问:
C# creating ".exe" with libraries
I'm using some dlls in my project. To make a '.exe' file i only used 'Released' in Solution Configurations. In my computer exe file works, but in another there's an error: "Can't load file X...". X is a dll file. How can i solve this problem? I copied all dlls into project-bin-realese.</p>

答: If you don't need the dependency on the DLL, then right-click it under "References" in your project and remove it.  If you do need the dependency, then it will need to go to the other computers with the EXE.</p>

Title: C# creating ".exe" with libraries


问:
Updating an array of objects in redux
The initial state looks like this:

```<code>const INITIAL_STATE = {
    myArray: []
};
</code>```

Now in my reducer, I want to append a new object to the existing array.
I came up with something like this but it doesn't work as expected.

```<code>    case ADD_TO_ARRAY:
        return {
            ...state,
            myArray: [...state[ { action.payload.key: action.payload.value} ]]
        };
</code>```

Note: I want to create a new object, in line, using the key and value passed in the action payload.

答:
with ES6 you can have dynamically calculated object keys

just add a variable to be evaluated in square brackets []

```<code>case ADD_TO_ARRAY:
  return {
    ...state,
    myArray: [...state.myArray, [ { [action.payload.key]: action.payload.value} ]]
};
</code>```

Title: Updating an array of objects in redux

Body:
The initial state looks like this:

const INITIAL_STATE = {
    myArray: []
};

Now in my reducer, I want to append a new object to the existing array.
I came up with something like this but it doesn't work as expected.

    case ADD_TO_ARRAY:
        return {
            ...state,
            myArray: [...state[ { action.payload.key: action.payload.value} ]]
        };

Note: I want to create a new object, in line, using the key and value passed in the action payload.

Body:
with ES6 you can have dynamically calculated object keys

just add a variable to be evaluated in square brackets []

case ADD_TO_ARRAY:
  return {
    ...state,
    myArray: [...state.myArray, [ { [action.payload.key]: action.payload.value} ]]
};


问:
Cloud shell via android?
is there anyway to access the google cloud shell on an android device?

Im trying to access the shell to use the given processing vs a vm instance. Although I am not emtirely sure it will process image recognition training any faster. Will it?

答:
I can't think of any ways to access cloud shell on an android device since the there are no compatible browsers and since Cloud Shell is not avaiable via ordinary ssh clients.

And no processing will not be faster since cloud shell uses the smallest instance type

When you start Cloud Shell, it provisions an f1-micro Google Compute Engine virtual machine running a Debian-based Linux operating system. Cloud Shell instances are provisioned on a per-user, per-session basis. The instance persists while your Cloud Shell session is active and terminates after an hour of inactivity.

From here https://cloud.google.com/shell/docs/features

Title: Cloud shell via android?


问:
instagram php scraping (gives error)
I am pretty new to PHP so this may be a dumb question but yeah. I'm trying to get information about a user on instagram with this library: https://github.com/postaddictme/instagram-php-scraper
I've added the library and also the Unirest library so that it should work?

I also have this code in my index.php file:

```<code><?php
require_once dirname(__FILE__) . '/Unirest/Exception.php';
require_once dirname(__FILE__) . '/Unirest/Method.php';
require_once dirname(__FILE__) . '/Unirest/Response.php';
require_once dirname(__FILE__) . '/Unirest/Request.php';
require_once dirname(__FILE__) . '/Unirest/Request/Body.php';
require_once dirname(__FILE__) . '/InstagramScraper/Instagram.php';
require_once dirname(__FILE__) . '/InstagramScraper/Endpoints.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Account.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Comment.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Location.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Media.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Tag.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramAuthException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramNotFoundException.php';
use InstagramScraper\Instagram;
$account = Instagram::getAccountById(272308256);
echo $account->username;

?>
</code>```

But this code does not want to run :/. I keep getting this error:

```<code> Fatal error: Using $this when not in object context in
 C:\xampp\htdocs\Instagramposts\InstagramScraper\Instagram.php on line 313
</code>```

I mean if it's a finished library it should immediately work? Anybody's got a solution?

答:
You need to create an instance of the class (object) first before using the method. The method makes use of the "this" operator which needs an object.
Your code should look like this:</p>

```<code>use InstagramScraper\Instagram;
$insta = new Instagram;
$account = $insta->getAccountById(272308256);
echo $account->username;
</code>```

Title: instagram php scraping (gives error)

Body:
I am pretty new to PHP so this may be a dumb question but yeah. I'm trying to get information about a user on instagram with this library: https://github.com/postaddictme/instagram-php-scraper
I've added the library and also the Unirest library so that it should work?

I also have this code in my index.php file:

<?php
require_once dirname(__FILE__) . '/Unirest/Exception.php';
require_once dirname(__FILE__) . '/Unirest/Method.php';
require_once dirname(__FILE__) . '/Unirest/Response.php';
require_once dirname(__FILE__) . '/Unirest/Request.php';
require_once dirname(__FILE__) . '/Unirest/Request/Body.php';
require_once dirname(__FILE__) . '/InstagramScraper/Instagram.php';
require_once dirname(__FILE__) . '/InstagramScraper/Endpoints.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Account.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Comment.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Location.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Media.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Tag.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramAuthException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramNotFoundException.php';
use InstagramScraper\Instagram;
$account = Instagram::getAccountById(272308256);
echo $account->username;

?>

But this code does not want to run :/. I keep getting this error:

 Fatal error: Using $this when not in object context in
 C:\xampp\htdocs\Instagramposts\InstagramScraper\Instagram.php on line 313

I mean if it's a finished library it should immediately work? Anybody's got a solution?

Body:
You need to create an instance of the class (object) first before using the method. The method makes use of the "this" operator which needs an object.
Your code should look like this:

use InstagramScraper\Instagram;
$insta = new Instagram;
$account = $insta->getAccountById(272308256);
echo $account->username;


问:
C++ Code generation and template specialization
Does a C++ compiler generates code if a function template or a class template is specialized but not actually used? I know it will not, if not specialized (function or class template) and not used.
--Thanks </p>

答: Technically the compiler may choose to eliminate your specialization since it's elimination would not affect the observable behavior of your program. See the as-if rule. Compilers generally provide facilities for exporting symbols such that they are preserved even if unused.</p>


问:
How to create a drop shadow only on one side of an element?
Is there a way to drop the shadow only on the bottom?. I have a menu with 2 images next to each other. I don't want a right shadow because it overlaps the right image. I don't like to use images for this so is there a way to drop it only on the bottom like:

box-shadow-bottom: 10px #FFF; or similar?

```<code>-moz-box-shadow: 0px 3px 3px #000;
-webkit-box-shadow: 0px 3px 3px #000;
box-shadow-bottom: 5px #000;
/* For IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000')";
/* For IE 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000');
</code>```

答:
If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

div {
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<p>Foobar</p>
<p>test</p>
</div></code>```

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.

Body:
Is there a way to drop the shadow only on the bottom?. I have a menu with 2 images next to each other. I don't want a right shadow because it overlaps the right image. I don't like to use images for this so is there a way to drop it only on the bottom like:

box-shadow-bottom: 10px #FFF; or similar?

-moz-box-shadow: 0px 3px 3px #000;
-webkit-box-shadow: 0px 3px 3px #000;
box-shadow-bottom: 5px #000;
/* For IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000')";
/* For IE 5.5 - 7 */
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000');

Body:
If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

div {
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)
}

<div>
<p>Foobar</p>
<p>test</p>
</div>

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.


问:
Why use JS for Image Rollovers When I can use CSS?
I am making my way through Lynda.com's JS tutorial, and they have a whole chapter on image rollevers for buttons.  Why would I use JS when I could just use CSS-- to create image rollevers?</p>

答: Sometimes you want to change a content image on rollover and not a background image (and putting two versions of a content image next to each other then using :hover to hide and show them puts a foot into the realm of "content not making sense without the presentation layer")


问:
Angularfire2 remove all items with matching UserId
I am using angularfire2 in an Ionic App. I am trying to remove from a firebase node all entries that match a user ID. I have a loyalty points node and when I run my reset function I want to remove all entries from the loyaltypoints node related to that user.

I have managed to get all the entries into a variable called 'myPoints' by adding this into my constructor:

this.angularfire.auth.subscribe(res => {
   if (res != null) {
     let userID = res.auth.uid;
     this.af.list('/loyaltypoints', {
        query: {
           orderByChild: 'userId',
           equalTo: userID,
        }
     }).subscribe(response => {
        this.myPoints = response;
     })
   }
})
```

<p>I dont know how to run a remove() function on the this.myPoints variable to remove all these entries now.</p>

<p>thank you</p>

<p><hr>
UPDATE
</p>

<p>So this seems to work for me, first of all import take like so:
import 'rxjs/add/operator/take';</p>

<p>Then this code deletes all the related firebase entries:</p>

```this.angularfire.auth.subscribe(res => {
        if (res != null) {
            let userID = res.auth.uid;
            this.af.list('/loyaltypoints', {
                preserveSnapshot: true,
                query: {
                    orderByChild: 'userId',
                    equalTo: userID,
                }
            }).take(1).subscribe(response => {
                console.log(response)
                response.forEach((snapshot) => {
                    this.af.object('/loyaltypoints/' + snapshot.key).remove();
                })

            })
        }
    })
```

答:
So what you are missing is getting the keys that correspond to each loyaltypoints entry.

```<code>this.angularfire.auth.subscribe(res => {
if (res != null) {
 let userID = res.auth.uid;
 this.af.list('/loyaltypoints', {
    preserveSnapshot: true,
    query: {
       orderByChild: 'userId',
       equalTo: userID,
    }
 }).take(1).subscribe(snaphots=> {
    snapshots.forEach((snapshot) => {
        this.af.object('/loyaltypoints/' + snapshot.key).remove();
    })

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

If you notice I added a take(1) because I if you're changing the node your subscribing too, it triggers a fetch of the data again.  You might have to play with this a little to make sure it's correct.

Body:
I am using angularfire2 in an Ionic App. I am trying to remove from a firebase node all entries that match a user ID. I have a loyalty points node and when I run my reset function I want to remove all entries from the loyaltypoints node related to that user.

I have managed to get all the entries into a variable called 'myPoints' by adding this into my constructor:

this.angularfire.auth.subscribe(res => {
   if (res != null) {
     let userID = res.auth.uid;
     this.af.list('/loyaltypoints', {
        query: {
           orderByChild: 'userId',
           equalTo: userID,
        }
     }).subscribe(response => {
        this.myPoints = response;
     })
   }
})

I dont know how to run a remove() function on the this.myPoints variable to remove all these entries now.

thank you

UPDATE

So this seems to work for me, first of all import take like so:
import 'rxjs/add/operator/take';

Then this code deletes all the related firebase entries:

this.angularfire.auth.subscribe(res => {
        if (res != null) {
            let userID = res.auth.uid;
            this.af.list('/loyaltypoints', {
                preserveSnapshot: true,
                query: {
                    orderByChild: 'userId',
                    equalTo: userID,
                }
            }).take(1).subscribe(response => {
                console.log(response)
                response.forEach((snapshot) => {
                    this.af.object('/loyaltypoints/' + snapshot.key).remove();
                })

            })
        }
    })

Body:
So what you are missing is getting the keys that correspond to each loyaltypoints entry.

this.angularfire.auth.subscribe(res => {
if (res != null) {
 let userID = res.auth.uid;
 this.af.list('/loyaltypoints', {
    preserveSnapshot: true,
    query: {
       orderByChild: 'userId',
       equalTo: userID,
    }
 }).take(1).subscribe(snaphots=> {
    snapshots.forEach((snapshot) => {
        this.af.object('/loyaltypoints/' + snapshot.key).remove();
    })

 })
}
})

If you notice I added a take(1) because I if you're changing the node your subscribing too, it triggers a fetch of the data again.  You might have to play with this a little to make sure it's correct.


问:
ModuleNotFOundError: No module named 'numpy.ma'; 'numpy' is not a package
I have installed Numpy 1.13.0 on Windows 10; however, when I try to execute the following code, it gives the above error

```<code>#!C:\Users\sukhpreet.singh\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
import numpy as np
import matplotlib.pyplot as pp
a = np.array([1,2,3,4,5])
print(a.dtype)
</code>```

Following are the details of error message:

```<code>Traceback (most recent call last):
File "numpyy.py", line 4, in <module>
import numpy as np
File "C:\Users\sukhpreet.singh\Project\numpy.py", line 5, in <module>
import matplotlib.pyplot as pp
File "C:\Users\sukhpreet.singh\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 122, in <module>
from matplotlib.cbook import is_string_like, mplDeprecation, dedent, get_label
File "C:\Users\sukhpreet.singh\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\cbook.py", line 33, in <module>
import numpy.ma as ma
ModuleNotFoundError: No module named 'numpy.ma'; 'numpy' is not a package
</code>```

答:
You also have a module called numpy on python's search path (at C:\Users\sukhpreet.singh\Project\numpy.py).

Unsurprisingly, when matplotlib tries to import numpy.ma it is finding your numpy module, not the library package.

Conclusion: Don't name your modules the same as other packages/libraries you'd like to use.

Body:
I have installed Numpy 1.13.0 on Windows 10; however, when I try to execute the following code, it gives the above error

#!C:\Users\sukhpreet.singh\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
import numpy as np
import matplotlib.pyplot as pp
a = np.array([1,2,3,4,5])
print(a.dtype)

Following are the details of error message:

Traceback (most recent call last):
File "numpyy.py", line 4, in <module>
import numpy as np
File "C:\Users\sukhpreet.singh\Project\numpy.py", line 5, in <module>
import matplotlib.pyplot as pp
File "C:\Users\sukhpreet.singh\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\__init__.py", line 122, in <module>
from matplotlib.cbook import is_string_like, mplDeprecation, dedent, get_label
File "C:\Users\sukhpreet.singh\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\cbook.py", line 33, in <module>
import numpy.ma as ma
ModuleNotFoundError: No module named 'numpy.ma'; 'numpy' is not a package


问:
Silverstripe CMS multiple "success" messages
I'm having this issue on my production server but not in local development:

Loading any page of the CMS (excluding secondary tabs) fires off a "success" notification, sometimes 5-6+ of them at the same time. I can not seem to track down where they're even coming from let alone what's causing them. I'm at such a loss I feel like I'm even having a tough time explaining it so I'll attach a screenshot.

Server is Cloudways PHP stack: 1GB RAM, Apache/Nginx

答:
That's an issue that was already fixed. See this issue on github.

It only happens on SSL/HTTP2 servers, so that explains why you don't get this issue on your local dev environment.

You should be able to solve your problem by updating the CMS.


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

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

public class CalcModel extends Observable
{

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

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

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

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

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

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

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

            return d1 % d2;
            SetUpdate(x);
        }

    };

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

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

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

答:
The error message tells you EXACTLY what you need to do.

class Operation is public , should be
  declared in a file named
  Operation.java

Title: Java object, interface

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

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

public class CalcModel extends Observable
{

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

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

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

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

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

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

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

            return d1 % d2;
            SetUpdate(x);
        }

    };

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

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

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


问:
Access upper class property for List<T> in T class C#
There are my classes:

```<code>public class myClass1
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    private void MyMethod()
    {
        int ParentClass_CodeProperty = ???
    }
}
</code>```

How to access (Code property) in upper (or Parent) class ?

example :

```<code>string ParentClass_CodeProperty = this.Parent.GetType().GetProperty("Code").GetValue(a, null).ToString()
</code>```

答:
Two possible solutions.

First solution is to pass dependency inside your constructor, from the start of class lifetime, just like every IoC framework do:

```<code>public interface IMyClass
{
    int Code {get;}
}
public class myClass1 : IMyClass
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2 : IMyClass
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    //Initialization scope
    private readonly int _parentCode;
    public myItem(IMyClass parent)
    {
       _parentCode = parent.Code;
    }

    //...

    //Execution scope
    private void MyMethod()
    {
        int ParentClass_CodeProperty = _parentCode;
    }
}
</code>```

Second solution is to delegate dependency injection to outer scope and pass it when it actualy needed:

```<code>public class myItem
{
    private void MyMethod(IMyClass parent)
    {
        int ParentClass_CodeProperty = parent.Code;
    }
}

//...

//Initialization scope
var _myItemToParentIndex = new Dictionary<myItem, IMyClass>();

var item = new myItem();
var cl = new myClass2();
myClass2.Items.Add(item);
_myItemToParentIndex.Add(item, myClass2);

//...

//Execution scope
item.MyMethod(_myItemToParentIndex[item]);
</code>```

Other solutions is pretty much more or less similar, like overloading IMyClass with custom AddItem, RemoveItem methods and so on. They just represent how early your dependency will be injected in myItem class.

Body:
There are my classes:

public class myClass1
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    private void MyMethod()
    {
        int ParentClass_CodeProperty = ???
    }
}

How to access (Code property) in upper (or Parent) class ?

example :

string ParentClass_CodeProperty = this.Parent.GetType().GetProperty("Code").GetValue(a, null).ToString()

Body:
Two possible solutions.

First solution is to pass dependency inside your constructor, from the start of class lifetime, just like every IoC framework do:

public interface IMyClass
{
    int Code {get;}
}
public class myClass1 : IMyClass
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2 : IMyClass
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    //Initialization scope
    private readonly int _parentCode;
    public myItem(IMyClass parent)
    {
       _parentCode = parent.Code;
    }

    //...

    //Execution scope
    private void MyMethod()
    {
        int ParentClass_CodeProperty = _parentCode;
    }
}

Second solution is to delegate dependency injection to outer scope and pass it when it actualy needed:

public class myItem
{
    private void MyMethod(IMyClass parent)
    {
        int ParentClass_CodeProperty = parent.Code;
    }
}

//...

//Initialization scope
var _myItemToParentIndex = new Dictionary<myItem, IMyClass>();

var item = new myItem();
var cl = new myClass2();
myClass2.Items.Add(item);
_myItemToParentIndex.Add(item, myClass2);

//...

//Execution scope
item.MyMethod(_myItemToParentIndex[item]);

Other solutions is pretty much more or less similar, like overloading IMyClass with custom AddItem, RemoveItem methods and so on. They just represent how early your dependency will be injected in myItem class.


问:
jQuery resizing code causing perpetual resize event in IE7
This is a bit of JavaScript (jQuery) I wrote that shrinks an element to be as high as possible while still keeping the entire page above the fold. The way it works is essentially "calculate the height difference between the document and the window, and make the element smaller by that much". (see below.)

This works fine as far as I can tell — except that unfortunately I still need IE7 support, and the behavior in that browser is kind of wonky. Specifically, calling my function seems to fire another resize event, causing a kind of feedback loop.

IE7 is apparently the only browser this happens in, and I haven't yet figured out why it happens. I've already tried making the target height smaller to make sure nothing goes out of bounds, but the result is the same.

What's the best way to make my code not fire the resize event in IE7?

```<code>function stretchToBottom($element) {

    (window.onresize = function () {

        // temporarily reset the element's height so $(document).height() yields the right value
        $element.css({maxHeight: ''});

        var heightDiff = $(document).height() - $(window).height();
        if (heightDiff <= 0) {
            return;
        }

        var initialHeight = $element[0].scrollHeight;
        var minHeight = 200;
        var targetHeight = initialHeight - heightDiff;
        var height = Math.max(targetHeight, minHeight);

        $element.css({maxHeight: height + 'px'});

    })();

}
</code>```

答:
wrap your code with:

```<code><!--[if !IE7]>-->
//NONE IE code comes here
<!--<![endif]-->

<!--[if IE7]>
//ONLY IE7 code comes here
<![endif]-->
</code>```

more info here

Body:
This is a bit of JavaScript (jQuery) I wrote that shrinks an element to be as high as possible while still keeping the entire page above the fold. The way it works is essentially "calculate the height difference between the document and the window, and make the element smaller by that much". (see below.)

This works fine as far as I can tell — except that unfortunately I still need IE7 support, and the behavior in that browser is kind of wonky. Specifically, calling my function seems to fire another resize event, causing a kind of feedback loop.

IE7 is apparently the only browser this happens in, and I haven't yet figured out why it happens. I've already tried making the target height smaller to make sure nothing goes out of bounds, but the result is the same.

What's the best way to make my code not fire the resize event in IE7?

function stretchToBottom($element) {

    (window.onresize = function () {

        // temporarily reset the element's height so $(document).height() yields the right value
        $element.css({maxHeight: ''});

        var heightDiff = $(document).height() - $(window).height();
        if (heightDiff <= 0) {
            return;
        }

        var initialHeight = $element[0].scrollHeight;
        var minHeight = 200;
        var targetHeight = initialHeight - heightDiff;
        var height = Math.max(targetHeight, minHeight);

        $element.css({maxHeight: height + 'px'});

    })();

}

Body:
wrap your code with:

<!--[if !IE7]>-->
//NONE IE code comes here
<!--<![endif]-->

<!--[if IE7]>
//ONLY IE7 code comes here
<![endif]-->

more info here


问:
laravel database pass data blade
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

```<code><h2>Your Hashtags</h2>

    <table>
        <tr>
            <th>Hashtag</th>
            <th>List Name</th>
            <th>List Members Added</th>
        </tr>

    @foreach($hashtags as $hashtag)

        <tr>
            <td>{{ $hashtag -> tagname }}</td>
            <td>{{ $hashtag -> listname }}</td>
            <td>Count</td>
        </tr>

    @endforeach

    </table>
</code>```

In my web.php routes file:

```<code>Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});
</code>```

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

答:
Seems like you are not passing $hashtags to your view. I would suggest using compact in your Routes file.
When you are moving to a controller, compact will work just fine there as well.

```<code><h2>Your Hashtags</h2>
<table>
    <tr>
        <th>Hashtag</th>
        <th>List Name</th>
        <th>List Members Added</th>
    </tr>
@foreach($hashtags as $hashtag)
    <tr>
        <td>{{ $hashtag-> tagname }}</td>
        <td>{{ $hashtag-> listname }}</td>
        <td>Count</td>
    </tr>
@endforeach
</table>
</code>```

And your Routes file:

```<code>Route::get('/hashtags', function () {
    $hashtags = DB::table('hashtags')->get();
    return view('hashtags', compact('hashtags'));
});
</code>```

If you have a Hashtag model, you could do like this:
(notice how you use the Hashtag model, rather then DB)

```<code>use App\Hashtag; // Add this at the routes files top

Route::get('/hashtags', function () {
    $hashtags = Hashtag::all();
    return view('hashtags', compact('hashtags'));
});
</code>```

Title: laravel database pass data blade

Body:
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

Your Hashtags

            Hashtag
            List Name
            List Members Added

    @foreach($hashtags as $hashtag)

            {{ $hashtag -> tagname }}
            {{ $hashtag -> listname }}
            Count

    @endforeach

In my web.php routes file:

Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

Body:
Seems like you are not passing $hashtags to your view. I would suggest using compact in your Routes file.
When you are moving to a controller, compact will work just fine there as well.

<h2>Your Hashtags</h2>
<table>
    <tr>
        <th>Hashtag</th>
        <th>List Name</th>
        <th>List Members Added</th>
    </tr>
@foreach($hashtags as $hashtag)
    <tr>
        <td>{{ $hashtag-> tagname }}</td>
        <td>{{ $hashtag-> listname }}</td>
        <td>Count</td>
    </tr>
@endforeach
</table>

And your Routes file:

Route::get('/hashtags', function () {
    $hashtags = DB::table('hashtags')->get();
    return view('hashtags', compact('hashtags'));
});

If you have a Hashtag model, you could do like this:
(notice how you use the Hashtag model, rather then DB)

use App\Hashtag; // Add this at the routes files top

Route::get('/hashtags', function () {
    $hashtags = Hashtag::all();
    return view('hashtags', compact('hashtags'));
});


问:
RowDataPacket value undefined
When I run my code it returns my value as undefined which is strange because if I run the entire array it shows all data.

Here is the code:

```<code>console.log(appid_cards[x].cards);  (returns "undefined")
console.log(appid_cards[x].appid);  (returns "undefined")
console.log(appid_cards[x]);        (returns "appid=", "cards:")
</code>```

for example this happens if I run a specific (existing row) :

```<code>console.log(appid_cards[x].cards);  (returns "undefined")
console.log(appid_cards[x].appid);  (returns "undefined")
console.log(appid_cards[x]);        (returns "appid: 400250, cards: 8")
console.log(x);                     (returns "0")
</code>```

so the X works for the entire RowDataPacket, but if I want to select a key then it somehow doesn't work.

I also check if maybe x would become greated then the number of rows but that is no the case because it is run in a "for" loop and it cannot be greater than appid_cards.length, I can call the entire array but once I start to specify the "cards" or "appid" it returns undefined.

Thanks for the help.

答: Found out that where I pushed the array something went wrong and fixed that piece of code, fixing this as well. Thanks for all the help !</p>

Title: RowDataPacket value undefined

Body:
When I run my code it returns my value as undefined which is strange because if I run the entire array it shows all data.

Here is the code:

console.log(appid_cards[x].cards);  (returns "undefined")
console.log(appid_cards[x].appid);  (returns "undefined")
console.log(appid_cards[x]);        (returns "appid=", "cards:")

for example this happens if I run a specific (existing row) :

console.log(appid_cards[x].cards);  (returns "undefined")
console.log(appid_cards[x].appid);  (returns "undefined")
console.log(appid_cards[x]);        (returns "appid: 400250, cards: 8")
console.log(x);                     (returns "0")

so the X works for the entire RowDataPacket, but if I want to select a key then it somehow doesn't work.

I also check if maybe x would become greated then the number of rows but that is no the case because it is run in a "for" loop and it cannot be greater than appid_cards.length, I can call the entire array but once I start to specify the "cards" or "appid" it returns undefined.

Thanks for the help.


问:
How to Get Github Issues to Linkify a Commit Hash from a Different Repository at Same Organization
If one creates a new GitHub repository, makes a commit with a hash, say, 56a18b4a829473e036f43c14611ab8a7022c500b, then creates an issue in that repository and mentions the hash in the issue comment, GitHub will shorten and linkify the hash.

However, if one includes a hash from a commit in a different repository within the same organization, GitHub does not linkify.

Is it possible to have GitHub Issues automatically linkify these extra-repo hashes?

答: If you just include the full URL of the commit in REPO B in the issue for REPO A, github will link the two automatically. You just can't use the short version. It will look like org/repo@abc123


问:
Django rest framework: Do I really need two separate serializers?
I have an APIView class with post and patch. The serializer for this class is a ModelSerializer.

The thing is: I would like post to require all fields, but patch to allow only a subset of those fields, any subset as long as the field name is legitimate.

Do I really have to create two separate serializers for it? I can't find a way to define those two different behaviors in one.

答: Oh. Duh. By adding partial=True to the serializer declaration, an .update can be partial without errors.


问:
Spring property placeholders in application-context.xml inside dependency jar
For my spring boot application I use annotation based configuration and a WebApplicationInitalizer.

One of my dependencies provides a spring configuration in an xml, included in the jar. I use @ImportResource to load the context xml. This seems to work, except for the fact that inside this xml, there are property placeholders, for example ${poolsize:10}

Apparently, spring does not automatically replace these placeholders (I get a NumberFormatException). Is there some extra configuration I need to add?

Our startup class:

```<code>public class Application implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        // config
        rootContext.register(JmsConfiguration.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));
    }

}
</code>```

And the configuration class (we use spring-jms):

```<code>@Configuration
@EnableJms
@ComponentScan(basePackages = { "..." })
public class JmsConfiguration implements JmsListenerConfigurer {
       // config for jms listener and jaxb, nothing to do with property handling
}
</code>```

Perhaps I'm mistaken in thinking that using a WebapplicationInitializer is how to use spring boot. Perhaps we don't even need spring boot?  The only spring boot related dependency we use is:

```<code><dependency>
    <!-- Import dependency management from Spring Boot -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>1.5.3.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
</code>```

Spring dependencies we use:

```<code>org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-jms:jar:4.3.8.RELEASE:compile
org.springframework:spring-oxm:jar:4.3.8.RELEASE:compile
org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-beans:jar:4.3.8.RELEASE:compile
</code>```

答:
I figured it out thanks @M. Deinum

We don't need spring boot to use the WebApplicationInitializer, but (at least without spring boot) we have to declare our own PropertySourcesPlaceholderConfigurer:

```<code>@Configuration
@ImportResource(locations = {"classpath*:/library-context.xml"})
public class MyConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
</code>```

NB. This works out of the box in spring boot thanks to @EnableAutoConfiguration and @PropertyPlaceholderAutoConfiguration which contains the exact same PropertySourcesPlaceholderConfigurer bean

Body:
For my spring boot application I use annotation based configuration and a WebApplicationInitalizer.

One of my dependencies provides a spring configuration in an xml, included in the jar. I use @ImportResource to load the context xml. This seems to work, except for the fact that inside this xml, there are property placeholders, for example ${poolsize:10}

Apparently, spring does not automatically replace these placeholders (I get a NumberFormatException). Is there some extra configuration I need to add?

Our startup class:

public class Application implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        // config
        rootContext.register(JmsConfiguration.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));
    }

}

And the configuration class (we use spring-jms):

@Configuration
@EnableJms
@ComponentScan(basePackages = { "..." })
public class JmsConfiguration implements JmsListenerConfigurer {
       // config for jms listener and jaxb, nothing to do with property handling
}

Perhaps I'm mistaken in thinking that using a WebapplicationInitializer is how to use spring boot. Perhaps we don't even need spring boot?  The only spring boot related dependency we use is:

<dependency>

    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>1.5.3.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

Spring dependencies we use:

org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-jms:jar:4.3.8.RELEASE:compile
org.springframework:spring-oxm:jar:4.3.8.RELEASE:compile
org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-beans:jar:4.3.8.RELEASE:compile

Body:
I figured it out thanks @M. Deinum

We don't need spring boot to use the WebApplicationInitializer, but (at least without spring boot) we have to declare our own PropertySourcesPlaceholderConfigurer:

@Configuration
@ImportResource(locations = {"classpath*:/library-context.xml"})
public class MyConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

NB. This works out of the box in spring boot thanks to @EnableAutoConfiguration and @PropertyPlaceholderAutoConfiguration which contains the exact same PropertySourcesPlaceholderConfigurer bean


问:
Combining noSQL (Firebase) and SQL for an Android application
so I've finished making a full fledged Android application with which I store data and retrieve on Firebase Database.

However, since there are many joining statements (By using orderByChild and equalTo), the main home screen is very laggy.

The main reason why I'm using Firebase, is because it is a real-time database, however, there is only one screen where that is useful.

Do you think that it's a good idea to keep most of the data on an SQL database and only the data that requires real-time data transfers on Firebase, and will using SQL databases reduce the time it takes to load my home screen?

答:
If you have a SQL background and you want to rewrite your application to use only Firebase, to have a better understanding, please take a look at this tutorial, The Firebase Database For SQL Developers. I asure you, Firebase will handle all your needs.

If don't have time to do this, than use Firebase just for the single activity that you need. If you think that in the future you'll need to make more than one section of your app to use Firebase, than think to change the whole app to use only Firebase.

Hope it helps.