问:
For Loop in Visual Basic results wrong number of loops
I don't understand why I get x with a value of 6 while I think it should be 5.

```<code>Sub Main()
    Dim x = 0
    For x = 1 To 5
    Next
    Console.WriteLine(x)
    Console.ReadLine()
End Sub
</code>```

Result: 6

答:
The reason that x equals 6 is because of the nature of a loop. You put no code inside the body of the loop. If you printed your code there you would see

```<code>1
2
3
4
5
</code>```

Each time Next is reached, x is incremented. The fifth time you go through the loop, x is incremented to 6. In most cases it's best to not use loop variables outside of their loop. Using a C style loop what I mean is a bit more clear

```<code>for (int i=0; i<=5; i++){}
</code>```

The loop runs until the condition i <= 5 is not true. Since each time through the loop i is increased by 1 this occurs first when i equals 6.  I used the variable i here because i is a much more common loop variable name to see than x.

Body:
I don't understand why I get x with a value of 6 while I think it should be 5.

Sub Main()
    Dim x = 0
    For x = 1 To 5
    Next
    Console.WriteLine(x)
    Console.ReadLine()
End Sub

Result: 6

Body:
The reason that x equals 6 is because of the nature of a loop. You put no code inside the body of the loop. If you printed your code there you would see

1
2
3
4
5

Each time Next is reached, x is incremented. The fifth time you go through the loop, x is incremented to 6. In most cases it's best to not use loop variables outside of their loop. Using a C style loop what I mean is a bit more clear

for (int i=0; i<=5; i++){}

The loop runs until the condition i <= 5 is not true. Since each time through the loop i is increased by 1 this occurs first when i equals 6.  I used the variable i here because i is a much more common loop variable name to see than x.


来源: stackexchange

问:
Rounding to midpoint of decimal place using ToString only
I know that C# has some options to format decimal numbers with some extended logic in the ToString() method, as e.g.

```<code>double d1 = 1.3333;
double d2 = 1.6666;
string d1Str = d1.ToString("#0.00"); // 1.33
string d2Str = d2.ToString("#0.00"); // 1.67
</code>```

That's great, my number is rounded to the second decimal. But what if I wanted to round to a step of 0.05 instead of 0.01? Is there a way to use the ToString() method in a similar way to round the value not to a given step-size (e.g. 0.05)?

Note: I know I could do something like this:

```<code>(Math.Round(1.33333*20)/20).ToString();
</code>```

but the question is about getting this result using ToString() only.

答:
Is it possible for you to create an extension overload for ToString() for these components?

If so you could write something like:

```<code>public static class DoubleStaticExtension
{
    public static string ToString(this double value, string format, int decimalToRoundHalfwayAt)
    {
        int modifier = 2 * (int)Math.Pow(10, decimalToRoundHalfwayAt -1 );
        return (Math.Round(value * modifier, MidpointRounding.AwayFromZero) / modifier).ToString(format);
    }
}
</code>```

Calling that with

```<code>        double d = 9.333333;
        string result = d.ToString("#0.00", 2);
</code>```

Would give a result of 9.35

And

```<code>    double d = 9.333333;
    string result = d.ToString("#0.00", 1);
</code>```

Would give a result of 9.50

ContentLicense: CC BY-SA 3.0

Body:
I know that C# has some options to format decimal numbers with some extended logic in the ToString() method, as e.g.

double d1 = 1.3333;
double d2 = 1.6666;
string d1Str = d1.ToString("#0.00"); // 1.33
string d2Str = d2.ToString("#0.00"); // 1.67

That's great, my number is rounded to the second decimal. But what if I wanted to round to a step of 0.05 instead of 0.01? Is there a way to use the ToString() method in a similar way to round the value not to a given step-size (e.g. 0.05)?

Note: I know I could do something like this:

(Math.Round(1.33333*20)/20).ToString();

but the question is about getting this result using ToString() only.

Body:
Is it possible for you to create an extension overload for ToString() for these components?

If so you could write something like:

public static class DoubleStaticExtension
{
    public static string ToString(this double value, string format, int decimalToRoundHalfwayAt)
    {
        int modifier = 2 * (int)Math.Pow(10, decimalToRoundHalfwayAt -1 );
        return (Math.Round(value * modifier, MidpointRounding.AwayFromZero) / modifier).ToString(format);
    }
}

Calling that with

        double d = 9.333333;
        string result = d.ToString("#0.00", 2);

Would give a result of 9.35

And

    double d = 9.333333;
    string result = d.ToString("#0.00", 1);

Would give a result of 9.50

ContentLicense: CC BY-SA 4.0


问:
how to store images and display the images when the name of the image is entered in electron app?
I'm trying to make a desktop application wherein I have few images stored inside app, whenever I type some text, the text should be scanned and the corresponding image should be displayed in realtime in electron

Please help me out.

答:
Tell us more details about that... Like, wish your current system?
Any way, I recommend you make this app with Python, that have some solutions for that (image recognition).</p>


问:
SSRS tablix visibility
I have a multi-parameter report in SSRS where I want to display or hide a report depending on the parameter selection.  If the user selects only one facility from a multi-value facility parameter then I want a second report to display along with the main report(it would be a separate tab).  If multiple facilities are chosen then I only want the main report to display.

I've been playing with the visibility expressions on the second report but I can't seem to get it to work.

I've tried:

```<code>   =IFF(Parameters!entity.IsMultiValue, "True", "False")
</code>```

but that returns an error "The hidden expression used in tablix returned a data type that is not valid.

I've also tried:

```<code>   =IIF(Parameters!entity.Count = 1), "False", "True")
</code>```

But I get the same error.  I'm using SSRS 2016.

答:
False and True are not strings but constants.

Change it to:

```<code>=IIF(Parameters!entity.IsMultiValue="Your value", True, False)
</code>```

And the second one to:

```<code> =IIF(Parameters!entity.Count = 1, False, True)
</code>```

Good luck.

Title: SSRS tablix visibility

Body:
I have a multi-parameter report in SSRS where I want to display or hide a report depending on the parameter selection.  If the user selects only one facility from a multi-value facility parameter then I want a second report to display along with the main report(it would be a separate tab).  If multiple facilities are chosen then I only want the main report to display.

I've been playing with the visibility expressions on the second report but I can't seem to get it to work.

I've tried:

   =IFF(Parameters!entity.IsMultiValue, "True", "False")

but that returns an error "The hidden expression used in tablix returned a data type that is not valid.

I've also tried:

   =IIF(Parameters!entity.Count = 1), "False", "True")

But I get the same error.  I'm using SSRS 2016.

Body:
False and True are not strings but constants.

Change it to:

=IIF(Parameters!entity.IsMultiValue="Your value", True, False)

And the second one to:

 =IIF(Parameters!entity.Count = 1, False, True)

Good luck.


问:
Create a stored procedure where the primary key is 'None' for my identified database
I'm a new SQL developer and I'm attempting to write a stored procedure that selects from my databases system views and where I need to get the following results:

I want to select my

database name

schema name

table name

primary key column (uses a function to return 'None' if no primary key)

