问:
Chrome console - breakpoint over whole file
is there any option to set something like "breakpoint" on a file in chrome console (kindof shortcut to set breakpoint on every line of code in the file)?

Would be extremely useful when trying to understand 3rd party scripts that you know are executed but have no idea which part of code and from where is executed when.

My current example use case: I downloaded a script (form validation) which does not work as expected. The fastest way to solve the problem would be to pause execution anytime JS runtime enters this file and start exploring it from there.

答:
If you know the function(s) being called, you can use function breakpoints

```<code>debug(function);
function(...args);
</code>```

When you call the function, it will hit the breakpoint. These aren't saved on page reload, but you can set a line breakpoint once you hit the function breakpoint.

This can get kinda tedious though.

If you have a array of functions, you can do

```<code>[function0, function1].map(debug)
</code>```

@Tibos answer in another post would be good if there was some sort of babel transform to insert debugger; at the start of every function, instead of inserting it manually.

Body:
If you know the function(s) being called, you can use function breakpoints

debug(function);
function(...args);

When you call the function, it will hit the breakpoint. These aren't saved on page reload, but you can set a line breakpoint once you hit the function breakpoint.

This can get kinda tedious though.

If you have a array of functions, you can do

[function0, function1].map(debug)

@Tibos answer in another post would be good if there was some sort of babel transform to insert debugger; at the start of every function, instead of inserting it manually.


来源: stackexchange

问:
Entity Framework Association Performance
I have the following association.. GroupFile has a one to many relationship with MappedFolders (via the MappedFolder navigation property).

I would expect the next line to do an update:

```<code>groupFile.MappedFolder = _mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();
</code>```

The Query (according to the profiler) is executing this SQL:

```<code>SELECT TOP ( 1 ) [Extent1].[MappedFolderId] AS [MappedFolderId],
                 [Extent1].[FolderPath]     AS [FolderPath],
                 [Extent1].[FolderName]     AS [FolderName],
                 [Extent1].[HotFolder]      AS [HotFolder],
                 [Extent1].[Workstation]    AS [Workstation]
FROM   [dbo].[MappedFolders] AS [Extent1]
WHERE  N'Unassigned' = [Extent1].[FolderName]
</code>```

But according to Entity Framework Profiler, the assignment itself is executing this SQL statement prior to beginning the transaction:

```<code>SELECT [Extent1].[Id]                          AS [Id],
       [Extent1].[Path]                        AS [Path],
       [Extent1].[Status]                      AS [Status],
       [Extent1].[DateAdded]                   AS [DateAdded],
       [Extent1].[DateLastUpdated]             AS [DateLastUpdated],
       [Extent1].[JobSetup_SetupId]            AS [JobSetup_SetupId],
       [Extent1].[Group_GroupId]               AS [Group_GroupId],
       [Extent1].[MappedFolder_MappedFolderId] AS [MappedFolder_MappedFolderId]
FROM   [dbo].[GroupFiles] AS [Extent1]
WHERE  [Extent1].[MappedFolder_MappedFolderId] = 7 /* @EntityKeyValue1 */
</code>```

I must be missing something subtle (or not so subtle) but I'm not sure why that SQL statement is needed....
UPDATE:
Looking further into what the profiler is telling me, the SQL Statement is associated with the following:

```<code>public virtual MappedFolders MappedFolder
{
    get { return _mappedFolder; }
    set
    {
        if (!ReferenceEquals(_mappedFolder, value))
        {
            var previousValue = _mappedFolder;
            _mappedFolder = value;
            FixupMappedFolder(previousValue);
        }
    }
}

private void FixupMappedFolder(MappedFolders previousValue)
{
    if (previousValue != null && previousValue.GroupFiles.Contains(this))
    {
        previousValue.GroupFiles.Remove(this);
    }

    if (MappedFolder != null)
    {
        // THIS IS WHAT THE SQL STATEMENT IS FOR!!!!!
        if (!MappedFolder.GroupFiles.Contains(this))
        {
            MappedFolder.GroupFiles.Add(this);
        }
    }
}
</code>```

The generated code is checking the GroupFiles collection of the mapped folder to see if it has already been added?

答:
You are seeing the select statement used to retrieve the entity associated with this:

```<code>_mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();
</code>```

The assignment to groupFile.MappedFolder doesn't update the database until you call ObjectContext.SaveChanges.  At that point you should see the update statement.

ContentLicense: CC BY-SA 2.5

Body:
I have the following association.. GroupFile has a one to many relationship with MappedFolders (via the MappedFolder navigation property).

I would expect the next line to do an update:

groupFile.MappedFolder = _mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();

The Query (according to the profiler) is executing this SQL:

SELECT TOP ( 1 ) [Extent1].[MappedFolderId] AS [MappedFolderId],
                 [Extent1].[FolderPath]     AS [FolderPath],
                 [Extent1].[FolderName]     AS [FolderName],
                 [Extent1].[HotFolder]      AS [HotFolder],
                 [Extent1].[Workstation]    AS [Workstation]
FROM   [dbo].[MappedFolders] AS [Extent1]
WHERE  N'Unassigned' = [Extent1].[FolderName]

But according to Entity Framework Profiler, the assignment itself is executing this SQL statement prior to beginning the transaction:

SELECT [Extent1].[Id]                          AS [Id],
       [Extent1].[Path]                        AS [Path],
       [Extent1].[Status]                      AS [Status],
       [Extent1].[DateAdded]                   AS [DateAdded],
       [Extent1].[DateLastUpdated]             AS [DateLastUpdated],
       [Extent1].[JobSetup_SetupId]            AS [JobSetup_SetupId],
       [Extent1].[Group_GroupId]               AS [Group_GroupId],
       [Extent1].[MappedFolder_MappedFolderId] AS [MappedFolder_MappedFolderId]
FROM   [dbo].[GroupFiles] AS [Extent1]
WHERE  [Extent1].[MappedFolder_MappedFolderId] = 7 /* @EntityKeyValue1 */

I must be missing something subtle (or not so subtle) but I'm not sure why that SQL statement is needed....
UPDATE:
Looking further into what the profiler is telling me, the SQL Statement is associated with the following:

public virtual MappedFolders MappedFolder
{
    get { return _mappedFolder; }
    set
    {
        if (!ReferenceEquals(_mappedFolder, value))
        {
            var previousValue = _mappedFolder;
            _mappedFolder = value;
            FixupMappedFolder(previousValue);
        }
    }
}

private void FixupMappedFolder(MappedFolders previousValue)
{
    if (previousValue != null && previousValue.GroupFiles.Contains(this))
    {
        previousValue.GroupFiles.Remove(this);
    }

    if (MappedFolder != null)
    {
        // THIS IS WHAT THE SQL STATEMENT IS FOR!!!!!
        if (!MappedFolder.GroupFiles.Contains(this))
        {
            MappedFolder.GroupFiles.Add(this);
        }
    }
}

The generated code is checking the GroupFiles collection of the mapped folder to see if it has already been added?

Body:
You are seeing the select statement used to retrieve the entity associated with this:

_mappedFoldersRepository.Query(m => m.FolderName == "Unassigned").FirstOrDefault();

The assignment to groupFile.MappedFolder doesn't update the database until you call ObjectContext.SaveChanges.  At that point you should see the update statement.


问:
Finding two associated indexes where the sum of two elements equals a target value
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

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

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}
</code>```

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

答:
Your approach is correct but you are forgetting you are in a loop that continues after finding the solution.

This will get you halfway there.  I recommend putting both loops in a function, and returning once you find a match.  One thing you could do is return a pair<int,int> from that function or you could simply output the results from within that point in the loop.

```<code>bool solutionFound = false;
int i,j;

for(i = 0; i < list.size(); i++)
{
    for(j = i+1; j < list.size(); j++)
    {
        if(list[i] + list[j] == target)
        {
            solutionFound = true;
        }
    }
}
</code>```

Here is what the function approach might look like:

```<code>pair<int, int> findSolution(vector<int> list, int target)
{
  for (int i = 0; i < list.size(); i++)
  {
    for (int j = i + 1; j < list.size(); j++)
    {
      if (list[i] + list[j] == target)
      {
        return pair<int, int>(i, j);
      }
    }
  }
  return pair<int, int>(-1, -1);
}

int main() {

  vector<int> list;
  list.push_back(1);
  list.push_back(2);
  list.push_back(3);
  list.push_back(4);
  list.push_back(5);

  int target = 8;
  pair<int, int> results = findSolution(list, target);
  cout << results.first << " " << results.second << "\n";

  return 0;
}
</code>```

Here's the C++ incorporating Dave's answer for linear execution time and a couple helpful comments:

```<code>pair<int, int> findSolution(vector<int> list, int target)
{
  unordered_map<int, int> valueToIndex;
  for (int i = 0; i < list.size(); i++)
  {
    int needed = target - list[i];
    auto it = valueToIndex.find(needed);
    if (it != valueToIndex.end())
    {
      return pair<int, int>(it->second, i);
    }
    valueToIndex.emplace(list[i], i);
  }
  return pair<int, int>(-1, -1);
}