identity column (uses case statement to return 'No Identity' if NORMALIZE columns are identity.

Example results:

```<code>Database     Table     Schema     Primary Key     Identity
-------------------------------------------------------------
DB1          Table1    dbo        None            No Identity
DB1          Table2    dbo        abcID           abcID
</code>```

I have my function (see bottom), but I'm having issues on where to use it.  I'm also having issues getting my CASE statement right.

Here's my script so far:

```<code>CREATE PROC System_Views_Databases_Without_Primary_Keys
     @DBName NVARCHAR(255)
AS
    SET NOCOUNT ON;

    SELECT
        db_name () AS [Database],
        SCHEMA_NAME(SCHEMA_ID) AS [Schema],
        tab.Name AS [Table],
        tc.TABLE_NAME AS [Primary Key],
        col.is.identity AS [Identity]
    FROM
        sys.columns col
    JOIN
        sys.tables tab ON col.object_id = tab.object_id
    JOIN
        INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tab.name = tc.table_name
    WHERE
        OBJECTPROPERTY(tab.object_id, 'TableHasPrimaryKey') = 1
        CASE
           WHEN [Identity] = 1 THEN 'Yes Identity'
           WHEN [Identity] = 0 THEN 'No Identity'
        END
</code>```

My DDL for function:

```<code>CREATE FUNCTION [dbo].[Primary_Key] (@Primary_Key VARCHAR(255))
RETURNS VARCHAR (255)
AS
BEGIN
    DECLARE @nonvalid varchar (255)

    IF @Primary_Key IS NULL
       SET @nonvalid = 'None'
    ELSE
       SET @nonvalid = @Primary_Key

    RETURN @nonvalid
END
</code>```

Any assistance is greatly appreciated!

答:
Try this, It will give you each column in the table and tell which one is identity and which one is primarykey.</p>

```<code>    SELECT DISTINCT
        db_name () AS [Database],
        SCHEMA_NAME(SCHEMA_ID) AS [Schema],
        tab.Name AS [Table],
        col.name,
        Case when COLUMNPROPERTY(OBJECT_ID(tab.name),col.name,'isidentity') = 1 then col.name Else 'No Identity' End AS [Identity]
        ,Case when Prim.CONSTRAINT_NAME is not null then prim.CONSTRAINT_NAME else 'None' End as Primarykey

    FROM
        sys.columns col
    JOIN
        sys.tables tab
            ON col.object_id = tab.object_id
   Left JOIN (
                SELECT K.TABLE_NAME,
                K.COLUMN_NAME,
                K.CONSTRAINT_NAME
                FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
                ON C.TABLE_NAME = K.TABLE_NAME
                AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
                AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
                AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
                WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
                ) prim
            on prim.TABLE_NAME = tab.name and prim.column_name=col.name
</code>```

Body:
I'm a new SQL developer and I'm attempting to write a stored procedure that selects from my databases system views and where I need to get the following results:

I want to select my

database name

schema name

table name

primary key column (uses a function to return 'None' if no primary key)

identity column (uses case statement to return 'No Identity' if NORMALIZE columns are identity.

Example results:

Database     Table     Schema     Primary Key     Identity
-------------------------------------------------------------
DB1          Table1    dbo        None            No Identity
DB1          Table2    dbo        abcID           abcID

I have my function (see bottom), but I'm having issues on where to use it.  I'm also having issues getting my CASE statement right.

Here's my script so far:

CREATE PROC System_Views_Databases_Without_Primary_Keys
     @DBName NVARCHAR(255)
AS
    SET NOCOUNT ON;

    SELECT
        db_name () AS [Database],
        SCHEMA_NAME(SCHEMA_ID) AS [Schema],
        tab.Name AS [Table],
        tc.TABLE_NAME AS [Primary Key],
        col.is.identity AS [Identity]
    FROM
        sys.columns col
    JOIN
        sys.tables tab ON col.object_id = tab.object_id
    JOIN
        INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tab.name = tc.table_name
    WHERE
        OBJECTPROPERTY(tab.object_id, 'TableHasPrimaryKey') = 1
        CASE
           WHEN [Identity] = 1 THEN 'Yes Identity'
           WHEN [Identity] = 0 THEN 'No Identity'
        END

My DDL for function:

CREATE FUNCTION [dbo].[Primary_Key] (@Primary_Key VARCHAR(255))
RETURNS VARCHAR (255)
AS
BEGIN
    DECLARE @nonvalid varchar (255)

    IF @Primary_Key IS NULL
       SET @nonvalid = 'None'
    ELSE
       SET @nonvalid = @Primary_Key

    RETURN @nonvalid
END

Any assistance is greatly appreciated!

Body:
Try this, It will give you each column in the table and tell which one is identity and which one is primarykey.

    SELECT DISTINCT
        db_name () AS [Database],
        SCHEMA_NAME(SCHEMA_ID) AS [Schema],
        tab.Name AS [Table],
        col.name,
        Case when COLUMNPROPERTY(OBJECT_ID(tab.name),col.name,'isidentity') = 1 then col.name Else 'No Identity' End AS [Identity]
        ,Case when Prim.CONSTRAINT_NAME is not null then prim.CONSTRAINT_NAME else 'None' End as Primarykey

    FROM
        sys.columns col
    JOIN
        sys.tables tab
            ON col.object_id = tab.object_id
   Left JOIN (
                SELECT K.TABLE_NAME,
                K.COLUMN_NAME,
                K.CONSTRAINT_NAME
                FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
                ON C.TABLE_NAME = K.TABLE_NAME
                AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
                AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
                AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
                WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
                ) prim
            on prim.TABLE_NAME = tab.name and prim.column_name=col.name


问:
Swift: Display Image from URL
In Swift 3, I am trying to capture an image from the internet, and have these lines of code:

```<code>var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)
</code>```

What am I doing wrong here?

答:
Swift

Good solution to extend native functionality by extensions

```<code>import UIKit

extension UIImage {
  convenience init?(url: URL?) {
    guard let url = url else { return nil }

    do {
      self.init(data: try Data(contentsOf: url))
    } catch {
      print("Cannot load image from url: \(url) with error: \(error)")
      return nil
    }
  }
}
</code>```

Usage

Convenience initializer is failable and accepts optional URL – approach is safe.

```<code>imageView.image = UIImage(url: URL(string: "some_url.png"))
</code>```

Title: Swift: Display Image from URL

Body:
In Swift 3, I am trying to capture an image from the internet, and have these lines of code:

var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg")
var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil
var catPicture = UIImage(data: catPictureData as! Data)

What am I doing wrong here?

Body:
Swift

Good solution to extend native functionality by extensions

import UIKit

extension UIImage {
  convenience init?(url: URL?) {
    guard let url = url else { return nil }

    do {
      self.init(data: try Data(contentsOf: url))
    } catch {
      print("Cannot load image from url: \(url) with error: \(error)")
      return nil
    }
  }
}

Usage

Convenience initializer is failable and accepts optional URL – approach is safe.

imageView.image = UIImage(url: URL(string: "some_url.png"))


问:
Getting 400 error when closing Excel session using the MS Graph API
I've created a microservice that takes in a workbook and a set of values. The microservice creates a non-persistent session for the workbook, sets some named ranges to the values, and returns contents of a different set of named ranges.

When I try to clean up the non-persistent session, I get a 400 error.

edit:
My question is "Are non-persistent sessions 'closable'?"

答:
The non-persistent session is also closable. I'm guessing you are including the HTTP header as shown here.

You could also ignore this error for the time-being. Session close error shouldn't result in application level error for the end-user. There is no side effect for the app - it just means that Excel has a bunch of unclosed sessions till it times out. We will take a look on the server side.


问:
Can you build dynamic libraries for iOS and load them at runtime?
Are dynamic libraries supported on iOS (iPhone/iPad)?

In Xcode, I tried to create a New project -> Framework & Library -> Cocoa Library (dynamic). In the project settings, I set the Base SDK to iOS device 4.1 and target to iOS4.1, but it has a build error:

target specifies product type 'com.apple.product-type.library.dynamic', but there's no such product type for the 'iphonesimulator' platform".

The build i selected is Simulator -> Debug -> i386.

答:
At the time this question was asked, Dynamic libraries were not supported by iOS and will result in your app getting rejected. Only static libraries are allowed.

However, in iOS8 you can use dynamic libraries and frameworks. It should "just work"


问:
Whitespace concatenation in Bash
The problem is simple.

```<code>for i in `seq $begin $progress_length` ; do
  progress_bar=$progress_bar'#'
done

for i in `seq $middle $end` ; do
  empty_space=$empty_space' '
done
</code>```

I need empty_space to position content after the progress bar. I've expected that it will be string of x whitespaces. But finally string is empty. How may I create string of x whitespaces?

答:
I understand your problem as I had exactly the same.

My solution was to concatenate a temporary character instead of a whitespace, say for example ☼, and then, at the end, replace all their occurences with sed by a whitespace :

```<code>echo $myString | sed 's/☼/ /g'
</code>```

I hope it will help you !

Title: Whitespace concatenation in Bash

Body:
The problem is simple.

for i in `seq $begin $progress_length` ; do
  progress_bar=$progress_bar'#'
done

for i in `seq $middle $end` ; do
  empty_space=$empty_space' '
done

I need empty_space to position content after the progress bar. I've expected that it will be string of x whitespaces. But finally string is empty. How may I create string of x whitespaces?

Body:
I understand your problem as I had exactly the same.

My solution was to concatenate a temporary character instead of a whitespace, say for example ☼, and then, at the end, replace all their occurences with sed by a whitespace :

echo $myString | sed 's/☼/ /g'

I hope it will help you !


问:
Drawing zoomable audio waveform timeline in Javascript
I have raw 44,1 kHz audio data from a song as Javascript array and I'd like to create a zoomable timeline out of it.

Example timeline from Audacity:

Since there are millions of timepoints normal Javascript graphics libraries probably don't cut it: I think, not sure, that normal graph libraries will die on this many timepoints. But does there exist already libraries for this sort of visualization for JS? Canvas, webGL, SVG all are acceptable solutions.

A solution preferably with zoom and pan.

Note that this happens strictly on client side and server-side solutions are not accetable.

答:
You cannot simply take the the waveform data and render all data points, this is terribly inefficient.

Variable explanation:

width: Draw area width in pixels, max is screen width

height: Same as width but then height of draw area

spp: Samples per pixel, this is your zoom level

resolution: Number of samples to take per pixel sample range, tweak for performance vs accuracy.

scroll: You will need virtual scrolling for performance, this is the scroll position in px

data: The raw audio data array, probably several million samples long

drawData: The reduced audio data used to draw

You are going to have to only take the samples that are in the viewport from the audio data and reduce those. Commenly this results in a data set that is 2 * width, you use this data set to render the image.
To zoom out increase spp, to zoom in decrease it. Changing scroll value pans it.

The following code has O(RN) complexity where N is width and R is resolution. Maximum accuracy is at spp <= resolution.

The code will look something like this, this gets the peak values, you could do rms or average as well.

```<code>let reduceAudioPeak = function(data, spp, scroll, width, resolution) {
    let drawData = new Array(width);
    let startSample = scroll * spp;
    let skip = Math.ceil(spp / resolution);

    // For each pixel in draw area
    for (let i = 0; i < width; i++) {
        let min = 0; // minimum value in sample range
        let max = 0; // maximum value in sample range
        let pixelStartSample = startSample + (i * spp);

        // Iterate over the sample range for this pixel (spp)
        // and find the min and max values.
        for(let j = 0; j < spp; j += skip) {
           const index = pixelStartSample + j;
           if(index < data.length) {
               let val = data[index];
               if (val > max) {
                  max = val;
               } else if (val < min) {
                  min = val;
               }
           }
        }

        drawData[i] = [min, max];
    }
    return drawData;
}
</code>```

With this data you can draw it like this, you could use lines, svg etc:

```<code>let drawWaveform = function(canvas, drawData, width, height) {
   let ctx = canvas.getContext('2d');
   let drawHeight = height / 2;

   // clear canvas incase there is already something drawn
   ctx.clearRect(0, 0, width, height);
   for(let i = 0; i < width; i++) {
      // transform data points to pixel height and move to centre
      let minPixel = drawData[i][0] * drawHeigth + drawHeight;
      let maxPixel = drawData[i][1] * drawHeight + drawHeight;
      let pixelHeight = maxPixel - minPixel;

      ctx.fillRect(i, minPixel, 1, pixelHeight);
   }
}
</code>```

Body:
You cannot simply take the the waveform data and render all data points, this is terribly inefficient.

Variable explanation:

width: Draw area width in pixels, max is screen width

height: Same as width but then height of draw area

spp: Samples per pixel, this is your zoom level

resolution: Number of samples to take per pixel sample range, tweak for performance vs accuracy.

scroll: You will need virtual scrolling for performance, this is the scroll position in px

data: The raw audio data array, probably several million samples long

drawData: The reduced audio data used to draw

You are going to have to only take the samples that are in the viewport from the audio data and reduce those. Commenly this results in a data set that is 2 * width, you use this data set to render the image.
To zoom out increase spp, to zoom in decrease it. Changing scroll value pans it.

The following code has O(RN) complexity where N is width and R is resolution. Maximum accuracy is at spp <= resolution.

The code will look something like this, this gets the peak values, you could do rms or average as well.

let reduceAudioPeak = function(data, spp, scroll, width, resolution) {
    let drawData = new Array(width);
    let startSample = scroll * spp;
    let skip = Math.ceil(spp / resolution);

    // For each pixel in draw area
    for (let i = 0; i < width; i++) {
        let min = 0; // minimum value in sample range
        let max = 0; // maximum value in sample range
        let pixelStartSample = startSample + (i * spp);

        // Iterate over the sample range for this pixel (spp)
        // and find the min and max values.
        for(let j = 0; j < spp; j += skip) {
           const index = pixelStartSample + j;
           if(index < data.length) {
               let val = data[index];
               if (val > max) {
                  max = val;
               } else if (val < min) {
                  min = val;
               }
           }
        }

        drawData[i] = [min, max];
    }
    return drawData;
}

With this data you can draw it like this, you could use lines, svg etc:

let drawWaveform = function(canvas, drawData, width, height) {
   let ctx = canvas.getContext('2d');
   let drawHeight = height / 2;

   // clear canvas incase there is already something drawn
   ctx.clearRect(0, 0, width, height);
   for(let i = 0; i < width; i++) {
      // transform data points to pixel height and move to centre
      let minPixel = drawData[i][0] * drawHeigth + drawHeight;
      let maxPixel = drawData[i][1] * drawHeight + drawHeight;
      let pixelHeight = maxPixel - minPixel;

      ctx.fillRect(i, minPixel, 1, pixelHeight);
   }
}


问:
Excel COUNTIF returns ambiguous results
I'm trying to use Excel's COUNTIF formula on a large range of values to basically create a unique and sorted list of those values. However, several values don't seem to be considered in this operation, so I went to debugging it.

Could you explain to me why the values in column B of the snipet table below are all '0'? What is the catch to obtain a value of '1' when comparing values like the ones below?

I understand I'm probably missing some silly detail...

Thanks in advance

```<code>   -----------------
   |   A   |   B   |
   -----------------
1  | 10 B  |   0   |  <-- B1 formula is =COUNTIF(A1;"<52")
   -----------------
2  |  52   |   0   |  <-- B2 formula is =COUNTIF(A2;"<10 B")
   -----------------
3  |  52   |   0   |  <-- B3 formula is =COUNTIF(A3;"=10 B")
   -----------------
</code>```

EDIT:
Let me put this into perspective. Consider the table below.

What I'm trying to achieve exactly is, on column B, construct a list of unique values from column A. I'm doing this by using the following formula on B2, with CTRL+SHIFT+ENTER, and dragging it through cells in B column, B3, B4, etc:

```<code>=INDEX($A$2:$A$100;MATCH(0;COUNTIF($A$2:$A$100;"<"&$A$2:$A$100)-SUM(COUNTIF($A$2:$A$100;B$1:B1));0))
</code>```

However, several values from column A are "skipped", hence why I've tried debuging the COUNTIF formula like I explained above, but still no idea why certain values are skipped, perhaps an error with the formula?

```<code>    -----------------------
    |     A    |     B    |
    -----------------------
 1  |          |          |
    -----------------------
 2  |    52    |    52    |
    -----------------------
 3  |   16277  |  16277   |
    -----------------------
 4  |   16277  |  21785   |
    -----------------------
 5  |   16277  | 5411828  |
    -----------------------
 6  |   21785  | 54112528 |
    -----------------------
 7  |  5411828 |   37-50  |
    -----------------------
 8  | 54112528 |   42-B   |
    -----------------------
 9  |   10 B   |  ABC-01  |
    -----------------------
10  |   10-M   |          |
    -----------------------
11  |   15-94  |          |
    -----------------------
12  |  15-971/ |          |
    -----------------------
13  |   16.    |          |
    -----------------------
14  |   16..   |          |
    -----------------------
15  |   22-23  |          |
    -----------------------
16  |   37-50  |          |
    -----------------------
17  |   42-B   |          |
    -----------------------
18  |  ABC-01  |          |
    -----------------------
</code>```

答:
I'm trying to use Excel's COUNTIF formula on a large range of values to basically create a unique and sorted list of those values.

What you have just described there can be accomplished easily with a PivotTable, with the field of interest in both the Rows area and in the Values area as a Count.

Title: Excel COUNTIF returns ambiguous results

Body:
I'm trying to use Excel's COUNTIF formula on a large range of values to basically create a unique and sorted list of those values. However, several values don't seem to be considered in this operation, so I went to debugging it.

Could you explain to me why the values in column B of the snipet table below are all '0'? What is the catch to obtain a value of '1' when comparing values like the ones below?

I understand I'm probably missing some silly detail...

Thanks in advance

   -----------------
   |   A   |   B   |
   -----------------
1  | 10 B  |   0   |  <-- B1 formula is =COUNTIF(A1;"<52")
   -----------------
2  |  52   |   0   |  <-- B2 formula is =COUNTIF(A2;"<10 B")
   -----------------
3  |  52   |   0   |  <-- B3 formula is =COUNTIF(A3;"=10 B")
   -----------------

EDIT:
Let me put this into perspective. Consider the table below.

What I'm trying to achieve exactly is, on column B, construct a list of unique values from column A. I'm doing this by using the following formula on B2, with CTRL+SHIFT+ENTER, and dragging it through cells in B column, B3, B4, etc:

=INDEX($A$2:$A$100;MATCH(0;COUNTIF($A$2:$A$100;"<"&$A$2:$A$100)-SUM(COUNTIF($A$2:$A$100;B$1:B1));0))

However, several values from column A are "skipped", hence why I've tried debuging the COUNTIF formula like I explained above, but still no idea why certain values are skipped, perhaps an error with the formula?

    -----------------------
    |     A    |     B    |
    -----------------------
 1  |          |          |
    -----------------------
 2  |    52    |    52    |
    -----------------------
 3  |   16277  |  16277   |
    -----------------------
 4  |   16277  |  21785   |
    -----------------------
 5  |   16277  | 5411828  |
    -----------------------
 6  |   21785  | 54112528 |
    -----------------------
 7  |  5411828 |   37-50  |
    -----------------------
 8  | 54112528 |   42-B   |
    -----------------------
 9  |   10 B   |  ABC-01  |
    -----------------------
10  |   10-M   |          |
    -----------------------
11  |   15-94  |          |
    -----------------------
12  |  15-971/ |          |
    -----------------------
13  |   16.    |          |
    -----------------------
14  |   16..   |          |
    -----------------------
15  |   22-23  |          |
    -----------------------
16  |   37-50  |          |
    -----------------------
17  |   42-B   |          |
    -----------------------
18  |  ABC-01  |          |
    -----------------------


问:
How to include a radio-button and a text field in a same if/else function?
I’m new in coding. Maybe it a basics question, but still...
I have a number field which assigns different values to another field with if / else statements, depending on the entered value (number >80 assigns 1, number between 50 and 80 assigns 2 and numbers <50 assigns 3). I have also a radio button, which, if checked, must assign a value (in my case “4”) to the same field and if the radio-button is checked it mustn’t allowed any change trough the number field (4 stays as an assigned value, no matter what number is or will be entered in number field).
Both codes worked separately, but I have a problem to merge them together.
Your help is appreciated.
V

EDIT: I edited the code after the comment from Sumeet, but this doesn’t solve my original question - how to include both in a same if/else statement?

```<code><input id="testscore" type="number" name="testscore">Test score
<br />
<input id="final" type=“text” name="final" readonly="true">Final score class
<br />
<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no
<br />

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if $("#radio1").is(':checked')){
    $("#final").val(4);
  } else {
    $("#final").val(0);
  }
});
</code>```

答:
try it: codepen

You can use document.querySelector('#radio1').checked instead $("#radio1").is(':checked')

Body:
I’m new in coding. Maybe it a basics question, but still...
I have a number field which assigns different values to another field with if / else statements, depending on the entered value (number >80 assigns 1, number between 50 and 80 assigns 2 and numbers <50 assigns 3). I have also a radio button, which, if checked, must assign a value (in my case “4”) to the same field and if the radio-button is checked it mustn’t allowed any change trough the number field (4 stays as an assigned value, no matter what number is or will be entered in number field).
Both codes worked separately, but I have a problem to merge them together.
Your help is appreciated.
V

EDIT: I edited the code after the comment from Sumeet, but this doesn’t solve my original question - how to include both in a same if/else statement?

<input id="testscore" type="number" name="testscore">Test score

<input id="final" type=“text” name="final" readonly="true">Final score class

<input id="radio1" class="radio" type="radio" name="test" value="4">yes
<input id="radio2" class="radio" type="radio" name="test" value="0">no

function getFinalScore() {
  var testScore = parseFloat($("#testscore").val());
  if (testScore >80){
    $('#final').val(1);
  } else if (testScore <=80 && testScore >50){
    $('#final').val(2);
  } else {
    $('#final').val(3);
  }
}
$(document).ready(function() {
  $('#testscore').keyup(function(event) {
    getFinalScore();
  });
});

$('input').click(function(e){
  if $("#radio1").is(':checked')){
    $("#final").val(4);
  } else {
    $("#final").val(0);
  }
});


问:
Non-recursive way to get all files in a directory and its subdirectories in Java
I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:

```<code>private void printFiles(File dir) {
  for (File child : dir.listFiles()) {
    if (child.isDirectory()) {
      printFiles(child);
    } else if (child.isFile()) {
      System.out.println(child.getPath());
    }
  }
}

printFiles(new File("somedir/somedir2"));
</code>```

However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?

答:
Java 8 onward, you can use Files#walk to list out all files and directories recursively in a given directory. Further you can apply the filter like Files::isRegularFile to filter out the directories if you need only regular files.

On the flip side, if you only need to list the given directory but not its sub-directories, you can use the lazy method Files#list which will only give you the files and directories in the given directory. You can again further apply the filter mentioned above.

Body:
I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:

private void printFiles(File dir) {
  for (File child : dir.listFiles()) {
    if (child.isDirectory()) {
      printFiles(child);
    } else if (child.isFile()) {
      System.out.println(child.getPath());
    }
  }
}

printFiles(new File("somedir/somedir2"));

However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?


问:
Java FX Bindings: bind a dynamic list of boolean properties
I'm trying to create a BooleanProperty for my CustomPane, let's call it isEmpty.

This property should be true when a collection (filled at runtime) of TextField objects matches a condition. This list does not change its content once given.

In this case the condition is that all fields must be empty (no text in any of the fields).

So when the CustomPane object is constructed, I have the list of fields and I should bind all their .textProperty().isEmpty() toghether.

Any suggetions on how I could do this?

答:
You could do something like this:</p>

```<code>private BooleanBinding areTheyEmptyBinding(List<TextField> list){
    BooleanBinding bind = new SimpleBooleanProperty(false).not();
    for (TextField text: list)
        bind = bind.and(text.textProperty().isEmpty());
    return bind;
}
</code>```

Body:
You could do something like this:

private BooleanBinding areTheyEmptyBinding(List<TextField> list){
    BooleanBinding bind = new SimpleBooleanProperty(false).not();
    for (TextField text: list)
        bind = bind.and(text.textProperty().isEmpty());
    return bind;
}


问:
Pentaho spoon is not starting
I'm just trying to open the GUI interface, but it is not opening and without any reason, any error message.
Any Idea?

C:\software\data-integration>Spoon.bat
DEBUG: Using JAVA_HOME
DEBUG: _PENTAHO_JAVA_HOME=C:\Program Files\Java\jre1.8.0_152
DEBUG: _PENTAHO_JAVA=C:\Program Files\Java\jre1.8.0_152\bin\javaw.exe

C:\software\data-integration>start "Spoon" "C:\Program Files\Java\jre1.8.0_152\bin\javaw.exe"  "-Xms1024m" "-Xmx1024m" "-XX:MaxPermSize=256m" "-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2" "-Djava.library.path=libswt\win64" "-DKETTLE_HOME=C:\software\data-integration\" "-DKETTLE_REPOSITORY=" "-DKETTLE_USER=" "-DKETTLE_PASSWORD=" "-DKETTLE_PLUGIN_PACKAGES=" "-DKETTLE_LOG_SIZE_LIMIT=" "-DKETTLE_JNDI_ROOT=" -jar launcher\pentaho-application-launcher-8.0.0.0-28.jar -lib ..\libswt\win64
```

答:
Try this:

Set PENTAHO_JAVA _HOME = C:\Pentaho\Java
AND
Set a system variable called JRE_HOME = C:\Program Files\Java\jdk1.8.0_144\jre

Mine is setup the same way and works perfectly fine. Let me know how it goes.

Title: Pentaho spoon is not starting


问:
Wait for set of qsub jobs to complete
I have a batch script which starts off a couple of qsub jobs, and I want to trap when they are all completed.

I don't want to use the -sync option, because I want them to be running simultaneously. Each job has a different set of command line parameters.

I want my script to wait till when all the jobs have been completed, and do something after that. I don't want to use the sleep function e.g. to check if certain files have been generated after each 30 s, because this is a drain on resources.

I believe Torque may have some options, but I am running SGE.

Any ideas on how I could implement this please?

Thanks
P.s.
I did find another thread
Link

which had a reponse

You can use wait to stop execution until all your jobs are done. You can even collect all the exit statuses and other running statistics (time it took, count of jobs done at the time, whatever) if you cycle around waiting for specific ids.

but I am not sure how to use it without polling on some value. Can bash trap be used, but how would I with qsub?

答:
I needed more flexibility, so I built a Python module for this and other purposes here. You can run the module directly as a script (python qsub.py) for a demo.

Usage:

```<code>$ git clone https://github.com/stevekm/util.git
$ cd util
$ python
Python 2.7.3 (default, Mar 29 2013, 16:50:34)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import qsub
>>> job = qsub.submit(command = 'echo foo; sleep 60', print_verbose = True)
qsub command is:

qsub -j y -N "python" -o :"/home/util/" -e :"/home/util/" <<E0F
set -x
echo foo; sleep 60
set +x
E0F

>>> qsub.monitor_jobs(jobs = [job], print_verbose = True)
Monitoring jobs for completion. Number of jobs in queue: 1
Number of jobs in queue: 0
No jobs remaining in the job queue
([Job(id = 4112505, name = python, log_dir = None)], [])
</code>```

Designed with Python 2.7 and SGE since thats what our system runs. The only non-standard Python libraries required are the included tools.py and log.py modules, and sh.py (also included)

Obviously not as helpful if you wish to stay purely in bash, but if you need to wait on qsub jobs then I would imagine your workflow is edging towards a complexity that would benefit from using Python instead.

Title: Wait for set of qsub jobs to complete

Body:
I needed more flexibility, so I built a Python module for this and other purposes here. You can run the module directly as a script (python qsub.py) for a demo.

Usage:

$ git clone https://github.com/stevekm/util.git
$ cd util
$ python
Python 2.7.3 (default, Mar 29 2013, 16:50:34)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import qsub
>>> job = qsub.submit(command = 'echo foo; sleep 60', print_verbose = True)
qsub command is:

qsub -j y -N "python" -o :"/home/util/" -e :"/home/util/" <<E0F
set -x
echo foo; sleep 60
set +x
E0F

>>> qsub.monitor_jobs(jobs = [job], print_verbose = True)
Monitoring jobs for completion. Number of jobs in queue: 1
Number of jobs in queue: 0
No jobs remaining in the job queue
([Job(id = 4112505, name = python, log_dir = None)], [])

Designed with Python 2.7 and SGE since thats what our system runs. The only non-standard Python libraries required are the included tools.py and log.py modules, and sh.py (also included)

Obviously not as helpful if you wish to stay purely in bash, but if you need to wait on qsub jobs then I would imagine your workflow is edging towards a complexity that would benefit from using Python instead.


问:
IF ELSE inside Load data infile mysql
I am trying to insert some data using Load data infile into a mysql table that already has some data. The table contains id and name. My csv file contains three fields: id, name and code. The table schema also has these three fields, but currently, the table has NULL for the code field. I am trying to insert the code from csv to an existing row in the table if it matches the name, else I am trying to insert a complete new row.

The code I have tried is as follows:

```
   LOAD DATA INFILE 'table1.csv'
   INTO TABLE table1
   FIELDS TERMINATED BY ','
   LINES TERMINATED BY '\n'
   IGNORE 1 LINES
   (@code, @name, @other_columns)
   IF EXISTS (SELECT * FROM table1 where name=@name);
   BEGIN
   set code=@Code;
   END
   ELSE
   BEGIN
   set code=@Code, name=@name;
   END
```

By doing so, I am getting a mysql syntax error, but am unable to figure it out. Can anyone point me in the right direction, or suggest to me another approach? I have thousands of new rows to insert and thousands of existing rows to modify based on the certain field, (name in this case).

答: MySQL does not allow the LOAD DATA INFILE statement inside a stored program, which is where the IF statement appears. Break up your task into two parts. First, LOAD DATA INFILE into a temporary table. Then create a stored program that replaces the loaded data into your table1 from the temporary table.

Title: IF ELSE inside Load data infile mysql

Body:
I am trying to insert some data using Load data infile into a mysql table that already has some data. The table contains id and name. My csv file contains three fields: id, name and code. The table schema also has these three fields, but currently, the table has NULL for the code field. I am trying to insert the code from csv to an existing row in the table if it matches the name, else I am trying to insert a complete new row.

The code I have tried is as follows:

   LOAD DATA INFILE 'table1.csv'
   INTO TABLE table1
   FIELDS TERMINATED BY ','
   LINES TERMINATED BY '\n'
   IGNORE 1 LINES
   (@code, @name, @other_columns)
   IF EXISTS (SELECT * FROM table1 where name=@name);
   BEGIN
   set code=@Code;
   END
   ELSE
   BEGIN
   set code=@Code, name=@name;
   END

By doing so, I am getting a mysql syntax error, but am unable to figure it out. Can anyone point me in the right direction, or suggest to me another approach? I have thousands of new rows to insert and thousands of existing rows to modify based on the certain field, (name in this case).


问:
Firebase Analytic for Phonegap/Cordova App
I have developed fews apps using Phonegap/Cordova. I'd like to integrate Firebase Analytics instead of Google Analytics. Is it possible? Is there any Cordova Plugin for Firebase Analytics? Please explain.

Also I don't find web support for Firebase Analytics in the official documentation samples

答:
Another Cordova plugin, although this is only for Analytics (one: https://github.com/chemerisuk/cordova-plugin-firebase-analytics

To debug your events remember to properly configure your apps as described here.


问:
Must variadic template have callable specialization with non empty parameter pack to be well-formed?
On the one hand there is the rule [temp.res]/8.3 which states that if every valid specialization of a variadic template requires an empty template parameter pack the program is ill-formed and no diagnostic is required. On the other hand one can imagine the situation when one can explicit instantiate any desired specialization of the template but cannot call it [temp.mem]/5.note-1, e.g.:

```<code>struct foo {
    template <class... Ts>
    foo() { }
};

template
foo::foo<int, float, double>();
</code>```

Is the code well-formed or the fact one cannot call any valid specialization apart from the one with empty template parameter pack violates the [temp.res]/8.3 rule?

答:
This reminds me a little of the Haskell function absurd:

```<code>-- | Since 'Void' values logically don't exist, this witnesses the logical
-- reasoning tool of \"ex falso quodlibet\".
absurd :: Void -> a
</code>```

What this means is a function that takes an instance of Void and returns an instance of any type. What does it mean to say that a function can invent an instance of any type out of thin air from nothing? It doesn't matter, because you can't come up with an instance of Void to pass into it.

Similarly here. In my opinion, the code is well-formed, if silly. There is nothing here that requires Ts... to be an empty pack. If Ts... were non-empty, the program would still be fine. The fact that there's no way to make Ts... non-empty seems orthogonal - if you could come up with a construct that made a non-empty Ts that led to the program being ill-formed, maybe [temp.res]/8.3 would apply - but you can't so... ¯\_(ツ)_/¯

Body:
On the one hand there is the rule [temp.res]/8.3 which states that if every valid specialization of a variadic template requires an empty template parameter pack the program is ill-formed and no diagnostic is required. On the other hand one can imagine the situation when one can explicit instantiate any desired specialization of the template but cannot call it [temp.mem]/5.note-1, e.g.:

struct foo {
    template <class... Ts>
    foo() { }
};

template
foo::foo<int, float, double>();

Is the code well-formed or the fact one cannot call any valid specialization apart from the one with empty template parameter pack violates the [temp.res]/8.3 rule?

Body:
This reminds me a little of the Haskell function absurd:

-- | Since 'Void' values logically don't exist, this witnesses the logical
-- reasoning tool of \"ex falso quodlibet\".
absurd :: Void -> a

What this means is a function that takes an instance of Void and returns an instance of any type. What does it mean to say that a function can invent an instance of any type out of thin air from nothing? It doesn't matter, because you can't come up with an instance of Void to pass into it.

Similarly here. In my opinion, the code is well-formed, if silly. There is nothing here that requires Ts... to be an empty pack. If Ts... were non-empty, the program would still be fine. The fact that there's no way to make Ts... non-empty seems orthogonal - if you could come up with a construct that made a non-empty Ts that led to the program being ill-formed, maybe [temp.res]/8.3 would apply - but you can't so... ¯\_(ツ)_/¯


问:
Inner Join in Django
I have two tables

front_employee (Employee model in Django)

```<code>+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| order           | int(11)      | NO   |     | NULL    |                |
| name            | varchar(100) | YES  |     | NULL    |                |
| position        | varchar(100) | YES  |     | NULL    |                |
| description     | longtext     | YES  |     | NULL    |                |
| employee_img_id | int(11)      | NO   | MUL | NULL    |                |
| language_id     | int(11)      | NO   | MUL | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
</code>```

And front_employeepicture (EmployeePicture in Django)

```<code>+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| order | int(11)      | NO   |     | NULL    |                |
| img   | varchar(100) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
</code>```

I would like to perform this query:

```<code>SELECT a.id, a.name, b.img
FROM front_employee a
INNER JOIN front_employeepicture b
ON a.employee_img_id = b.id
</code>```

For now I have

```<code>context['employee'] = Employee.objects.all().order_by('order')
</code>```

And I tried something like

```<code>context['employee'] = Employee.objects.select_related('EmployeePicture')
</code>```

Without result. Any idea?

答:
Django's ORM is really powerful. You actually don't have to do joins like that, ever. When you access the field, the ORM performs the join on the fly, returning the result you want.

```<code>first_employee = Employee.objects.all().first()
employee_picture = first_employee.employee_img
</code>```

And then employee_picture should have the picture of the first employee. It needed to internally do an inner join to figure that out, but Django hides all that for you. (I may have gotten your variable names wrong, sorry).

What select_related does is pre-fetch a relation for every object in a queryset. That means less trips back and forth to the database, which makes your functions faster. But, Django allows you to traverse relationships just by accessing attributes.

Try messing around with this stuff in your django shell. I would add django_extensions to your app (pip install django-extensions, then add django_extensions to your INSTALLED_APPS, then run python manage.py shell_plus). And if not, python manage.py shell works fine, but you have to import your models manually.

Title: Inner Join in Django

Body:
I have two tables

front_employee (Employee model in Django)

+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| order           | int(11)      | NO   |     | NULL    |                |
| name            | varchar(100) | YES  |     | NULL    |                |
| position        | varchar(100) | YES  |     | NULL    |                |
| description     | longtext     | YES  |     | NULL    |                |
| employee_img_id | int(11)      | NO   | MUL | NULL    |                |
| language_id     | int(11)      | NO   | MUL | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+

And front_employeepicture (EmployeePicture in Django)

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| order | int(11)      | NO   |     | NULL    |                |
| img   | varchar(100) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

I would like to perform this query:

SELECT a.id, a.name, b.img
FROM front_employee a
INNER JOIN front_employeepicture b
ON a.employee_img_id = b.id

For now I have

context['employee'] = Employee.objects.all().order_by('order')

And I tried something like

context['employee'] = Employee.objects.select_related('EmployeePicture')

Without result. Any idea?

Body:
Django's ORM is really powerful. You actually don't have to do joins like that, ever. When you access the field, the ORM performs the join on the fly, returning the result you want.

first_employee = Employee.objects.all().first()
employee_picture = first_employee.employee_img

And then employee_picture should have the picture of the first employee. It needed to internally do an inner join to figure that out, but Django hides all that for you. (I may have gotten your variable names wrong, sorry).

What select_related does is pre-fetch a relation for every object in a queryset. That means less trips back and forth to the database, which makes your functions faster. But, Django allows you to traverse relationships just by accessing attributes.

Try messing around with this stuff in your django shell. I would add django_extensions to your app (pip install django-extensions, then add django_extensions to your INSTALLED_APPS, then run python manage.py shell_plus). And if not, python manage.py shell works fine, but you have to import your models manually.


问:
How to get the last dir from a path in a string
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

```<code>result = test
</code>```

答:
```<code><?php
$path = explode('/', $yourPathVar);
// array_pop gives you the last element of an array()
$last = array_pop($path);
?>
</code>```

Body:
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test

ContentLicense: CC BY-SA 2.5


问:
Error in get_map using ggmap in R
About 90% of the time, when using get_map in ggmap, I get the following error. Can someone please tell me why?

```<code>map <- get_map(location = 'Australia', zoom = 4)
</code>```

Error in download.file(url, destfile = destfile, quiet = !messaging,
  mode = "wb") :    cannot open URL
  'http://maps.googleapis.com/maps/api/staticmap?center=Australia&zoom=4&size=%20640x640&scale=%202&maptype=terrain&sensor=false'
  In addition: Warning message: In download.file(url, destfile =
  destfile, quiet = !messaging, mode = "wb") :   cannot open: HTTP
  status was '403 Forbidden'

答:
The problem is likely related to your API project not being authorized by Google.

An API project is easy to create, and get authorized:

Click this link and choose create. Alternatively choose select if you already have a created project, but just need to activate the API.
After that choose "Enable".
After that your code should work.

Link again:
https://console.developers.google.com/apis/api/static_maps_backend?project=_

Title: Error in get_map using ggmap in R

Body:
About 90% of the time, when using get_map in ggmap, I get the following error. Can someone please tell me why?

map <- get_map(location = 'Australia', zoom = 4)

Error in download.file(url, destfile = destfile, quiet = !messaging,
  mode = "wb") :    cannot open URL
  'http://maps.googleapis.com/maps/api/staticmap?center=Australia&zoom=4&size=%20640x640&scale=%202&maptype=terrain&sensor=false'
  In addition: Warning message: In download.file(url, destfile =
  destfile, quiet = !messaging, mode = "wb") :   cannot open: HTTP
  status was '403 Forbidden'


问:
Echo page description from Yoast on wordpress
I have installed Wordpress SEO by Yoast onto a site Im building. They have an area when you can add the description for the meta information.

However I want to add this to a twitter meta tag:

```<code><meta name="twitter:description" content="">
</code>```

Does anyone know how to grab the description and output it for a single page?

Cheers

答:
wpseo_get_value('metadesc'); has been deprecated

Please use WPSEO_Meta::get_value("metadesc");

```<code><?php echo WPSEO_Meta::get_value("metadesc"); ?>
</code>```

Body:
I have installed Wordpress SEO by Yoast onto a site Im building. They have an area when you can add the description for the meta information.

However I want to add this to a twitter meta tag:

<meta name="twitter:description" content="">

Does anyone know how to grab the description and output it for a single page?

Cheers

Body:
wpseo_get_value('metadesc'); has been deprecated

Please use WPSEO_Meta::get_value("metadesc");

<?php echo WPSEO_Meta::get_value("metadesc"); ?>


问:
How to return the first exception that occurred?
There's a method called validate which as input accepts an instance of Option and a Predicate - two arguments (yeah, I know Option should be passed as an argument but this is simplified real-world scenario here. Now, if Option is empty I need to throw NotFoundException. When it has a value that doesn't match the Predicate passed it should fail with ForbiddenException. If it has value and it matches the predicate nothing happens.

So this will be:

```<code>                Option, Predicate
                     /\
          isEmpty() /  \ isDefined()
                   /    \
            throw NFE    matches(Predicate)
                        / \
                    no /   \ yes
                      /     \
                throw FE     end
</code>```

I have some solutions but would like potential answerers to come to this question with clear mind ;) My problem is getting the first exception if both tests fail. I expect an elegant solution if I may expect anything ;) All vavr beings allowed (Either, Validation, Try..)

One of the ideas is to use double Option:

```<code>Option
  .of(o.getOrElseThrow(NotFoundException::new))
  .filter(p)
  .getOrElseThrow(ForbiddenException::new);
</code>```

But this seems a bit awkward.

Here sample project may be found.

答:
This would be the solution with Optional (don't have the time to check vavr but should be close enough)

```<code>public static <T> void validate( Optional<T> optional, Predicate<T> pred ) throws NotFoundException, ForbiddenException {
    if ( !pred.test( optional.orElseThrow( NotFoundException::new ) ) )
        throw new ForbiddenException();
}
</code>```

Don't know a prettier way to throw that ForbiddenException unfortunately.

If you want a full functional solution, you will need an Optional

```<code>Optional.of(
    pred.test(
       option.orElseThrow( NotFoundException::new )
    )
).filter( b -> b ).orElseThrow( ForbiddenException::new );
</code>```

The exception are thrown in the correct order since we only check the Predicate after the option check.

Body:
There's a method called validate which as input accepts an instance of Option and a Predicate - two arguments (yeah, I know Option should be passed as an argument but this is simplified real-world scenario here. Now, if Option is empty I need to throw NotFoundException. When it has a value that doesn't match the Predicate passed it should fail with ForbiddenException. If it has value and it matches the predicate nothing happens.

So this will be:

                Option, Predicate
                     /\
          isEmpty() /  \ isDefined()
                   /    \
            throw NFE    matches(Predicate)
                        / \
                    no /   \ yes
                      /     \
                throw FE     end

I have some solutions but would like potential answerers to come to this question with clear mind ;) My problem is getting the first exception if both tests fail. I expect an elegant solution if I may expect anything ;) All vavr beings allowed (Either, Validation, Try..)

One of the ideas is to use double Option:

Option
  .of(o.getOrElseThrow(NotFoundException::new))
  .filter(p)
  .getOrElseThrow(ForbiddenException::new);

But this seems a bit awkward.

Here sample project may be found.

Body:
This would be the solution with Optional (don't have the time to check vavr but should be close enough)

public static <T> void validate( Optional<T> optional, Predicate<T> pred ) throws NotFoundException, ForbiddenException {
    if ( !pred.test( optional.orElseThrow( NotFoundException::new ) ) )
        throw new ForbiddenException();
}

Don't know a prettier way to throw that ForbiddenException unfortunately.

If you want a full functional solution, you will need an Optional

Optional.of(
    pred.test(
       option.orElseThrow( NotFoundException::new )
    )
).filter( b -> b ).orElseThrow( ForbiddenException::new );

The exception are thrown in the correct order since we only check the Predicate after the option check.


问:
Starting a SQL server
I'm trying to learn web programming and I don't know what I need to do.

What I'm trying to do: download data from a 3rd party website and load it into my own private SQL database.

What I've done so far: I'm working in visual studio 2017, I've got a console JavaScript project that gets the data via https request.  I've also got a SQL server project working with a table ready to receive the data. I can make entries by manually doing an insert query using the visual studio interface.

What do I do next?  How do I get the SQL server to listen for insert requests from an app? How do I get the data(simple arrays of numbers with no json or xml labels) from the JavaScript app to the sql server?

Once I get the JavaScript app and the server talking to eachother, can I take the next step and just have the sql server make the https requests directly?

答:
Hoping that your are using nodejs application.
First install mssql

```<code> npm install mssql
</code>```

You can try something like this.

```<code>const sql = require('mssql')

async () => {
    try {
        const pool = await sql.connect('mssql://username:password@localhost/database')
        const result = await sql.query`insert into  ... // your query`
        console.dir(result)
    } catch (err) {
        // ... error checks
    }
}
</code>```

If you are not using nodejs probably any language might have basic mysql connector which you could install and start using

Title: Starting a SQL server

Body:
Hoping that your are using nodejs application.
First install mssql

 npm install mssql

You can try something like this.

const sql = require('mssql')

async () => {
    try {
        const pool = await sql.connect('mssql://username:password@localhost/database')
        const result = await sql.query`insert into  ... // your query`
        console.dir(result)
    } catch (err) {
        // ... error checks
    }
}

If you are not using nodejs probably any language might have basic mysql connector which you could install and start using


问:
Adding animation to my images with JQuery
Here is my home page:

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">
<table id="home" style="margin-left: auto; margin-right:auto;">
    <td id="homeLinks">
        <div style="padding-left:35px;" id="homeListing" class="containerMid">
            <div id="homeView">
                <table style="margin-left: auto; margin-right:auto;">
                    <tr>
                        <tr>
                            <td id="btnIcOld" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />
                            </td>
                            <td id="btnIc" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />
                            </td>
                            <td id="btnPricing" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnSheets" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnPort" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />
                            </td>
                            <td id="btnAdmin" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />
                            </td>
                        </tr>
                        <tr>
                            <td id="Td1">
                                <b>Indications Calculator | </b>
                            </td>
                            <td id="lblIc">
                                <b>Indications Calculator - Beta | </b>
                            </td>
                            <td id="lblPricing">
                                <b>Managing Pricing Triggers | </b>
                            </td>
                            <td id="lblSheets">
                                <b>Creating Pricing Sheets | </b>
                            </td>
                            <td id="lblPort">
                                <b>Portfolio Analysis | </b>
                            </td>
                            <td id="lblAdmin">
                                <b>Administration</b>
                            </td>
                        </tr>
                    </tr>
                </table>
            </div>
        </div>
    </td>