int main()
{
  vector<int> list = { 1,2,3,4,5 };
  int target = 10;
  pair<int, int> results = findSolution(list, target);
  cout << results.first << " " << results.second << "\n";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

Body:
Your approach is correct but you are forgetting you are in a loop that continues after finding the solution.

This will get you halfway there.  I recommend putting both loops in a function, and returning once you find a match.  One thing you could do is return a pair<int,int> from that function or you could simply output the results from within that point in the loop.

bool solutionFound = false;
int i,j;

for(i = 0; i < list.size(); i++)
{
    for(j = i+1; j < list.size(); j++)
    {
        if(list[i] + list[j] == target)
        {
            solutionFound = true;
        }
    }
}

Here is what the function approach might look like:

pair<int, int> findSolution(vector<int> list, int target)
{
  for (int i = 0; i < list.size(); i++)
  {
    for (int j = i + 1; j < list.size(); j++)
    {
      if (list[i] + list[j] == target)
      {
        return pair<int, int>(i, j);
      }
    }
  }
  return pair<int, int>(-1, -1);
}

int main() {

  vector<int> list;
  list.push_back(1);
  list.push_back(2);
  list.push_back(3);
  list.push_back(4);
  list.push_back(5);

  int target = 8;
  pair<int, int> results = findSolution(list, target);
  cout << results.first << " " << results.second << "\n";

  return 0;
}

Here's the C++ incorporating Dave's answer for linear execution time and a couple helpful comments:

pair<int, int> findSolution(vector<int> list, int target)
{
  unordered_map<int, int> valueToIndex;
  for (int i = 0; i < list.size(); i++)
  {
    int needed = target - list[i];
    auto it = valueToIndex.find(needed);
    if (it != valueToIndex.end())
    {
      return pair<int, int>(it->second, i);
    }
    valueToIndex.emplace(list[i], i);
  }
  return pair<int, int>(-1, -1);
}

int main()
{
  vector<int> list = { 1,2,3,4,5 };
  int target = 10;
  pair<int, int> results = findSolution(list, target);
  cout << results.first << " " << results.second << "\n";
}


问:
Gitignore - ignore a specific file from a specific folder
I am new here and I need some help.
I have a website with this structure:

folder1

folder2

folder3

folder4

folder5

index.php

.gitignore

In folder2 there is a config.php file. How can I ignore that file?
I tried to edit .gitignore file and I add folder2/config.php but git doesn't ignore it.

I also tried from Terminal and Source Tree but without success?

Can you please tell me how can I ignore a specific file from a folder?

Many thanks in advance guys!

答:
If the file is already part of git repo, then you need to remove it from git to prevent from further tracking. You can do it by using following command

```<code>git rm --cached folder2/config.php
git commit -m "Removed config file from repo"
git push
</code>```

As for your question in comment, create and add config.php.dist and add it to git

```<code>cp folder2/config.php folder2/config.php.dist
git add folder2/config.php.dist
git commit - m 'adding config.dist to hold bsic config'
git push
</code>```

See my other answer for more detail.
how to specify paths in .gitignore?

Thanks!

Body:
If the file is already part of git repo, then you need to remove it from git to prevent from further tracking. You can do it by using following command

git rm --cached folder2/config.php
git commit -m "Removed config file from repo"
git push

As for your question in comment, create and add config.php.dist and add it to git

cp folder2/config.php folder2/config.php.dist
git add folder2/config.php.dist
git commit - m 'adding config.dist to hold bsic config'
git push

See my other answer for more detail.
how to specify paths in .gitignore?

Thanks!


问:
Where can i get a wiki formatting widget for my django application?
Am looking for a wiki formatting widget for my django application, just like the one am using to type this question in stackoverflow?</p>

答:
Stack Overflow uses WMD for their editing. This is an editor for the Markdown language, which, while not strictly wiki markup, is quite close.

An un-obfuscated Stack Overflow-edition version of WMD is available here.

OwnerDisplayName: gath

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: person-b


问:
Insert query result into table - SQL Server Management Studio
This code works great:

```<code>select month(period)
from fmdr3.dbo.fmdr_2017
</code>```

It returns the number of the month from a date column.

I'm trying to figure out how to insert the results into the table FMDR_2017 in a column called Month.

I've been trying permutations of this:

```<code>insert into fmdr3.dbo.fmdr_2017(Month)
    select month(period)
    from fmdr3.dbo.fmdr_2017
</code>```

but haven't had any success yet.

Thank you.

答:
It sounds like you're trying to update a value in existing records, is that right?

If so, you need something like this:

```<code>UPDATE fmdr3.dbo.fmdr_2017
SET [Month] = month(period)
</code>```

see http://sqlfiddle.com/#!6/7c403/1

Body:
This code works great:

select month(period)
from fmdr3.dbo.fmdr_2017

It returns the number of the month from a date column.

I'm trying to figure out how to insert the results into the table FMDR_2017 in a column called Month.

I've been trying permutations of this:

insert into fmdr3.dbo.fmdr_2017(Month)
    select month(period)
    from fmdr3.dbo.fmdr_2017

but haven't had any success yet.

Thank you.

Body:
It sounds like you're trying to update a value in existing records, is that right?

If so, you need something like this:

UPDATE fmdr3.dbo.fmdr_2017
SET [Month] = month(period)

see http://sqlfiddle.com/#!6/7c403/1


问:
Unable to Call Oracle Stored Procedure from Sqoop
I want to call an Oracle stored procedure from Sqoop but I'm getting an error. I have to call a function of stored procedure and need to pass the parameter.

```<code>$: sqoop import --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --call Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')

-bash: syntax error near unexpected token `('

$: sqoop import --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --call "Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')"

Warning: /opt/cloudera/parcels/CDH-5.4.7-1.cdh5.4.7.p1246.1021/bin/../lib/sqoop/../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.
17/11/27 10:31:31 INFO sqoop.Sqoop: Running Sqoop version: 1.4.5-cdh5.4.7
17/11/27 10:31:32 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Error parsing arguments for import:
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Unrecognized argument: --call
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Unrecognized argument: Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')
</code>```

Can someone please help!

答:
If you stored procedure does some kind of select to import through sqoop-import that will not work, sqoop import doesn't have that flexibility.

But if your stored procedure is doing some kind of clean-up operation you can use the below sqoop eval utility

```<code>sqoop eval --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --query "EXECUTE Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')"
</code>```

--query "will execute the query as if you are running in oracle database, you can use the same SQL syntax that you will use from oracle client application/command line"

Body:
I want to call an Oracle stored procedure from Sqoop but I'm getting an error. I have to call a function of stored procedure and need to pass the parameter.

$: sqoop import --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --call Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')

-bash: syntax error near unexpected token `('

$: sqoop import --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --call "Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')"

Warning: /opt/cloudera/parcels/CDH-5.4.7-1.cdh5.4.7.p1246.1021/bin/../lib/sqoop/../accumulo does not exist! Accumulo imports will fail.
Please set $ACCUMULO_HOME to the root of your Accumulo installation.
17/11/27 10:31:31 INFO sqoop.Sqoop: Running Sqoop version: 1.4.5-cdh5.4.7
17/11/27 10:31:32 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Error parsing arguments for import:
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Unrecognized argument: --call
17/11/27 10:31:32 ERROR tool.BaseSqoopTool: Unrecognized argument: Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')

Can someone please help!

Body:
If you stored procedure does some kind of select to import through sqoop-import that will not work, sqoop import doesn't have that flexibility.

But if your stored procedure is doing some kind of clean-up operation you can use the below sqoop eval utility

sqoop eval --connect jdbc:oracle:thin:@localhost:1512/db --username userA --password password --query "EXECUTE Oracle_Schema.pkg_table_maintenance.sf_drop_index('TBL_A_%','Group_id')"

--query "will execute the query as if you are running in oracle database, you can use the same SQL syntax that you will use from oracle client application/command line"


问:
help with sql server '05 query statement
I'm trying to write a select statement for my autocomplete function(s). I want to take the prefix text from the given text box and pull the first 10 items who's beginning characters matches the prefix. I could probably figure it out on my own, but its getting only the first 10 matches that loses me. Any solutions?</p>

答:
If you have the SQL working to pull the list back from the DB, just add "top 10" to the SQL... like </p>

```<code>SELECT TOP 10 *
FROM EMPLOYEE
WHERE LName like 'Smi%'
</code>```

Body:
If you have the SQL working to pull the list back from the DB, just add "top 10" to the SQL... like

SELECT TOP 10 *
FROM EMPLOYEE
WHERE LName like 'Smi%'


问:
Google Map addCircle above GroundOverlayOptions
I am drawing image on Google Map using

```<code>map.GroundOverlayOptions()
</code>```

Now I am trying to draw circle on this image. I am using

```<code>map.addCircle()
</code>```

But the circle is being drawn under the image. I have also tried to draw circle using Post() of Handler so that it is added later, but it still draws under the image.

答:
Use zIndex() method of Circle and GroundOverlay objects:

The order of overlays with the same zIndex value is arbitrary. This is
  optional and the default zIndex is 0.

Something like that:

```<code>GroundOverlayOptions overlay = new GroundOverlayOptions()
        .image(BitmapDescriptorFactory.fromBitmap(mBitmap))
        .transparency(0f)
        .zIndex(1f)
        .positionFromBounds(borders);

mGoogleMap.addGroundOverlay(overlay);

mGoogleMap.addCircle(new CircleOptions()
        .center(new LatLng(borders.getCenter().latitude, borders.getCenter().longitude))
        .radius(100000)
        .strokeColor(Color.RED)
        .zIndex(2f)
        .fillColor(Color.BLUE));
</code>```

Body:
I am drawing image on Google Map using

map.GroundOverlayOptions()

Now I am trying to draw circle on this image. I am using

map.addCircle()

But the circle is being drawn under the image. I have also tried to draw circle using Post() of Handler so that it is added later, but it still draws under the image.

Body:
Use zIndex() method of Circle and GroundOverlay objects:

The order of overlays with the same zIndex value is arbitrary. This is
  optional and the default zIndex is 0.

Something like that:

GroundOverlayOptions overlay = new GroundOverlayOptions()
        .image(BitmapDescriptorFactory.fromBitmap(mBitmap))
        .transparency(0f)
        .zIndex(1f)
        .positionFromBounds(borders);

mGoogleMap.addGroundOverlay(overlay);

mGoogleMap.addCircle(new CircleOptions()
        .center(new LatLng(borders.getCenter().latitude, borders.getCenter().longitude))
        .radius(100000)
        .strokeColor(Color.RED)
        .zIndex(2f)
        .fillColor(Color.BLUE));


问:
Split rows in limited size buckets
I have a table with thousands of records, I want to associate each row with a bucket and each bucket has a maximum of rows associated to it.

I'd love something a "bucketize" analytic function similar to ntile but that instead of the number of buckets takes the maximum number of elements of each bucket.

Is there anything like that?

```<code>select value, bucketize(3) as bucket
  from table;

VALUE   BUCKET
--------------
foo          1
bar          1
baz          1
qux          2
quux         2
zap          2
xfoo         3
xbar         3
xbaz         3
xqux         4
</code>```

答:
You can just use row_number():

```<code>select value, floor((row_number() over (order by value) - 1) / 3) as bucket
from t;
</code>```

I don't think a separate window function is really needed in this case.

Title: Split rows in limited size buckets

Body:
I have a table with thousands of records, I want to associate each row with a bucket and each bucket has a maximum of rows associated to it.

I'd love something a "bucketize" analytic function similar to ntile but that instead of the number of buckets takes the maximum number of elements of each bucket.

Is there anything like that?

select value, bucketize(3) as bucket
  from table;

VALUE   BUCKET
--------------
foo          1
bar          1
baz          1
qux          2
quux         2
zap          2
xfoo         3
xbar         3
xbaz         3
xqux         4

Body:
You can just use row_number():

select value, floor((row_number() over (order by value) - 1) / 3) as bucket
from t;

I don't think a separate window function is really needed in this case.


问:
Unable to determine composite primary key ordering for type

{"Unable to determine composite primary key ordering for type
  'Conference_Project.Models.Login'. Use the ColumnAttribute (see
  http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method
  (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an
  order for composite primary keys."}

```<code> [Table("ConferenceLogin")]
public class Login
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long confid { get; set; }
    [Key]
    public string emailID { get; set; }
    [Key]
    public string registration { get; set; }
    [Key]
    public long regNo { get; set; }
}
</code>```

```<code>Version Used : EntityFramework.6.1.3  And MVC5
</code>```

I want unique value for this (emailID , registration , regNo ) for that
set all as primary key then EntityFramework showed error

how to use multiple primary key with EntityFramework?

答:
Although I'm not sure as to the underlying logic why this error occurs, I did have the same issue with a project I was working on for class. What worked for me was to add a Column(order) decorator to the Key tag turning

```<code>[Key]
</code>```

into

```<code>[Key, Column(Order = n)]
</code>```

where n is the 0-based index of the key in question.

In this light, your class should look like the following:

```<code>[Table("ConferenceLogin")]
public class Login
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long confid { get; set; }
    [Key, Column(Order = 1)]
    public string emailID { get; set; }
    [Key, Column(Order = 2)]
    public string registration { get; set; }
    [Key, Column(Order = 3)]
    public long regNo { get; set; }
}
</code>```

Hope this works for you as well as it did for me!

Body:
{"Unable to determine composite primary key ordering for type
  'Conference_Project.Models.Login'. Use the ColumnAttribute (see
  http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method
  (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an
  order for composite primary keys."}

 [Table("ConferenceLogin")]
public class Login
{

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long confid { get; set; }
    [Key]
    public string emailID { get; set; }
    [Key]
    public string registration { get; set; }
    [Key]
    public long regNo { get; set; }
}

Version Used : EntityFramework.6.1.3  And MVC5

I want unique value for this (emailID , registration , regNo ) for that
set all as primary key then EntityFramework showed error

how to use multiple primary key with EntityFramework?

Body:
Although I'm not sure as to the underlying logic why this error occurs, I did have the same issue with a project I was working on for class. What worked for me was to add a Column(order) decorator to the Key tag turning

[Key]

into

[Key, Column(Order = n)]

where n is the 0-based index of the key in question.

In this light, your class should look like the following:

[Table("ConferenceLogin")]
public class Login
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long confid { get; set; }
    [Key, Column(Order = 1)]
    public string emailID { get; set; }
    [Key, Column(Order = 2)]
    public string registration { get; set; }
    [Key, Column(Order = 3)]
    public long regNo { get; set; }
}

Hope this works for you as well as it did for me!


问:
php Update function doesn't work
I'm trying to update row in mysql table with php, but for some reason it doesnt work.

I have validation and some checks on the variables and all of them works great, when I var_dump the variable in the php statement everything is great, so I guess the problem is in the query code to mysql. I will be really happy if you can help me!

This is the php part:

```<code>if (isset($_POST['editIdea'])) {
    $editIdea = trim($_POST['editIdea']);
    $editIdea = preg_replace('/[^А–Яа-яА-ЯA-Za-z0-9\. -!?,.@]/u', '', $editIdea);
    $editMoney = trim($_POST['editMoney']);
    $editMoney = preg_replace('/[^0-9\.]/', '', $editMoney);
    $editLong = trim($_POST['editLong']);
    $editLong = preg_replace('/[^А–Яа-яА-ЯA-Za-z0-9\. -!?,.@]/u', '', $editLong);
    $idnow = $_SESSION['id'];
    $error = false;

    if(mb_strlen($editIdea)<3 || mb_strlen($editIdea)>40) {
    echo '<b><p id="wrongname"> *blabla1 </b></p>';
    $error=true;
    }

    if(mb_strlen($editLong)<9 || mb_strlen($editLong)>400) {
    echo '<b><p id="wronglongtext">*blabla2</b></p>';
    $error=true;
    }

    if($editMoney == false) {
    echo '<b><p id="wrongmoney"> *blabla3 </p> </b>';
    $error=true;
    }

    if (!$error){
        var_dump($editIdea);
        var_dump($editMoney);
        var_dump($editLong);
       $sql = "UPDATE `Registration` SET `nameidea` = '$editIdea' , `moneyidea` = '$editMoney' , `explainidea`= '$editLong' WHERE `id` = '$idnow' ";
    }
else {
       echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}
</code>```

So to say again my progress till now:

All var_dumps near the query statement are working great, variables have the information that I want to send.
There are no errors in the php log.
The statement doesn't go in the else, so I can't see any error or more information.

Also, i was trying with and without the "`" near the rows and database names.

Where is my mystake in the query syntax?

Thanks in advance again!

**All the names of the database and rows are correct and double checked.

答:
Add this code after $sql = ....</p>

```<code>$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, $sql)) {
    printf("Error message: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
</code>```

Title: php Update function doesn't work

Body:
I'm trying to update row in mysql table with php, but for some reason it doesnt work.

I have validation and some checks on the variables and all of them works great, when I var_dump the variable in the php statement everything is great, so I guess the problem is in the query code to mysql. I will be really happy if you can help me!

This is the php part:

if (isset($_POST['editIdea'])) {
    $editIdea = trim($_POST['editIdea']);
    $editIdea = preg_replace('/[^А–Яа-яА-ЯA-Za-z0-9\. -!?,.@]/u', '', $editIdea);
    $editMoney = trim($_POST['editMoney']);
    $editMoney = preg_replace('/[^0-9\.]/', '', $editMoney);
    $editLong = trim($_POST['editLong']);
    $editLong = preg_replace('/[^А–Яа-яА-ЯA-Za-z0-9\. -!?,.@]/u', '', $editLong);
    $idnow = $_SESSION['id'];
    $error = false;

    if(mb_strlen($editIdea)<3 || mb_strlen($editIdea)>40) {
    echo '
 *blabla1
';
    $error=true;
    }

    if(mb_strlen($editLong)<9 || mb_strlen($editLong)>400) {
    echo '
*blabla2
';
    $error=true;
    }

    if($editMoney == false) {
    echo '
 *blabla3
 ';
    $error=true;
    }

    if (!$error){
        var_dump($editIdea);
        var_dump($editMoney);
        var_dump($editLong);
       $sql = "UPDATE `Registration` SET `nameidea` = '$editIdea' , `moneyidea` = '$editMoney' , `explainidea`= '$editLong' WHERE `id` = '$idnow' ";
    }
else {
       echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
}

So to say again my progress till now:

All var_dumps near the query statement are working great, variables have the information that I want to send.
There are no errors in the php log.
The statement doesn't go in the else, so I can't see any error or more information.

Also, i was trying with and without the "`" near the rows and database names.

Where is my mystake in the query syntax?

Thanks in advance again!

**All the names of the database and rows are correct and double checked.

Body:
Add this code after $sql = ....

$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, $sql)) {
    printf("Error message: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);


问:
not able to create a dictionary from a one-element list
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

```<code>{Kabul: River Kabul, Tirana: River Tirane, etc}
</code>```

Any help will be really appreciated. Thanks in advance.

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])
</code>```

答:
Code:

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
rivers = soup.select_one("td.sites-layout-tile.sites-tile-name-content-1")

data = [
    div.text.split('-')[1:]
    for div in rivers.find_all('div', style='font-size:small')
    if div.text.strip()
    ][4:-4]
data = {k.strip():v.strip() for k,v in data}

print(data)
</code>```

Steps:

Select the container tag ('tr.sites-layout-tile.sites-tile-name-content-1')

Find all
 children tags, select the text and split by '-'.

Create a dictionary from the items in data.

Body:
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

{Kabul: River Kabul, Tirana: River Tirane, etc}

Any help will be really appreciated. Thanks in advance.

from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])

Body:
Code:

from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
rivers = soup.select_one("td.sites-layout-tile.sites-tile-name-content-1")

data = [
    div.text.split('-')[1:]
    for div in rivers.find_all('div', style='font-size:small')
    if div.text.strip()
    ][4:-4]
data = {k.strip():v.strip() for k,v in data}

print(data)

Steps:

Select the container tag ('tr.sites-layout-tile.sites-tile-name-content-1')

Find all <div style='font-size:small'> children tags, select the text and split by '-'.

Create a dictionary from the items in data.


问:
Wildcards in apache virtualhosts
I try to get my apache (2.4) routing all *.dev requests to the directory /var/www/vhosts/*.dev (softlink)

What i've done:

I created a dnsmasq configuration like this:

```<code>address=/dev/127.0.0.1
</code>```

And i can ping to any *.dev url

```<code>PING something.dev (127.0.53.53) 56(84) bytes of data.
64 bytes from localhost (127.0.53.53): icmp_seq=1 ttl=64 time=0.049 ms
64 bytes from localhost (127.0.53.53): icmp_seq=2 ttl=64 time=0.072 ms
</code>```

So i would say this is working. And the proble is in apache configuration. There is only one site enabled and the vhost_alias mod is also enabled.

```<code><VirtualHost *:80>
VirtualDocumentRoot /var/www/vhosts/%0
VirtualScriptAlias /var/www/vhosts/%0
<Directory />
  Options FollowSymLinks
  AllowOverride None
</Directory>
<Directory /var/www/vhosts/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Require all granted
</Directory>
</code>```

I've created a directory  /var/www/vhosts/test.dev and I expected, that I can browse from the local machine to this url: test.dev

```<code>matthias@matthias-VirtualBox:~$ ls /var/www/vhosts/test.dev/
index.html
</code>```

Edit:
This problem is strange. I can download the index.html with wget http://test.dev But I can't show the page in any browser (tested with chrome and firefox)
Any Ideas?

答: It turns out, that .dev is a new tld. I had to change the order of dns in resolv.conf.</p>

Title: Wildcards in apache virtualhosts

Body:
I try to get my apache (2.4) routing all *.dev requests to the directory /var/www/vhosts/*.dev (softlink)

What i've done:

I created a dnsmasq configuration like this:

address=/dev/127.0.0.1

And i can ping to any *.dev url

PING something.dev (127.0.53.53) 56(84) bytes of data.
64 bytes from localhost (127.0.53.53): icmp_seq=1 ttl=64 time=0.049 ms
64 bytes from localhost (127.0.53.53): icmp_seq=2 ttl=64 time=0.072 ms

So i would say this is working. And the proble is in apache configuration. There is only one site enabled and the vhost_alias mod is also enabled.

<VirtualHost *:80>
VirtualDocumentRoot /var/www/vhosts/%0
VirtualScriptAlias /var/www/vhosts/%0
<Directory />
  Options FollowSymLinks
  AllowOverride None
</Directory>
<Directory /var/www/vhosts/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Require all granted
</Directory>

I've created a directory  /var/www/vhosts/test.dev and I expected, that I can browse from the local machine to this url: test.dev

matthias@matthias-VirtualBox:~$ ls /var/www/vhosts/test.dev/
index.html

Edit:
This problem is strange. I can download the index.html with wget http://test.dev But I can't show the page in any browser (tested with chrome and firefox)
Any Ideas?


问:
Validate html form with javascript after html automatic validation
I have to make a little form with some fields like name, age or email. For example:

```<code><input id="name" type="text" required/>
</code>```

I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:

```<code><input type="submit" value="Submit" onclick="form.validate()" />
</code>```

The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:

```<code>"use strict";
class Form {
    constructor(){}
    validate(){
        alert("validate");
    }
}
var form = new Form();
</code>```

The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?

答:
This method uses jQuery. First you need to prevent the default action on form submit, then you can do your validation, then finally submit the form. Example below.

Your form:

```<code><form id="form">
    <input type="text" required>
    <input type="submit" value="Submit!">
</form>
</code>```

Javascript(with jQuery):

```<code>$('#form').submit(function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    form.validate();
    alert('here');
    this.submit(); // If all the validations succeeded
});
</code>```

JavaScript(vanilla):

```<code>document.getElementById('form').addEventListener('submit', function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    alert('here');
    this.submit(); // If all the validations succeeded
});
</code>```

Body:
I have to make a little form with some fields like name, age or email. For example:

<input id="name" type="text" required/>

I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:

<input type="submit" value="Submit" onclick="form.validate()" />

The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:

"use strict";
class Form {
    constructor(){}
    validate(){
        alert("validate");
    }
}
var form = new Form();

The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?

Body:
This method uses jQuery. First you need to prevent the default action on form submit, then you can do your validation, then finally submit the form. Example below.

Your form:

<form id="form">
    <input type="text" required>
    <input type="submit" value="Submit!">
</form>

Javascript(with jQuery):

$('#form').submit(function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    form.validate();
    alert('here');
    this.submit(); // If all the validations succeeded
});

JavaScript(vanilla):

document.getElementById('form').addEventListener('submit', function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    alert('here');
    this.submit(); // If all the validations succeeded
});


问:
Replacing strings recursively in a Linked list in Java
Trying to create a method that will replace all instances of a string in a linked list with the chosen replacement string.

However, what I've got only seems to check the node chosen by the third argument, and does not recur through the list.

```<code>public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
    }
}
</code>```

Here is the main app:

```<code>public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("red", n4);
        Node n2 = new Node("red", n3);
        Node n1 = new Node("red", n2);

        LinkedList list = new LinkedList(n1);

        System.out.println(list);

        list.replace("red", "RED", n1); // CALLING THE METHOD

        System.out.println(list);

    }
}
</code>```

However the output comes out as:

```<code>RED, red, red, green
</code>```

Not sure what I need to do to make it so it checks every node.

If needed, the node library:

```<code>package lib;

public class Node {
    private String item;
    private Node nextItem;

    public Node(String str, Node n){
        item = str;
        nextItem = n;
    }
    public String getItem(){
        return item;
    }
    public void setItem(String str){
        item = str;
    }
    public Node next(){
        return nextItem;
    }
    public void setNext(Node n){
        nextItem = n;
    }
}
</code>```

Any information would be greatly appreciated, thanks!

答:
The problem with your code is, that you do not call the function recursivly.

Furthermore, you might want to get the next node every time, not only when you replaced an item.

Therefore, you code should look like this:

```<code>public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
        }
        replace (firstItem, replaceItem, n.next());
    }
}
</code>```

Body:
Trying to create a method that will replace all instances of a string in a linked list with the chosen replacement string.

However, what I've got only seems to check the node chosen by the third argument, and does not recur through the list.

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
            n = n.next();
        }
    }
}

Here is the main app:

public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("red", n4);
        Node n2 = new Node("red", n3);
        Node n1 = new Node("red", n2);

        LinkedList list = new LinkedList(n1);

        System.out.println(list);

        list.replace("red", "RED", n1); // CALLING THE METHOD

        System.out.println(list);

    }
}

However the output comes out as:

RED, red, red, green

Not sure what I need to do to make it so it checks every node.

If needed, the node library:

package lib;

public class Node {
    private String item;
    private Node nextItem;

    public Node(String str, Node n){
        item = str;
        nextItem = n;
    }
    public String getItem(){
        return item;
    }
    public void setItem(String str){
        item = str;
    }
    public Node next(){
        return nextItem;
    }
    public void setNext(Node n){
        nextItem = n;
    }
}

Any information would be greatly appreciated, thanks!

Body:
The problem with your code is, that you do not call the function recursivly.

Furthermore, you might want to get the next node every time, not only when you replaced an item.

Therefore, you code should look like this:

public void replace(String firstItem, String replaceItem, Node n){
    if (n != null) {
        if (n.getItem().equals(firstItem)) {
            n.setItem(replaceItem);
        }
        replace (firstItem, replaceItem, n.next());
    }
}


答:
You can achieve this by sorting your file on the Time column (reverse alphanumeric sort gives the most recent Time on top), then take the first row and write it to a JSON file. Like so :

tSampleRow_1 config :

Title: Max date row using Talend Data Integration

Body:
Using Talend Data Integration, following data is inputted from a CSV file

  Time       A          B          C
18:22.0 -0.30107087 3.79899955  6.52000999
18:23.5 -9.648633   0.84515321  1.50116444
18:25.0 -6.01184034 7.66982508  4.42568207
18:25.9 -9.22426033 3.12263751  5.10443783
18:26.7 -9.00698662 4.03901815  0.01316811
18:27.4 -4.31255579 6.25724602  5.02961922
18:28.2 -2.67013335 7.5932107   5.41628265
18:28.8 -1.76213241 6.26981592  7.44536877
18:29.5 -2.18590617 5.58567238  6.23928976
18:30.3 0.42078096  3.1429882   8.46290493
18:30.9 0.36391866  3.02926373  8.86752415
18:31.6 0.35673606  3.07176089  8.93396378
18:32.4 0.35374331  3.05081153  8.93994904
18:33.0 0.38187516  3.05799413  8.89745235
18:33.7 0.32920274  3.03644633  8.9315691
18:34.4 0.37529111  3.07475352  8.93575954
18:35.0 0.40342298  3.07654929  8.86393356
18:35.7 0.35254622  3.05260706  8.9267807

How do I extract only the max date row  (18:35.7    0.35254622  3.05260706  8.9267807) and load it into a JSON?


问:
One more tidyr, gather and use of variables
Here is my code:

```<code>library(tidyr)

messy <- data.frame(
  name = c("Wilbur", "Petunia", "Gregory"),
  a = c(67, 80, 64),
  b = c(56, 90, 50)
)
</code>```

And I would like to use gather function with variable/function result. Borrowing from I tried:

```<code>not_messy <-messy %>%
  gather_('drug', 'heartrate', paste0('a',''):paste0('b',''))
</code>```

But it generated error:

```<code>Error in paste0("a", ""):paste0("b", "") : NA/NaN argument
In addition: Warning messages:
1: In lapply(.x, .f, ...) : NAs introduced by coercion
2: In lapply(.x, .f, ...) : NAs introduced by coercion
</code>```

What am I missing?

答:
With the latest version of the tidyverse functions, you are discouraged from using the underscore versions of the function for standard evaluation and instead use the rlang function syntax. In this case you can use</p>

```<code>gather(messy, "drug", "heartrate", (!!as.name("a")):(!!as.name("b")))
</code>```

Body:
Here is my code:

library(tidyr)

messy <- data.frame(
  name = c("Wilbur", "Petunia", "Gregory"),
  a = c(67, 80, 64),
  b = c(56, 90, 50)
)

And I would like to use gather function with variable/function result. Borrowing from I tried:

not_messy <-messy %>%
  gather_('drug', 'heartrate', paste0('a',''):paste0('b',''))

But it generated error:

Error in paste0("a", ""):paste0("b", "") : NA/NaN argument
In addition: Warning messages:
1: In lapply(.x, .f, ...) : NAs introduced by coercion
2: In lapply(.x, .f, ...) : NAs introduced by coercion

What am I missing?

Body:
With the latest version of the tidyverse functions, you are discouraged from using the underscore versions of the function for standard evaluation and instead use the rlang function syntax. In this case you can use

gather(messy, "drug", "heartrate", (!!as.name("a")):(!!as.name("b")))


问:
WHERE inside CASE statement
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

```<code>Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....
</code>```

What I want to do is something like this.

```<code>-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END
</code>```

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

答:
You're trying to build a conditional WHERE clause, yes? I'd think something like this would work pretty well for what you want to do:

```<code>WHERE (EXISTS (SELECT 1 FROM Status_table WHERE ID = 3)
        AND Item_Table.Status != 3)
        OR
        NOT EXISTS (SELECT 1 FROM Status_table WHERE ID = 3)
</code>```

Title: WHERE inside CASE statement

Body:
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....

What I want to do is something like this.

-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

Body:
You're trying to build a conditional WHERE clause, yes? I'd think something like this would work pretty well for what you want to do:

WHERE (EXISTS (SELECT 1 FROM Status_table WHERE ID = 3)
        AND Item_Table.Status != 3)
        OR
        NOT EXISTS (SELECT 1 FROM Status_table WHERE ID = 3)


问:
How to disable skipping in JavaScript console.log()

I'm trying to measure time taken by a function to execute in JS.
When I try to console.log() the elapsed time, some blue numbers appear in the console and some of the logs are gone.

When I counted the appeared number, it matched with the number of lines of skipped log.

I'm sure you can notice the problem at the right part of screenshot.

I would like the console to show all of the logs.

Is there anything I can do? BTW, the browser is Firefox 58.0b8. (Developer Edition)

答:
There are benchmarking methods in console that have very high accuracy. You can use console.time(key) and console.timeEnd(key).

https://developer.mozilla.org/en-US/docs/Web/API/Console/time

```<code>// kick off
console.time('asdf')

// later
console.timeEnd('asdf')

// VM18707:1 asdf: 2077.59716796875ms
</code>```

Even calling timeEnd immediately will yield different results, so it's not likely to have multiple consecutive equal results with a more complex script.

Body:
There are benchmarking methods in console that have very high accuracy. You can use console.time(key) and console.timeEnd(key).

https://developer.mozilla.org/en-US/docs/Web/API/Console/time

// kick off
console.time('asdf')

// later
console.timeEnd('asdf')

// VM18707:1 asdf: 2077.59716796875ms

Even calling timeEnd immediately will yield different results, so it's not likely to have multiple consecutive equal results with a more complex script.


问:
All ASP.NET Web API controllers return 404
I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I'm stumped. :/

I have the standard API controller route from the project template defined like:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

The registration is invoked in Global.asax:

```<code>protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register API routes
    WebApiConfig.Register(GlobalConfiguration.Configuration);

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
}
</code>```

I have a basic API controller like this:

```<code>namespace Website.Controllers
{
    public class FavoritesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new [] { "first", "second" };
        }

        // PUT api/<controller>/5
        public void Put(int id)
        {

        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {

        }
    }
}
</code>```

Now, when I browse to localhost:59900/api/Favorites I expect the Get method to be invoked, but instead I get a 404 status code and the following response:

```<code><Error>
   <Message>
       No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
   </Message>
   <MessageDetail>
      No type was found that matches the controller named 'Favorites'.
   </MessageDetail>
</Error>
</code>```

Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!

答:
Similar problem with an embarrassingly simple solution - make sure your API methods are public.  Leaving off any method access modifier will return an HTTP 404 too.

Will return 404:

```<code>List<CustomerInvitation> GetInvitations(){
</code>```

Will execute as expected:

```<code>public List<CustomerInvitation> GetInvitations(){
</code>```

Body:
I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I'm stumped. :/

I have the standard API controller route from the project template defined like:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

The registration is invoked in Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register API routes
    WebApiConfig.Register(GlobalConfiguration.Configuration);

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

I have a basic API controller like this:

namespace Website.Controllers
{
    public class FavoritesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new [] { "first", "second" };
        }

        // PUT api/<controller>/5
        public void Put(int id)
        {

        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {

        }
    }
}

Now, when I browse to localhost:59900/api/Favorites I expect the Get method to be invoked, but instead I get a 404 status code and the following response:

<Error>
   <Message>
       No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
   </Message>
   <MessageDetail>
      No type was found that matches the controller named 'Favorites'.
   </MessageDetail>
</Error>

Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!

Body:
Similar problem with an embarrassingly simple solution - make sure your API methods are public.  Leaving off any method access modifier will return an HTTP 404 too.

Will return 404:

List<CustomerInvitation> GetInvitations(){

Will execute as expected:

public List<CustomerInvitation> GetInvitations(){


问:
Google FCM Invalid_argument when sending message
I'm trying to figure out how to do push notifications to Android using Firebase and got it working using the legacy HTTP (https://fcm.googleapis.com/fcm/send) but the documentation suggests using the newer endpoint (https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send).  I can't seem to get it working because I keep getting this response:

```<code>{
    "error": {
        "code": 400,
        "message": "Request contains an invalid argument.",
        "status": "INVALID_ARGUMENT"
    }
}
</code>```

This occurs using the sample at https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_specific_devices:

```<code>POST https://fcm.googleapis.com/v1/projects/project-916177026973/messages:send HTTP/1.1
cache-control: no-cache
Postman-Token: 81403929-77ba-4568-8681-a854527ccb22
Content-Type: application/json
Authorization: Bearer <token redacted>
User-Agent: PostmanRuntime/6.4.1
Accept: */*
Host: fcm.googleapis.com
accept-encoding: gzip, deflate
content-length: 319
Connection: close

{
  "message":{
    "token" : <token redacted>,
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message",
      }
   }
}
</code>```

I also tried with the last comma removed to make it compliant with JSON and still no luck.  Any ideas?

答:
As the OP pointed out Firebase now suggest to the FCM v1 endpoint if you want to send messages via HTTP.

To send messages via HTTP, send an HTTP POST request to the FCM v1
  endpoint and specify the send method. The endpoint URL must contain
  the project ID of the Firebase project for your app, available in the
  General project settings tab of the Firebase console.

It will look something like this:

```<code>POST https://fcm.googleapis.com/v1/projects/your_project_id_here/messages:send HTTP/
</code>```

The section of the URL your_project_id_here  is your project id. You will need to find the project specific project Id which is located in the Settings section of the Firebase console for your project under the tab General.

Look for Project ID. If you have any doubts about your correct Project ID it is also a part if the URL in the website address to your project. It looks like:

```<code>https://console.firebase.google.com/project/your_project_id_here/settings/general/android:your_project_name
</code>```

Body:
I'm trying to figure out how to do push notifications to Android using Firebase and got it working using the legacy HTTP (https://fcm.googleapis.com/fcm/send) but the documentation suggests using the newer endpoint (https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send).  I can't seem to get it working because I keep getting this response:

{
    "error": {
        "code": 400,
        "message": "Request contains an invalid argument.",
        "status": "INVALID_ARGUMENT"
    }
}

This occurs using the sample at https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_specific_devices:

POST https://fcm.googleapis.com/v1/projects/project-916177026973/messages:send HTTP/1.1
cache-control: no-cache
Postman-Token: 81403929-77ba-4568-8681-a854527ccb22
Content-Type: application/json
Authorization: Bearer <token redacted>
User-Agent: PostmanRuntime/6.4.1
Accept: */*
Host: fcm.googleapis.com
accept-encoding: gzip, deflate
content-length: 319
Connection: close

{
  "message":{
    "token" : <token redacted>,
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message",
      }
   }
}

I also tried with the last comma removed to make it compliant with JSON and still no luck.  Any ideas?

Body:
As the OP pointed out Firebase now suggest to the FCM v1 endpoint if you want to send messages via HTTP.

To send messages via HTTP, send an HTTP POST request to the FCM v1
  endpoint and specify the send method. The endpoint URL must contain
  the project ID of the Firebase project for your app, available in the
  General project settings tab of the Firebase console.

It will look something like this:

POST https://fcm.googleapis.com/v1/projects/your_project_id_here/messages:send HTTP/

The section of the URL your_project_id_here  is your project id. You will need to find the project specific project Id which is located in the Settings section of the Firebase console for your project under the tab General.

Look for Project ID. If you have any doubts about your correct Project ID it is also a part if the URL in the website address to your project. It looks like:

https://console.firebase.google.com/project/your_project_id_here/settings/general/android:your_project_name


问:
Do functions called from parent functions on dispatch_queue get placed on main or dispatch_queue?
I am working in Swift 3.0 currently. I am wondering if functions called from functions that are placed on a Dispatch_Queue are also placed on the same Dispatch_Queue as well, or are they placed back on Main?

I included an example snippet below, in this case I'm wondering if calledFromParentFunction() is called from MyQueue since parentFunction1() that calls it is placed on MyQueue, or does calledFromParentFunction() get called on Main since it wasn't explicitly called on MyQueue?

```<code>let MyQueue = DispatchQueue(label: "My Queue", attributes: [], target: nil)

parentFunction1() {
    calledFromParentFunction()
}

calledFromParentFunction() {
    print("Is this on Main or MyQueue?")
}

override func viewDidLoad() {
    super.viewDidLoad()
    MyQueue.async { [unowned self] in
        parentFunction1()
    }
}
</code>```

答:
It's on the custom queue. You can prove it with this hack:</p>

```<code>func calledFromParentFunction() {
    let name = __dispatch_queue_get_label(nil)
    let queue =  String(cString: name, encoding: .utf8)!
    print("This is on", queue)
}
</code>```

Body:
I am working in Swift 3.0 currently. I am wondering if functions called from functions that are placed on a Dispatch_Queue are also placed on the same Dispatch_Queue as well, or are they placed back on Main?

I included an example snippet below, in this case I'm wondering if calledFromParentFunction() is called from MyQueue since parentFunction1() that calls it is placed on MyQueue, or does calledFromParentFunction() get called on Main since it wasn't explicitly called on MyQueue?

let MyQueue = DispatchQueue(label: "My Queue", attributes: [], target: nil)

parentFunction1() {
    calledFromParentFunction()
}

calledFromParentFunction() {
    print("Is this on Main or MyQueue?")
}

override func viewDidLoad() {
    super.viewDidLoad()
    MyQueue.async { [unowned self] in
        parentFunction1()
    }
}

Body:
It's on the custom queue. You can prove it with this hack:

func calledFromParentFunction() {
    let name = __dispatch_queue_get_label(nil)
    let queue =  String(cString: name, encoding: .utf8)!
    print("This is on", queue)
}


问:
cache a dataframe in pyspark
I want to know more precisely about the use of the method cache for dataframe in pyspark

When I run df.cache() it returns a dataframe.
Therefore, if I do df2 = df.cache(), which dataframe is in cache ? Is it df, df2, or both ?

答:
I found the source code DataFrame.cache

def cache(self):
    """Persists the :class:`DataFrame` with the default storage level (`MEMORY_AND_DISK`).

    .. note:: The default storage level has changed to `MEMORY_AND_DISK` to match Scala in 2.0.
    """
    self.is_cached = True
    self._jdf.cache()
    return self
```

Therefore, the answer is : both

Title: cache a dataframe in pyspark

Body:
I found the source code DataFrame.cache

def cache(self):
    """Persists the :class:`DataFrame` with the default storage level (`MEMORY_AND_DISK`).

    .. note:: The default storage level has changed to `MEMORY_AND_DISK` to match Scala in 2.0.
    """
    self.is_cached = True
    self._jdf.cache()
    return self

Therefore, the answer is : both

ContentLicense: CC BY-SA 4.0


问:
send binary with sendDocument in python-telegram-bot
this work :

```<code>mybot.sendDocument(chat_id=chatid, document=open('bla.pdf', rb'))
</code>```

But if I did before :

```<code>with open('bla.pdf', 'rb') as fp:
    b = fp.read()
</code>```

I can't do :

```<code>mybot.sendDocument(chat_id=chatid, document=b)
</code>```

The error is :

TypeError: Object of type 'bytes' is not JSON serializable

I use python 3.5.2 win or linux

Thanks for answer

答:
sorry I didn't see your answer.

My trouble was I wanted to send a downloaded document, not a document on disk.

I resolved it like this :

```<code>mybot.sendDocument(chat_id=chatid,document=io.BytesIO(self.downloaded_file))
</code>```

Body:
this work :

mybot.sendDocument(chat_id=chatid, document=open('bla.pdf', rb'))

But if I did before :

with open('bla.pdf', 'rb') as fp:
    b = fp.read()

I can't do :

mybot.sendDocument(chat_id=chatid, document=b)

The error is :

TypeError: Object of type 'bytes' is not JSON serializable

I use python 3.5.2 win or linux

Thanks for answer

Body:
sorry I didn't see your answer.

My trouble was I wanted to send a downloaded document, not a document on disk.

I resolved it like this :

mybot.sendDocument(chat_id=chatid,document=io.BytesIO(self.downloaded_file))


问:
Define a sympy symbol for physics value "hbar" that will print with latex
Sympy has the ability to print expressions with latex.  In pure latex, the physics symbol  ("hbar") is simply $\hbar$.

sympy.galgebra.GA has a make_symbols() method that provides extended symbol naming capabilities, but I don't see a way to create "hbar".

I want to define a sympy expression which contains the symbol "hbar" which will render as the physics symbol.

答:
You can create a SymPy symbol 'hbar'. SymPy will understand it and generate the latex representation for the variable you want. I tested this on SymPy version 1.1.1. If you have an older version and this does not work, please consider updating.

```<code>import sympy as sp
sp.init_printing()

h = sp.Symbol('hbar')
print(sp.latex(h)) # prints \hbar
</code>```

Thus, you can check that the LaTeX representation of the variable h is indeed $\hbar$.

Body:
You can create a SymPy symbol 'hbar'. SymPy will understand it and generate the latex representation for the variable you want. I tested this on SymPy version 1.1.1. If you have an older version and this does not work, please consider updating.

import sympy as sp
sp.init_printing()

h = sp.Symbol('hbar')
print(sp.latex(h)) # prints \hbar

Thus, you can check that the LaTeX representation of the variable h is indeed $\hbar$.


问:
hololens socket can't receive full packet
A simple summary:

boost asio server, send a video frame 720x768x3 with simple compression

packet size is 186476, not really to much

nothing to complicated, anyway, if i test it in the hololens emulator or on the physical device

```<code>// uint32_t data_length == size of frame 'data_ptr'
enum max_length = sizeof(uint32_t);
memcpy(data_, &data_length, max_length);
auto length = boost::asio::write(*socket_, boost::asio::buffer(data_, max_length), e);
length = boost::asio::write(*socket_, boost::asio::buffer(data_ptr, data_length), e);

// receive
char data_[max_length] = { 0 };

fd_set readSet;
FD_ZERO(&readSet);
FD_SET(_socket, &readSet);
timeval timeout;
timeout.tv_sec = 0;  // Zero timeout (poll)
timeout.tv_usec = 0;

auto result = select(_socket, &readSet, nullptr, nullptr, &timeout);
if (result == 0)
    continue;

result = recv(_socket, data_, max_length, 0);
if (result == SOCKET_ERROR) {
    closesocket(_socket);
    _socket = INVALID_SOCKET;
    break;
}

uint32_t msg_size(0);
memcpy(&msg_size, data_, max_length);

std::vector<char> vec(msg_size);
result = recv(_socket, &vec[0], msg_size, 0);

while (result < msg_size) {
    result += recv(_socket, &vec[result], msg_size - result, 0);
}
</code>```

but the hololens can't receive the full packet, i try it also with the .net streamsockets, same result. it tried a few times and then recv blocks in the while loop and doesn't receive anymore.

anyone, any idea? is it an uwp app problem, that i can't receive 'bigger' packets, or get it killed because it takes too long?

答:
You have two main problems:

First, you need to check the return value of recv for errors. If it returns 0 or -1, you need to handle that.

Second, you ignore all the data you received from your first call to recv. You set msg_size to zero when it should be result minus however many bytes the length took.

I would suggest writing a function that reads exactly the specified number of bytes, checking for errors. Call it first to receive four bytes and check if it returned an error. Then call it to receive the number of bytes indicated by the length data you received.

Smaller problems include:

What if the first recv only returns one byte?

What if the way your platform stores 32-bit integers isn't the same as the way the emulator sends it?

Body:
A simple summary:

boost asio server, send a video frame 720x768x3 with simple compression

packet size is 186476, not really to much

nothing to complicated, anyway, if i test it in the hololens emulator or on the physical device

// uint32_t data_length == size of frame 'data_ptr'
enum max_length = sizeof(uint32_t);
memcpy(data_, &data_length, max_length);
auto length = boost::asio::write(*socket_, boost::asio::buffer(data_, max_length), e);
length = boost::asio::write(*socket_, boost::asio::buffer(data_ptr, data_length), e);

// receive
char data_[max_length] = { 0 };

fd_set readSet;
FD_ZERO(&readSet);
FD_SET(_socket, &readSet);
timeval timeout;
timeout.tv_sec = 0;  // Zero timeout (poll)
timeout.tv_usec = 0;

auto result = select(_socket, &readSet, nullptr, nullptr, &timeout);
if (result == 0)
    continue;

result = recv(_socket, data_, max_length, 0);
if (result == SOCKET_ERROR) {
    closesocket(_socket);
    _socket = INVALID_SOCKET;
    break;
}

uint32_t msg_size(0);
memcpy(&msg_size, data_, max_length);

std::vector<char> vec(msg_size);
result = recv(_socket, &vec[0], msg_size, 0);

while (result < msg_size) {
    result += recv(_socket, &vec[result], msg_size - result, 0);
}

but the hololens can't receive the full packet, i try it also with the .net streamsockets, same result. it tried a few times and then recv blocks in the while loop and doesn't receive anymore.

anyone, any idea? is it an uwp app problem, that i can't receive 'bigger' packets, or get it killed because it takes too long?


问:
Extracting from key value pairs where each is in curly brackets
I'm pulling from an xml file using etree where I've extracted the following from a tag called dc as text:

```<code><dc>[{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]</dc>
</code>```

so I have dc = [{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]

I want to parse this out to have names and affiliations as lists:

```<code>names = Smith, Doe
affiliations = UofHawaii, UW
</code>```

Is there a simple way to do this? I can see that it's similar to a dictionary but not quite.
The number of names and affiliations does vary in the tree from 1 to 4.

Thanks.

答:
Simple list-comp.</p>

```<code>names = [x["name"] for x in dc]
affiliations = [x["affiliation"] for x in dc]

>>> names
['Smith', 'Doe']
>>> affiliations
['UofHawaii', 'UW']
</code>```

Body:
I'm pulling from an xml file using etree where I've extracted the following from a tag called dc as text:

<dc>[{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]</dc>

so I have dc = [{"name": "Smith", "affiliation": "UofHawaii"}, {"name": "Doe", "affiliation": "UW"}]

I want to parse this out to have names and affiliations as lists:

names = Smith, Doe
affiliations = UofHawaii, UW

Is there a simple way to do this? I can see that it's similar to a dictionary but not quite.
The number of names and affiliations does vary in the tree from 1 to 4.

Thanks.

Body:
Simple list-comp.

names = [x["name"] for x in dc]
affiliations = [x["affiliation"] for x in dc]

>>> names
['Smith', 'Doe']
>>> affiliations
['UofHawaii', 'UW']


问:
MySQL - the cheapest order
I have 2 MySQL tables:

```<code>Persons:
person_id
person_name

Orders:
person_id
cost
order_name
</code>```

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

答:
```<code>SELECT person_name, order_id, order_name, MIN(cost) as cost
FROM persons
INNER JOIN orders
ON persons.person_id = orders.person_id
GROUP BY person.person_name, order_id, order_name;
</code>```

You can do this just by joining your 2 tables and use MIN.

Title: MySQL - the cheapest order

Body:
I have 2 MySQL tables:

Persons:
person_id
person_name

Orders:
person_id
cost
order_name

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

Body:
SELECT person_name, order_id, order_name, MIN(cost) as cost
FROM persons
INNER JOIN orders
ON persons.person_id = orders.person_id
GROUP BY person.person_name, order_id, order_name;

You can do this just by joining your 2 tables and use MIN.


问:
Where is an error in this PHP code?
I have  PHP code that convert PDF files  to text files.For this task I  installed an external library using the composer in order to be able to use the library of the PDF.

The problem is that even when I required the installed library the system still not recognize the PDF Class.

The path of the library :

C:\xampp\htdocs\vendor\spatie\pdf-to-text\src\pdf.php

Error:

Fatal error: Uncaught Error: Class 'Pdf' not found in C:\xampp\htdocs\testwebsite\OSWebProject\test2.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\testwebsite\OSWebProject\test2.php on line 5

code : pdf class

```<code><?php

namespace Spatie\PdfToText;

use Spatie\PdfToText\Exceptions\CouldNotExtractText;
use Spatie\PdfToText\Exceptions\PdfNotFound;
use Symfony\Component\Process\Process;

class Pdf
{
    protected $pdf;

    protected $binPath;

    public function __construct(string $binPath = null)
    {
        $this->binPath = $binPath ?? '/usr/bin/pdftotext';
    }

    public function setPdf(string $pdf) : Pdf
    {
        if (!file_exists($pdf)) {
            throw new PdfNotFound("could not find pdf {$pdf}");
        }

        $this->pdf = $pdf;

        return $this;
    }

    public function text() : string
    {
        $process = new Process("{$this->binPath} " . escapeshellarg($this->pdf) . " -");
        $process->run();

        if (!$process->isSuccessful()) {
            throw new CouldNotExtractText($process);
        }

        return trim($process->getOutput(), " \t\n\r\0\x0B\x0C");
    }

    public static function getText(string $pdf, string $binPath = null) : string
    {
        return (new static($binPath))
            ->setPdf($pdf)
            ->text();
    }
}
</code>```

code:

```<code><?php

require_once('C:\xampp\htdocs\vendor\spatie\pdf-to-text\src\pdf.php');

$text = (new Pdf())
    ->setPdf('اجواء.pdf')
    ->text();
?>
</code>```

答:
Per the docs and source, the Pdf class is within the Spatie\PdfToText namespace.

You'll need use Spatie\PdfToText\Pdf; at the top of your PHP file, or you can reference it as new Spatie\PdfToText\Pdf() when you call it.

Title: Where is an error in this PHP code?

Body:
I have  PHP code that convert PDF files  to text files.For this task I  installed an external library using the composer in order to be able to use the library of the PDF.

The problem is that even when I required the installed library the system still not recognize the PDF Class.

The path of the library :

C:\xampp\htdocs\vendor\spatie\pdf-to-text\src\pdf.php

Error:

Fatal error: Uncaught Error: Class 'Pdf' not found in C:\xampp\htdocs\testwebsite\OSWebProject\test2.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\testwebsite\OSWebProject\test2.php on line 5

code : pdf class

<?php

namespace Spatie\PdfToText;

use Spatie\PdfToText\Exceptions\CouldNotExtractText;
use Spatie\PdfToText\Exceptions\PdfNotFound;
use Symfony\Component\Process\Process;

class Pdf
{
    protected $pdf;

    protected $binPath;

    public function __construct(string $binPath = null)
    {
        $this->binPath = $binPath ?? '/usr/bin/pdftotext';
    }

    public function setPdf(string $pdf) : Pdf
    {
        if (!file_exists($pdf)) {
            throw new PdfNotFound("could not find pdf {$pdf}");
        }

        $this->pdf = $pdf;

        return $this;
    }

    public function text() : string
    {
        $process = new Process("{$this->binPath} " . escapeshellarg($this->pdf) . " -");
        $process->run();

        if (!$process->isSuccessful()) {
            throw new CouldNotExtractText($process);
        }

        return trim($process->getOutput(), " \t\n\r\0\x0B\x0C");
    }

    public static function getText(string $pdf, string $binPath = null) : string
    {
        return (new static($binPath))
            ->setPdf($pdf)
            ->text();
    }
}

code:

<?php

require_once('C:\xampp\htdocs\vendor\spatie\pdf-to-text\src\pdf.php');

$text = (new Pdf())
    ->setPdf('اجواء.pdf')
    ->text();
?>


问:
Get the display property value of an element
Using the sample below, I'm trying to get return the display value or trs[1].

```<code><table>
    <tr>
        <td></td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>
<script>
    const trs = document.getElementsByTagName("tr");
    trs[1].style.display = "hidden";
    console.log(trs[1].style.getPropertyValue('display'));
</script>
</code>```

I would expect the the result to be "hidden" for trs[1] and NULL or "" for trs[0]. However in the console, i'm not getting any property value back for either trs[0/1].

I'm not sure if i'm using the right method to return a css property value that is set dynamically in js.

Thanks
JR

答:
The value isn't set as "hidden" isn't a valid value. Try:</p>

```<code>trs[1].style.display = "none";
console.log(trs[1].style.getPropertyValue('display'));
</code>```

Body:
Using the sample below, I'm trying to get return the display value or trs[1].

I would expect the the result to be "hidden" for trs[1] and NULL or "" for trs[0]. However in the console, i'm not getting any property value back for either trs[0/1].

I'm not sure if i'm using the right method to return a css property value that is set dynamically in js.

Thanks
JR

Body:
The value isn't set as "hidden" isn't a valid value. Try:

trs[1].style.display = "none";
console.log(trs[1].style.getPropertyValue('display'));


问:
Crafting items using MineCraft Forge 1.12
Since forge has changed from 1.18/1.11 to 1.12, I need some examples of how to code with the new framework in regards to tools/weopons</p>

答:
After a painful trial of trying to figure out how to register items in the new version of Forge for 1.12, I have attached a link to my Github repository that outlines how to register new items, jsut go to the link below:
Minecraft forge 1.12 crafting project

Forge from version 1.8 - 1.12 has changed a lot.
Hope this helps


问:
MPI: Processor does not go up to 100% on a single MPI process
I have a simple client-server program written in C using sockets. The server opens a new pthread for each request. On each new opened thread, I do a CPU intensive task (matrix multiplication).

I have a CPU with 2 physical cores and 4 logical processors.

When I run 4 clients, the server opens 4 threads, each thread is assigned on a logical processor and the CPU goes to 100% (usage).

If I run the clients one by one at a 5 seconds delay, I can see very clear how the CPU goes from 25% (one client), to 50% (two clients), to 75% (three clients) and finally to 100% (4 clients). It's a pretty normal behaviour.

However, if I embed the entire server code into a MPI process (only one MPI process), the CPU does not raise more than 50% no matter how many clients I start.

Why is this happening?

Thank you respectfully

答:
The official answer to this question / problem is the following:

As Hristo Iliev said in a comment to my question, passing --bind-to none to the mpirun command solves the problem.

This option actually binds a MPI process to a specific object (see the manual for more details).

By default, each MPI process is bound to a physical core. I have 2 cores on my machine, so the maximum usage of the CPU that I can get will be around 50%.

Setting the binding to none removes that constraint and now each MPI process will be bound to a logical core, which allows my CPU to get to 100%.


问:
c# sql server backup percent read
sql command

```<code>BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT
</code>```

result

```<code>5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.
</code>```

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

答:
Besides from using the SMO method as other have indicated, or from sneaking the percent_complete column of sys.dm_exec_requests, there is also another question asked here: how to I capture those 5 percent complete messages in C#?

The percent complete is an informational message. All informational messages in C# can be captured from the SqlConnection.InfoMessage event.

Title: c# sql server backup percent read

Body:
sql command

BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT

result

5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?


问:
How to set a breakpoint on access a js-file/lib in dev tools in chrome?
Is it possible to get a breakpoint when debugging, so that it stops each time when the certain class is accessed, otherwise it runs normally.

It's very common use case when one don't want to stop on jquery functions or other common libs functions, and want rather to stay on a specific js-file, but has no idea of what there could fire a bug, so one don't want explicitly to set a breakpoint on every line in the js file to catch all accesses on that file. Are there any options for Chrome DevTools for that debugging functionality?

Update:

Or maybe there is another way to get the similar functionality by ignoring whole libraries such as jquery, if there should be a breakpoint, so that only other files will be handled with debugger? That would be still not the best solution for the case, but anyway saves much time.

Update2:

the second approach is described here, but I have Chrome 26, and unfortunately cannot update it in the next one-two months, so this feature doesn't work for my browser now.

答:
If you know the function(s) being called, you can use function breakpoints

```<code>debug(function);
function(...args);
</code>```

When you call the function, it will hit the breakpoint. These aren't saved on page reload, but you can set a line breakpoint once you hit the function breakpoint.

This can get kinda tedious though.

If you have a array of functions, you can do

```<code>[function0, function1].map(debug)
</code>```

@Tibos answer would be good if there was some sort of babel transform to insert debugger; at the start of every function, instead of inserting it manually.

Body:
If you know the function(s) being called, you can use function breakpoints

debug(function);
function(...args);

When you call the function, it will hit the breakpoint. These aren't saved on page reload, but you can set a line breakpoint once you hit the function breakpoint.

This can get kinda tedious though.

If you have a array of functions, you can do

[function0, function1].map(debug)

@Tibos answer would be good if there was some sort of babel transform to insert debugger; at the start of every function, instead of inserting it manually.


问:
Can you replicate a normal table to a system versioned temporal table?
I'm curious to know whether I can replicate a table in SQL Server where the publisher is a normal table, and the subscriber is a system versioned temporal table? Is that possible? </p>

<p>The intent is to have a DW containing the historical (and current) data of an ODS. The DW being the subscriber, and the ODS being the publisher in this scenario. </p>

答:
This is an explanation from the online docs.

Snapshot and transactional replication: Only supported for a single publisher without temporal being enabled and one subscriber with temporal enabled. In this case, the publisher is used for an OLTP workload while subscriber serves for offloading reporting (including AS OF querying).

Body:
I'm curious to know whether I can replicate a table in SQL Server where the publisher is a normal table, and the subscriber is a system versioned temporal table? Is that possible?

The intent is to have a DW containing the historical (and current) data of an ODS. The DW being the subscriber, and the ODS being the publisher in this scenario.