</table>

<div id="pageMessage"></div>

<script>
    $(document).ready(function () {

        $('#btnIc').live('click', function () {
            window.location.href = "<%=Url.Action("Indications") %>";
        });

        $('#btnIcOld').live('click', function () {
            window.location.href = 'https://extranetint/swap';
        });

        $('#btnPricing').live('click', function () {
            //window.location.href = "<%=Url.Action("Triggers") %>";
        });

        $('#btnSheets').live('click', function () {
            //window.location.href = "<%=Url.Action("Sheets") %>";
        });

        $('#btnPort').live('click', function () {
            //window.location.href = "<%=Url.Action("Analysis") %>";
        });

        $('#btnAdmin').live('click', function () {
            //window.location.href = "<%=Url.Action("Admin") %>";
        });

    });
</script>
</asp:Content>
</code>```

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

答:
You can bind a hover event to all the img tags in your page or just the ones that is required and use 2 functions to animate the size for mousein and mouseout</p>

```<code>$(function(){
    $('img').hover(function(){
        $(this).animate({
            height: '110%',
            width: '110%',
        });
    },
    function(){
        $(this).animate({
            height: '100%',
            width: '100%',
        });
    });
});
</code>```

Body:
Here is my home page:

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />

                                Indications Calculator |

                                Indications Calculator - Beta |

                                Managing Pricing Triggers |

                                Creating Pricing Sheets |

                                Portfolio Analysis |

                                Administration

</asp:Content>

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

Body:
You can bind a hover event to all the img tags in your page or just the ones that is required and use 2 functions to animate the size for mousein and mouseout

$(function(){
    $('img').hover(function(){
        $(this).animate({
            height: '110%',
            width: '110%',
        });
    },
    function(){
        $(this).animate({
            height: '100%',
            width: '100%',
        });
    });
});


问:
Problems with constant iterators
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

```<code>    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/
</code>```

This code not working if i pass const iterators. What should I change to make it work with const iterators?

答:
Fixed your templated function for you (still requires non-const iterators):

```<code>template<class Iterator> size_t count_perm(Iterator p, Iterator q)
{
    if (p == q || std::all_of(p, q, [&](auto &el) {return el == *p; })))
        return 0;

    size_t count = 1;
    std::sort(p, q);

    while (std::next_permutation(p, q))
        if (std::adjacent_find(p, q) == q)
            ++count;

    return count;
}
</code>```

you should return count

when no adjacent elements are found, std::adjacent_find returns end, so you should == q not != q

Your example produces 6 and 37. Should it be 36 instead of 37?

Title: Problems with constant iterators

Body:
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/

This code not working if i pass const iterators. What should I change to make it work with const iterators?

Body:
Fixed your templated function for you (still requires non-const iterators):

template<class Iterator> size_t count_perm(Iterator p, Iterator q)
{
    if (p == q || std::all_of(p, q, [&](auto &el) {return el == *p; })))
        return 0;

    size_t count = 1;
    std::sort(p, q);

    while (std::next_permutation(p, q))
        if (std::adjacent_find(p, q) == q)
            ++count;

    return count;
}

you should return count

when no adjacent elements are found, std::adjacent_find returns end, so you should == q not != q

Your example produces 6 and 37. Should it be 36 instead of 37?


问:
SQL join three tables in a query

I'm trying to join 3 tables in my query. Here's the situation:

I have two tables (inscription and fees) that have their secondary key in a third table.

Inscription

Bills

Fees

I can find inscriptions and fees in bills. I'm able to associate an inscription to bills but not able to associate fees to an inscription.

When an inscription is placed, there are some fees applied to that inscription plus an inscription price itself.
BillID can have both inscription price and fees applied.

The table bills is an intermediate. I believe that if I have a BillID I am able to assign the fee to an inscription. But that is my challenge.

```<code>select
*
from bills i
left join  Inscription ip
on ip.Idinscription = i.IDinscription
left join  fees f
on f.IDfee = i.Idfee
</code>```

When I have IDfee, IDinscription is null and when I have IDinscription, IDfee is null as well. Both bill and fee have the same IDbill.

results requested

答:
EDIT
Try running the following:

```<code>SELECT DISTINCT * FROM bills i
LEFT JOIN inscription ip
ON ip.idInscription = i.idInscription
LEFT JOIN fees f ON f.idFee = i.idFee
WHERE i.idFee IS NOT NULL AND i.idInscription IS NOT NULL
</code>```

This query will present you the fees associated with each inscription. I believe the structure of your database is quite organized. One inscription has one bill, and each bill has numerous fees.

Title: SQL join three tables in a query

Body:
I'm trying to join 3 tables in my query. Here's the situation:

I have two tables (inscription and fees) that have their secondary key in a third table.

Inscription

Bills

Fees

I can find inscriptions and fees in bills. I'm able to associate an inscription to bills but not able to associate fees to an inscription.

When an inscription is placed, there are some fees applied to that inscription plus an inscription price itself.
BillID can have both inscription price and fees applied.

The table bills is an intermediate. I believe that if I have a BillID I am able to assign the fee to an inscription. But that is my challenge.

select
*
from bills i
left join  Inscription ip
on ip.Idinscription = i.IDinscription
left join  fees f
on f.IDfee = i.Idfee

When I have IDfee, IDinscription is null and when I have IDinscription, IDfee is null as well. Both bill and fee have the same IDbill.

results requested

Body:
EDIT
Try running the following:

SELECT DISTINCT * FROM bills i
LEFT JOIN inscription ip
ON ip.idInscription = i.idInscription
LEFT JOIN fees f ON f.idFee = i.idFee
WHERE i.idFee IS NOT NULL AND i.idInscription IS NOT NULL

This query will present you the fees associated with each inscription. I believe the structure of your database is quite organized. One inscription has one bill, and each bill has numerous fees.


问:
PDF generated was printing option blocked - Interop
I'm using the interface Microsoft.Office.Interop.Word.Document() to convert DOC/DOCX files to PDF, but the PDF files that are generated are with the print option blocked. I'm using the "SaveAs2" method, passing only two parameters which are the file name and file format.

Is there any way for the print option to always be unlocked for the pdf that is generated via Interop? Or is this an MS Office configuration?

```
public static string convertFileDocDocx(string fileDocDocx)
{
    try
    {
        if (fileDocDocx.ToUpper().Contains(".DOTX") || fileDocDocx.ToUpper().Contains(".DOCX") ||
            fileDocDocx.ToUpper().Contains(".DOT") || fileDocDocx.ToUpper().Contains(".DOC"))
        {
            var wordDoc = new Microsoft.Office.Interop.Word.Document();
            var wordApp = new Microsoft.Office.Interop.Word.Application();
            Object oMissing = System.Type.Missing;
            object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;</p>

<code>            wordDoc = wordApp.Documents.Add(fileDocDocx, oMissing, oMissing, oMissing);
            wordDoc = wordApp.Documents.Open(fileDocDocx, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                 oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                 oMissing, oMissing, oMissing);

            wordDoc.Activate();

            var secao = wordDoc.Sections[1];
            var rng = secao.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            var rng2 = secao.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

           if (fileDocDocx.Substring(fileDocDocx.Length - 4).ToUpper() == "DOTX" || fileDocDocx.Substring(fileDocDocx.Length - 4).ToUpper() == "DOCX")
              wordDoc.SaveAs2(fileDocDocx.Substring(0, fileDocDocx.Length - 5) + ".pdf", fileFormat);
          else if (fileDocDocx.Substring(fileDocDocx.Length - 3).ToUpper() == "DOT" || fileDocDocx.Substring(fileDocDocx.Length - 3).ToUpper() == "DOC")
              wordDoc.SaveAs2(fileDocDocx.Substring(0, fileDocDocx.Length - 4) + ".pdf", fileFormat);

          wordDoc.Close();
          System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
          wordDoc = null;

          wordApp.Quit();
          System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
          wordApp = null;

          System.GC.Collect();
          System.GC.WaitForPendingFinalizers();
      }
  }
  catch (Exception ex)
  {
      Util.insertLog(ex);
      Process[] processList = Process.GetProcesses();

      for (int i = 0; i < processList.Length; i++)
      {
          if (processList[i].ProcessName.Contains("WINWORD"))
              processList[i].Kill();
      }

      return "Error:" + ex.Message;
  }

  return fileDocDocx;
}
</code>```

答:
The following creates a printable PDF file:

```<code>using Word=Microsoft.Office.Interop.Word;
....
Word.Application winword = new Word.Application();
Word.Document document = winword.Documents.Open(@"C:\temp\Hallo.docx");

object SavePDFFormat = Word.WdSaveFormat.wdFormatPDF;

document.SaveAs2(@"C:\temp\Hallo.pdf", ref SavePDFFormat);
document.Close();
winword.Quit();
</code>```

Body:
I'm using the interface Microsoft.Office.Interop.Word.Document() to convert DOC/DOCX files to PDF, but the PDF files that are generated are with the print option blocked. I'm using the "SaveAs2" method, passing only two parameters which are the file name and file format.

Is there any way for the print option to always be unlocked for the pdf that is generated via Interop? Or is this an MS Office configuration?

public static string convertFileDocDocx(string fileDocDocx)
{
    try
    {
        if (fileDocDocx.ToUpper().Contains(".DOTX") || fileDocDocx.ToUpper().Contains(".DOCX") ||
            fileDocDocx.ToUpper().Contains(".DOT") || fileDocDocx.ToUpper().Contains(".DOC"))
        {
            var wordDoc = new Microsoft.Office.Interop.Word.Document();
            var wordApp = new Microsoft.Office.Interop.Word.Application();
            Object oMissing = System.Type.Missing;
            object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            wordDoc = wordApp.Documents.Add(fileDocDocx, oMissing, oMissing, oMissing);
            wordDoc = wordApp.Documents.Open(fileDocDocx, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                 oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                 oMissing, oMissing, oMissing);

            wordDoc.Activate();

            var secao = wordDoc.Sections[1];
            var rng = secao.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            var rng2 = secao.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

           if (fileDocDocx.Substring(fileDocDocx.Length - 4).ToUpper() == "DOTX" || fileDocDocx.Substring(fileDocDocx.Length - 4).ToUpper() == "DOCX")
              wordDoc.SaveAs2(fileDocDocx.Substring(0, fileDocDocx.Length - 5) + ".pdf", fileFormat);
          else if (fileDocDocx.Substring(fileDocDocx.Length - 3).ToUpper() == "DOT" || fileDocDocx.Substring(fileDocDocx.Length - 3).ToUpper() == "DOC")
              wordDoc.SaveAs2(fileDocDocx.Substring(0, fileDocDocx.Length - 4) + ".pdf", fileFormat);

          wordDoc.Close();
          System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
          wordDoc = null;

          wordApp.Quit();
          System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
          wordApp = null;

          System.GC.Collect();
          System.GC.WaitForPendingFinalizers();
      }
  }
  catch (Exception ex)
  {
      Util.insertLog(ex);
      Process[] processList = Process.GetProcesses();

      for (int i = 0; i < processList.Length; i++)
      {
          if (processList[i].ProcessName.Contains("WINWORD"))
              processList[i].Kill();
      }

      return "Error:" + ex.Message;
  }

  return fileDocDocx;
}

Body:
The following creates a printable PDF file:

using Word=Microsoft.Office.Interop.Word;
....
Word.Application winword = new Word.Application();
Word.Document document = winword.Documents.Open(@"C:\temp\Hallo.docx");

object SavePDFFormat = Word.WdSaveFormat.wdFormatPDF;

document.SaveAs2(@"C:\temp\Hallo.pdf", ref SavePDFFormat);
document.Close();
winword.Quit();


问:
Can I create a WordPress plugin with JavaScript only?
I am scared to ask this question, because StackOverflow is already warning me about my question being likely to be downvoted. But I am very curious about this.

I have read that you must have at least one php file in your WordPress Plugin. Which sounds to me like you only need something like an index/entry php file.

However, I wasn't able to find much about JavaScript in WordPress Plugins by using google. Which seemed weird to me, because we're talking here about the web of 2017.

An answer would be very appreciated!

答:
Since WordPress is (basically) purely php, then all its plugins will also be php. This is they way it has been set up.

In order to have a 'WordPress plugin', yes you will need at least one php file to register to WordPress and enqueue your javascript/css/what-have-you..

This means if you want something like React/Ember on your WP installation, they aren't going to be 'WordPress' plugins, they will belong to the React/Ember ecosystem. You will just have the minimum to enqueue the javascript libraries you want to use.

You can then use your javascript frontend and talk to WP's REST API, and now WP has basically become your server 'framework'.

So, no, there's no such thing as a 'JavaScript WordPress Plugin'. But you can have a plugin that includes as much fancy JS as you may want.


问:
About template specialization
I need to provide an insertion/lookup/delete interface for a hash table. I wrote the hash table only to provide the internal bucket/entry management. The hash function should be supplied from outside. I am now stuck on how to expose the interface so that the hash table can handle byte arrays as well as fixed length data types. The problem is that for byte arrays, the hash function needs to know the length of the array while for other types, it can do without that information. My problems is that I can't implement operator[] for byte arrays because the hash function needs two parameters. And I would like to keep operator[] dearly. Is there any way around this (Without specializing for T* and throwing a compiler error for operator[] in that specialization.)?

答:
can handle byte arrays as well as fixed length data types

So, your byte arrays vary in size.  You'll need to record the length of each somewhere.  If you want to store them in the hash table by value, then you can package up the data and a length value in an object: the STL already provides some classes suitable for this including std::vector<> and std::string<>.  Alternatively, if you only want the hash table to store pointers/references to your byte arrays, then you can create a trivial "handle" class that either stores or knows where to find the length, and has a pointer/reference to the data.

As "CashCow" points out, there is no inherent conflict between operator[] on the byte array and that on the hash table... they can even be chained if necessary.

Title: About template specialization


问:
Using Azure Search index to index blobs in Azure Blob Storage (Images and Videos)
I want to index blob of type image and video.
From what I have read Azure Search cannot index image and video types.

What I have done is that I was thinking of using the blob's metadata_storage_path. However that is my key and it is encoded.

Decoding it is really a performance killer.

Is there any way I can index images and videos, using azure search index?

If not, is there any other way?

答:
IIUC, you want to index the metadata attached to the blob but not its content, correct? If so, set dataToExtract parameter to storageMetadata as described in Controlling which parts of the blob are indexed.

The cost of base64-decoding the encoded metadata_storage_path to correlate with the rest of your system is likely to be negligible compared to other work your app is doing, such as calls to the database or Azure Search. However, you can avoid the need for decoding if you fork metadata_storage_path into a new non-key field in your index, which won't need to be encoded. You can use field mappings to fork the field.


问:
c++ array adjust all values by the same amount
My question is how to adjust all the values in an array by the same amount so that the smallest value will be zero. I don't know what way to go about it.</p>

答:
Below is the code which does what you want to do:</p>

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

int main() {
    int min,i;
    int A[] = {1,5,8,4,3,9,-2,4,-7,6};
    int n = (sizeof(A)/sizeof(A[0]));
    min = A[0];
    for(i=1;i<n;i++)
     if(A[i]<min)
      min = A[i];

    for(i=0;i<n;i++)
     A[i] = A[i] - min;

}
</code>```

Body:
Below is the code which does what you want to do:

 #include <iostream>
    using namespace std;

int main() {
    int min,i;
    int A[] = {1,5,8,4,3,9,-2,4,-7,6};
    int n = (sizeof(A)/sizeof(A[0]));
    min = A[0];
    for(i=1;i<n;i++)
     if(A[i]<min)
      min = A[i];

    for(i=0;i<n;i++)
     A[i] = A[i] - min;

}


问:
How to get window id from the title by swift3
How can I get a CGWindowID from the title of it?

I thought I can get list of titles by this code

```<code>let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]
</code>```

https://stackoverflow.com/a/31367468/1536527

But it seems there is no info for title of the windows.

How can I get CGWindowID or any info to specify a window by title?

答:
Actually the code snippet you posted seems to work for me. All I did was to iterate over the dictionary and find the window info for a given window title.

Here is the code:

```<code>func getWindowInfo(pname: String) -> Dictionary<String, AnyObject> {
    var answer = Dictionary<String, AnyObject>()
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]

    infoList?.forEach{eachDict in
        eachDict.keys.forEach{ eachKey in
            if (eachKey == "kCGWindowName" && eachDict[eachKey] != nil ){
                let name = eachDict[eachKey] as? String ?? ""
                print (name)
                if ( name == pname){
                    print("******** Found **********")
                    answer = eachDict as! Dictionary<String, AnyObject>
                }
            }
            print(eachKey , "-->" , eachDict[eachKey])
        }
    }
    return answer
}
</code>```

With the above function, I am able to get a window's details, including name for example.

I hope it works for you too.

Body:
How can I get a CGWindowID from the title of it?

I thought I can get list of titles by this code

let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]

https://stackoverflow.com/a/31367468/1536527

But it seems there is no info for title of the windows.

How can I get CGWindowID or any info to specify a window by title?

Body:
Actually the code snippet you posted seems to work for me. All I did was to iterate over the dictionary and find the window info for a given window title.

Here is the code:

func getWindowInfo(pname: String) -> Dictionary<String, AnyObject> {
    var answer = Dictionary<String, AnyObject>()
    let options = CGWindowListOption(arrayLiteral: CGWindowListOption.optionOnScreenOnly)
    let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
    let infoList = windowListInfo as NSArray? as? [[String: AnyObject]]

    infoList?.forEach{eachDict in
        eachDict.keys.forEach{ eachKey in
            if (eachKey == "kCGWindowName" && eachDict[eachKey] != nil ){
                let name = eachDict[eachKey] as? String ?? ""
                print (name)
                if ( name == pname){
                    print("******** Found **********")
                    answer = eachDict as! Dictionary<String, AnyObject>
                }
            }
            print(eachKey , "-->" , eachDict[eachKey])
        }
    }
    return answer
}

With the above function, I am able to get a window's details, including name for example.

I hope it works for you too.


答:
Use basename

```<code>basename('Home/new_folder/test');
// output: test
</code>```

As a side note to those who answered explode:

To get the trailing name component of a path you should use basename!
In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.

Title: How to get the last dir from a path in a string

Body:
I am trying to get the last folder name from a path that i store in a string.

e.g: Home/new_folder/test

result = test

Body:
Use basename

basename('Home/new_folder/test');
// output: test

As a side note to those who answered explode:

To get the trailing name component of a path you should use basename!
In case your path is something like $str = "this/is/something/" the end(explode($str)); combo will fail.