问:
Open pdf in default app using pdfmake
I am able to create pdf in my ionic app and if I run the app in chrome it opens perfectly. However if I install my app on the android device it doesn't open. Below is my code. Can someone please help me if I have to do something extra to open it on device. I want to open it with default pdf application on device.</p>

```<code>pdfMake.createPdf(dd).open();
</code>```

答:
Ok. After banging my head on wall for 3 days I finally found the solution and sharing here so that other people who are facing this issue can get help. I am creating pdf and saving it using cordova file plugin. After successful save I am opening it in default application using cordova file opener plugin. Below is my code.</p>

```<code>pdfMake.createPdf(YOUR_DEFINITION_HERE).getBlob(buffer => {
  this.file.resolveDirectoryUrl(this.file.externalRootDirectory)
   .then(dirEntry => {
      this.file.getFile(dirEntry, 'test1.pdf', { create: true })
        .then(fileEntry => {
          fileEntry.createWriter(writer => {
            writer.onwrite = () => {
              this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
                .then(res => { })
                .catch(err => {
                  const alert = this.alertCtrl.create({ message:
err.message, buttons: ['Ok'] });
                  alert.present();
                });
            }
            writer.write(buffer);
          })
        })
        .catch(err => {
          const alert = this.alertCtrl.create({ message: err, buttons: ['Ok'] });
          alert.present();
        });
    })
    .catch(err => {
      const alert = this.alertCtrl.create({ message: err, buttons: ['Ok']
});
      alert.present();
    });
});
</code>```

Title: Open pdf in default app using pdfmake

Body:
I am able to create pdf in my ionic app and if I run the app in chrome it opens perfectly. However if I install my app on the android device it doesn't open. Below is my code. Can someone please help me if I have to do something extra to open it on device. I want to open it with default pdf application on device.

pdfMake.createPdf(dd).open();

Body:
Ok. After banging my head on wall for 3 days I finally found the solution and sharing here so that other people who are facing this issue can get help. I am creating pdf and saving it using cordova file plugin. After successful save I am opening it in default application using cordova file opener plugin. Below is my code.

pdfMake.createPdf(YOUR_DEFINITION_HERE).getBlob(buffer => {
  this.file.resolveDirectoryUrl(this.file.externalRootDirectory)
   .then(dirEntry => {
      this.file.getFile(dirEntry, 'test1.pdf', { create: true })
        .then(fileEntry => {
          fileEntry.createWriter(writer => {
            writer.onwrite = () => {
              this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
                .then(res => { })
                .catch(err => {
                  const alert = this.alertCtrl.create({ message:
err.message, buttons: ['Ok'] });
                  alert.present();
                });
            }
            writer.write(buffer);
          })
        })
        .catch(err => {
          const alert = this.alertCtrl.create({ message: err, buttons: ['Ok'] });
          alert.present();
        });
    })
    .catch(err => {
      const alert = this.alertCtrl.create({ message: err, buttons: ['Ok']
});
      alert.present();
    });
});


来源: stackexchange

问:
Using jQuery I need to replace spaces inside href with hyphens
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

href="http://www.projectknow.com/find/New York/" class="spaces">

MUST BE REPLACED WITH

href="http://www.projectknow.com/find/New-York/" class="spaces">

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

```<code>var option = '';
for (var i = 0; i < states.length;i++){
    option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
    class="spaces">'+ states[i] +'</a></li>';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});
</code>```

答:
Use this code instead:</p>

```<code>$(this).attr('href', $(this).attr("href").replace(/\s/g, "-");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

MUST BE REPLACED WITH

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

var option = '';
for (var i = 0; i < states.length;i++){
    option += '
'+ states[i] +'
';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});

Body:
Use this code instead:

$(this).attr('href', $(this).attr("href").replace(/\s/g, "-");


问:
An object with the name already exist in the database just when I use constraint
When I use this script:

```<code>IF OBJECT_ID('dbo.TableX', 'U') IS NOT NULL
    DROP TABLE dbo.TableX

CREATE TABLE TableX
(
    ...
    ...
    ...

    CONSTRAINT TableX PRIMARY KEY (column1, column2, column3)
)
</code>```

I get an error

An object with the name 'TableX' already exist in the database

but that is only when I use the CONSTRAINT line.

Why do I get an error only when I use CONSTRAINT and how can I solve it?

答: That's because your Constaint name is the same as table name. Name it like PK_TableX</p>

Body:
When I use this script:

IF OBJECT_ID('dbo.TableX', 'U') IS NOT NULL
    DROP TABLE dbo.TableX

CREATE TABLE TableX
(
    ...
    ...
    ...

    CONSTRAINT TableX PRIMARY KEY (column1, column2, column3)
)

I get an error

An object with the name 'TableX' already exist in the database

but that is only when I use the CONSTRAINT line.

Why do I get an error only when I use CONSTRAINT and how can I solve it?


问:
How to check more than one year in 'leap year'
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable. </p>

```<code>int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}
</code>```

答:
One way to do this is to write a function that takes in an int and returns true if the int represents a leap year. For example, the method below uses a simplified, one-line version of the code you wrote above:

```<code>public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
</code>```

Then, you can get a bunch of years from the user (in this example we're using a comma-separated list of years), split the years into an array (on the comma character), and call this method for each year in a loop:

```<code>private static void Main()
{
    // Get a list of years from the user
    Console.Write("Enter some years separated by commas: ");
    var input = Console.ReadLine();

    // Split the user input on the comma character, creating an array of years
    var years = input.Split(',');

    foreach (var year in years)
    {
        bool isLeapYear = IsLeapYear(int.Parse(year));

        if (isLeapYear)
        {
            Console.WriteLine("{0} is a leap year", year);
        }
        else
        {
            Console.WriteLine("{0} is not a leap year", year);
        }

    }
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Another thing you can do, if you want to enter them one at a time, is just ask the user for a new year inside a loop, and give them the answer after they enter an integer. Here's an example, where I also added another function called GetIntFromUser, which forces them to enter a valid integer (it keeps asking until one is entered):

```<code>private static void Main()
{
    // In this loop, ask for a year and tell them the answer
    while (true)
    {
        int input = GetIntFromUser("Enter a year to check: ");
        string verb = IsLeapYear(input) ? "is" : "is not";
        Console.WriteLine($"{input} {verb} a leap year.\n");
    }
}

public static int GetIntFromUser(string prompt)
{
    int input;

    // Show the prompt and keep looping until the input is a valid integer
    do
    {
        Console.Write(prompt);
    } while (!int.TryParse(Console.ReadLine(), out input));

    return input;
}

public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
</code>```

Output

Body:
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable.

int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}

Body:
One way to do this is to write a function that takes in an int and returns true if the int represents a leap year. For example, the method below uses a simplified, one-line version of the code you wrote above:

public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

Then, you can get a bunch of years from the user (in this example we're using a comma-separated list of years), split the years into an array (on the comma character), and call this method for each year in a loop:

private static void Main()
{
    // Get a list of years from the user
    Console.Write("Enter some years separated by commas: ");
    var input = Console.ReadLine();

    // Split the user input on the comma character, creating an array of years
    var years = input.Split(',');

    foreach (var year in years)
    {
        bool isLeapYear = IsLeapYear(int.Parse(year));

        if (isLeapYear)
        {
            Console.WriteLine("{0} is a leap year", year);
        }
        else
        {
            Console.WriteLine("{0} is not a leap year", year);
        }

    }
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output

Another thing you can do, if you want to enter them one at a time, is just ask the user for a new year inside a loop, and give them the answer after they enter an integer. Here's an example, where I also added another function called GetIntFromUser, which forces them to enter a valid integer (it keeps asking until one is entered):

private static void Main()
{
    // In this loop, ask for a year and tell them the answer
    while (true)
    {
        int input = GetIntFromUser("Enter a year to check: ");
        string verb = IsLeapYear(input) ? "is" : "is not";
        Console.WriteLine($"{input} {verb} a leap year.\n");
    }
}

public static int GetIntFromUser(string prompt)
{
    int input;

    // Show the prompt and keep looping until the input is a valid integer
    do
    {
        Console.Write(prompt);
    } while (!int.TryParse(Console.ReadLine(), out input));

    return input;
}

public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

Output


问:
Tensorflow program results in type conversion error
Tring to master Tensorflow, following documentation of TensorFlow.

Below program results in 'Incompatible type conversion error'

```<code>import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = 1.0
linear_model = W * x + b
#tf.to_float(linear_model, name='ToFloat')

# Global initialization is must
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))
</code>```

Above program results in this error

File "v-prog3-variables.py", line 7, in
      linear_model = W * x + b
  .. .. ..
  ValueError: Incompatible type conversion requested to type 'float32'
  for variable of type 'int32_ref'

I tried to solve the problem by defining the 'linear_model' variable as float (linear_model = 1.0) or tf.to_float(linear_model = W * x + b)

but nothing works

Im a TensorFlow newbie, please help me out.
Thanks in advance.

答:
I was able to get it to run by recasting it to float32.  Have you read the source code of the library?  Yea... I don't ask questions lol</p>

```<code>import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)

linear_model = W * x + tf.cast(b, tf.float32)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))
</code>```

Body:
Tring to master Tensorflow, following documentation of TensorFlow.

Below program results in 'Incompatible type conversion error'

import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = 1.0
linear_model = W * x + b
#tf.to_float(linear_model, name='ToFloat')

# Global initialization is must
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))

Above program results in this error

File "v-prog3-variables.py", line 7, in
      linear_model = W * x + b
  .. .. ..
  ValueError: Incompatible type conversion requested to type 'float32'
  for variable of type 'int32_ref'

I tried to solve the problem by defining the 'linear_model' variable as float (linear_model = 1.0) or tf.to_float(linear_model = W * x + b)

but nothing works

Im a TensorFlow newbie, please help me out.
Thanks in advance.

Body:
I was able to get it to run by recasting it to float32.  Have you read the source code of the library?  Yea... I don't ask questions lol

import tensorflow as tf

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-3], tf.float32)
x = tf.placeholder(tf.float32)

linear_model = W * x + tf.cast(b, tf.float32)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

print(sess.run(linear_model, {x:[1,2,3,4]}))


问:
Vacuuming and Analyse : Drastic change in query cost
I have a Postgres 9.6 installation and I am running into this weird case where - if I run a same query having multiple joins after 10 to 15 mins, there is increase in the value of query cost in the order of few hundreds and its keep on increasing.

I do understand what vacuuming and analyse does, but I am worried about the query cost which starts increases within few minutes of performing vacuum and analyse. I am afraid this might lead do future performance bottlenecks.

PS: I have two table out of which one is heavily written (about 5 million records ) and other is heavily updated (70 K records with postGIS this table mostly have updates on lat lon & geom column)

Does this means I should have auto vacuum run every few hours?

答: Make Autovaccum aggressive; but if you think autovaccum is using up resources(by looking at cpu ]and IO usage) you could tweak-- autovacuum_vacuum_cost_delay and autovacuum_vacuum_threshold paramters at table level</p>


问:
top 10 comments of each messages
I have two tables. One for messages and one for comments. For each entry in messages table there will be multiple records in comments table.
Now I want to select the top 5 messages and top 10 comments for each message.
My table structure is

Messages

MID        Message

1         msg 1

2         msg 2

Comments

CID   MID   Comment   Date

1     1     Cmnt1     date 1

2     1     Cmnt2     date 2

3     1     Cmnt3     date 3

4     2     Cmnt4     date 4

5     2     Cmnt5     date 5

Thanks in Advance

-Arun

答:
You're question is a bit vague. However, assuming you have a field indicating your criteria for being "top", e.g. votes:

For MySQL you can use a select statement like this:

```<code>SELECT *
FROM comments
JOIN messages ON comments.mid = messages.mid
WHERE messages.mid = 1
ORDER BY comments.topvotes DESC
LIMIT 10;
</code>```

This query would give you the top 10 voted comments for message 1.

A more complex query for getting the comments sorted for the top five messages:

```<code>SELECT comments.cid
FROM comments
JOIN messages ON comments.mid = messages.mid
WHERE comments.mid IN(
        SELECT messages.mid
        FROM messages
        ORDER BY messages.votes DESC
        LIMIT 5)
ORDER BY messages.mid, comments.votes DESC;
</code>```

But I can't quite figure out, how to limit this to the 10 top comments. I would use a cursor, but I've been doing too much PLSQL on Oracle lately anyway. So if anyone got a good solution how to express that in a single select with a subquery, please shoot...

ContentLicense: CC BY-SA 2.5

Title: top 10 comments of each messages

Body:
You're question is a bit vague. However, assuming you have a field indicating your criteria for being "top", e.g. votes:

For MySQL you can use a select statement like this:

SELECT *
FROM comments
JOIN messages ON comments.mid = messages.mid
WHERE messages.mid = 1
ORDER BY comments.topvotes DESC
LIMIT 10;

This query would give you the top 10 voted comments for message 1.

A more complex query for getting the comments sorted for the top five messages:

SELECT comments.cid
FROM comments
JOIN messages ON comments.mid = messages.mid
WHERE comments.mid IN(
        SELECT messages.mid
        FROM messages
        ORDER BY messages.votes DESC
        LIMIT 5)
ORDER BY messages.mid, comments.votes DESC;

But I can't quite figure out, how to limit this to the 10 top comments. I would use a cursor, but I've been doing too much PLSQL on Oracle lately anyway. So if anyone got a good solution how to express that in a single select with a subquery, please shoot...


问:
E00007 : User authentication failed due to invalid authentication values. in auth.net
I am new to the Authorized.net API and facing the below E00007, User authentication failed due to invalid authentication values. in authorized.net. I am using the authorize.net version to call the GetTransactionDetails API.

Any idea on what is the issue ? Any help ?

```<code><dependency>
            <groupId>net.authorize</groupId>
            <artifactId>anet-java-sdk</artifactId>
            <version>1.8.6</version>
        </dependency>
</code>```

and I am using the below code

```<code>public class GetTransactionDetails {

    public static final String apiLoginId= "6LaBc8HJ6Q";
    public static final String transactionKey= "XXXXXXXX";

    public static void main(String[] args) {
        ApiOperationBase.setEnvironment(Environment.SANDBOX);

        MerchantAuthenticationType merchantAuthenticationType  = new MerchantAuthenticationType() ;
        merchantAuthenticationType.setName(apiLoginId);
        merchantAuthenticationType.setTransactionKey("transactionKey");

        ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);

        //need valid transacaction Id to run
        String transId = "60024624183";

        GetTransactionDetailsRequest getRequest = new GetTransactionDetailsRequest();
        getRequest.setMerchantAuthentication(merchantAuthenticationType);
        getRequest.setTransId(transId);

        GetTransactionDetailsController controller = new GetTransactionDetailsController(getRequest);
        controller.execute();
        GetTransactionDetailsResponse getResponse = controller.getApiResponse();

        TransactionDetailsType transactionDetailsType = getResponse.getTransaction();

        if (getResponse!=null) {
            if (getResponse.getMessages().getResultCode() == MessageTypeEnum.OK) {
                System.out.println(getResponse.getMessages().getMessage().get(0).getCode());
                System.out.println(getResponse.getMessages().getMessage().get(0).getText());

                System.out.println("---------------------------------------");
                System.out.println("Auth Amount                 : "+transactionDetailsType.getAuthAmount());
                System.out.println("Auth Code                   : "+transactionDetailsType.getAuthCode());
                System.out.println("Response Reason Description : "+transactionDetailsType.getResponseReasonDescription());
                System.out.println("Transaction Status          : "+transactionDetailsType.getTransactionStatus());
                System.out.println("Submit Date                 : "+transactionDetailsType.getSubmitTimeLocal());
            }else{
                System.out.println("Failed to get transaction details:  " + getResponse.getMessages().getResultCode());
                List<Message> messages = getResponse.getMessages().getMessage();
                for (Message message : messages) {
                    System.out.println("Code   : "+message.getCode());
                    System.out.println("Text   : "+message.getText());
                }
            }
        }
    }
}
</code>```

output:

```<code>06/02/17 00:35:48,733:  INFO [pool-1-thread-1] (net.authorize.util.LogHelper:24) - Use Proxy: 'false'
Failed to get transaction details:  ERROR
Code   : E00007
Text   : User authentication failed due to invalid authentication values.
</code>```

答:
Can you try removing the quotes from setTransactionKey

```<code>merchantAuthenticationType.setTransactionKey("transactionKey");
</code>```

change to

```<code>merchantAuthenticationType.setTransactionKey(transactionKey);
</code>```

Body:
I am new to the Authorized.net API and facing the below E00007, User authentication failed due to invalid authentication values. in authorized.net. I am using the authorize.net version to call the GetTransactionDetails API.

Any idea on what is the issue ? Any help ?

<dependency>
            <groupId>net.authorize</groupId>
            <artifactId>anet-java-sdk</artifactId>
            <version>1.8.6</version>
        </dependency>

and I am using the below code

public class GetTransactionDetails {

    public static final String apiLoginId= "6LaBc8HJ6Q";
    public static final String transactionKey= "XXXXXXXX";

    public static void main(String[] args) {
        ApiOperationBase.setEnvironment(Environment.SANDBOX);

        MerchantAuthenticationType merchantAuthenticationType  = new MerchantAuthenticationType() ;
        merchantAuthenticationType.setName(apiLoginId);
        merchantAuthenticationType.setTransactionKey("transactionKey");

        ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);

        //need valid transacaction Id to run
        String transId = "60024624183";

        GetTransactionDetailsRequest getRequest = new GetTransactionDetailsRequest();
        getRequest.setMerchantAuthentication(merchantAuthenticationType);
        getRequest.setTransId(transId);

        GetTransactionDetailsController controller = new GetTransactionDetailsController(getRequest);
        controller.execute();
        GetTransactionDetailsResponse getResponse = controller.getApiResponse();

        TransactionDetailsType transactionDetailsType = getResponse.getTransaction();

        if (getResponse!=null) {
            if (getResponse.getMessages().getResultCode() == MessageTypeEnum.OK) {
                System.out.println(getResponse.getMessages().getMessage().get(0).getCode());
                System.out.println(getResponse.getMessages().getMessage().get(0).getText());

                System.out.println("---------------------------------------");
                System.out.println("Auth Amount                 : "+transactionDetailsType.getAuthAmount());
                System.out.println("Auth Code                   : "+transactionDetailsType.getAuthCode());
                System.out.println("Response Reason Description : "+transactionDetailsType.getResponseReasonDescription());
                System.out.println("Transaction Status          : "+transactionDetailsType.getTransactionStatus());
                System.out.println("Submit Date                 : "+transactionDetailsType.getSubmitTimeLocal());
            }else{
                System.out.println("Failed to get transaction details:  " + getResponse.getMessages().getResultCode());
                List<Message> messages = getResponse.getMessages().getMessage();
                for (Message message : messages) {
                    System.out.println("Code   : "+message.getCode());
                    System.out.println("Text   : "+message.getText());
                }
            }
        }
    }
}

output:

06/02/17 00:35:48,733:  INFO [pool-1-thread-1] (net.authorize.util.LogHelper:24) - Use Proxy: 'false'
Failed to get transaction details:  ERROR
Code   : E00007
Text   : User authentication failed due to invalid authentication values.

Body:
Can you try removing the quotes from setTransactionKey

merchantAuthenticationType.setTransactionKey("transactionKey");

change to

merchantAuthenticationType.setTransactionKey(transactionKey);


答:
First, you put the existing code into a function, so it can be re-used:

```<code>public bool IsLeapYear(int year)
{
    bool div1 = year % 4 == 0;
    bool div2 = year % 100 != 0;
    bool div3 = year % 400 == 0;
    return ((div1 && div2) || div3);
}
</code>```

Then let's say you have a set of 40 years in an array:

```<code>//don't worry about how this works right now.
// just know it gives you an array with 40 years starting in 1980
int[] years = Enumerable.Range(1980, 40).ToArray();
</code>```

You can check all of them like this:

```<code>foreach (int year in years)
{
    if (IsLeapYear(year))
    {
        Console.WriteLine($"{year} is a leap year");
    }
    else
    {
        Console.WriteLine($"{year} is not a leap year");
    }
}
</code>```

Title: How to check more than one year in 'leap year'

Body:
First, you put the existing code into a function, so it can be re-used:

public bool IsLeapYear(int year)
{
    bool div1 = year % 4 == 0;
    bool div2 = year % 100 != 0;
    bool div3 = year % 400 == 0;
    return ((div1 && div2) || div3);
}

Then let's say you have a set of 40 years in an array:

//don't worry about how this works right now.
// just know it gives you an array with 40 years starting in 1980
int[] years = Enumerable.Range(1980, 40).ToArray();

You can check all of them like this:

foreach (int year in years)
{
    if (IsLeapYear(year))
    {
        Console.WriteLine($"{year} is a leap year");
    }
    else
    {
        Console.WriteLine($"{year} is not a leap year");
    }
}


问:
Manage namespace library (C#)
I am trying to organize a library. My issue is that it would quickly gets very large.

This is what i have so far:

```<code>namespace MyLibrary {

    namespace Math {

        namespace Geometry {

            public class BezierCurve {

                //...
            };
        }

        namespace Combinatorics {

        }
    }

    namespace Collections {

    }

    //...
}
</code>```

Its not many lines of code now, but since BezierCurve alone is around 200 lines, creating all of the classes in the above document is not going to be the way to go.

Is it possible to somehow specify the content of BezierCurve in another document and include / refer to it in the namespace Geometry?

答:
Multiple files can declare classes in the same namespace. There  is no requirement for a namespace to be fully defined within a single file.
You should have a file per class.
e.g. your BezierCurve would typically be in:
MyLibrary/Math/Geometry/BezierCurve.cs
and be declared within</p>

```<code>namespace MyLibrary.Math.Geometry
{
    public class BezierCurve
    {
    }
}
</code>```

Title: Manage namespace library (C#)

Body:
I am trying to organize a library. My issue is that it would quickly gets very large.

This is what i have so far:

namespace MyLibrary {

    namespace Math {

        namespace Geometry {

            public class BezierCurve {

                //...
            };
        }

        namespace Combinatorics {

        }
    }

    namespace Collections {

    }

    //...
}

Its not many lines of code now, but since BezierCurve alone is around 200 lines, creating all of the classes in the above document is not going to be the way to go.

Is it possible to somehow specify the content of BezierCurve in another document and include / refer to it in the namespace Geometry?

Body:
Multiple files can declare classes in the same namespace. There  is no requirement for a namespace to be fully defined within a single file.
You should have a file per class.
e.g. your BezierCurve would typically be in:
MyLibrary/Math/Geometry/BezierCurve.cs
and be declared within

namespace MyLibrary.Math.Geometry
{
    public class BezierCurve
    {
    }
}


问:
Is there a better way to write this switch in JavaScript?
I have a switch with the following conditions:

The first case is or between three names (ROKA, MOKA and TOKA).

The second case is another name (KOKA) but with two additional conditions to display an alert.

Lastly, I have some other conditions to check inside the default block, as I'm unable to use a case for them.

This is my code:

```<code>var myname= 'JOKA';
var dhaba = false;

switch (myname) {
  case ('ROKA'):
  case ('MOKA'):
  case ('TOKA'):
    alert('EEE');
    break;

  case ('KOKA'):
    // This will work as Goto to final default:

    if (condition1 && condition2) {
      alert('FEEE');
      break;
    }

  default:
    if (dhaba && myname != 'ROKA' && myname != 'TOKA') {
      alert('TEEEE');
    } else {
      alert('CHEEE');
    }
}
</code>```

Is there a better way to write this code?

答:
I think switch is not the best option for your use case.

Also, as @NinaScholz has pointed out, the myname != 'ROKA' && myname != 'TOKA' will always be true, as otherwise you will fall in the first case.

Let's go step by step and see different ways to refactor your code:

 Simplified (Non-Switch) Code

The easies and most straightforward way to write your code is like this:

```<code>const myname = 'JOKA';
const dhaba = false;

if ('ROKA' === myname || 'MOKA' === myname || 'TOKA' === myname) {
    alert('EEE');
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}
</code>```

Note how the redundant checks have been removed and the last if - else block have been replaced with a ternary operator.

It is possible that your code is not exactly like the example you provided or that it changes overtime. In that case, you may consider other options other than the above simplified code.

 Checking multiple matches from a single variable using Array.prototype.indexOf()

However, you may have a lot more elements to check in the first if. In that case you could use an Array and Array.prototype.indexOf() to check if there's any match inside it (it will return -1 if there isn't any):

```<code>const myname = 'JOKA';
const dhaba = false;

if (['ROKA', 'MOKA', 'TOKA'].indexOf(myname) !== -1) {
    alert('EEE');
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}
</code>```

 N Input - Output (String) Pairs + Complex Default with Switch

It is also possible that you have multiple myname values that map to multiple alert() params, so you may feel tempted to write something like this:

```<code>const myname = 'JOKA';
const dhaba = false;

switch(myname) {
    case 'XXX-1': alert('YYY-1'); break;
    case 'XXX-2': alert('YYY-2'); break;

    ...

    case 'XXX-N': alert('YYY-N'); break;

    default:
        if (myname === 'KOKA' && true && true) {
            alert('FEEE');
        } else {
            alert(dhaba ? 'TEEEE' : 'CHEEE');
        }
}
</code>```

While this is fine and, actually, I think it is cleaner and less error-prone than checking an additional condition inside a case block, as you did in your example, and based on that do something and break or let the next block execute, I would advise you to consider using object literal lookups instead.

 N Input - Output (String) Pairs + Complex Default with Object Literals Lookups

There are multiple advantages to use them: better readability, easier debugging, maintainability, concision (no need to add break, for example)... I think the most important one for you, as you added the tag performance in your question, is that it is more performant.

This is because while the switch has to evaluate each case condition until it fins a break, so their order matters, the object lookup is just a hash table lookup, that is, O(1).

With this in mind, we could refactor the last example like this:

```<code>const myname = 'JOKA';
const dhaba = false;

const output = {
    'XXX-1': 'YYY-1',
    'XXX-2': 'YYY-2',

    ...

    'XXX-N': 'YYY-N',
}[myname];

// Note output will be undefined if there isn't a match, so the first if
// will be evaluated to false in that scenario:

if (output) {
    alert(output);
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}
</code>```

 N Input - Output (String) Pairs + Single-Value Default with Object Literals Lookups  and || (or) Operator

Also, note that if your default were just using another value inside the if, you could do that with a simple || operator:

```<code>const myname = 'JOKA';

const output = {
    'XXX-1': 'YYY-1',
    'XXX-2': 'YYY-2',

    ...

    'XXX-N': 'YYY-N',
}[myname] || 'DEFAULT OUTPUT';

alert(output);
</code>```

 N Input - Output (Arbitrary Code) Pairs with Object Literals Lookups

Note you could also execute arbitrary code for each case in your objects using functions or arrow functions:

```<code>const myname = 'JOKA';

const output = {
    'XXX-1': () => { /* Do something... */ },
    'XXX-2': () => { /* Do something... */ },

    ...

    'XXX-N': () => { /* Do something... */ },
}[myname]();

...
</code>```

Note that you could declare those functions above the object declaration and share them across multiple keys that should have the same behaviour:

```<code>const myname = 'JOKA';

const f1 = () => { /* Do something 1... */ };

const output = {
    'XXX-1': f1,
    'XXX-2': f1,

    ...

    'XXX-N': () => { /* Do something... */ },
}[myname]();

...
</code>```

For more on replace switchs with object literal lookups, take a look at this post: https://toddmotto.com/deprecating-the-switch-statement-for-object-literals

Body:
I have a switch with the following conditions:

The first case is or between three names (ROKA, MOKA and TOKA).

The second case is another name (KOKA) but with two additional conditions to display an alert.

Lastly, I have some other conditions to check inside the default block, as I'm unable to use a case for them.

This is my code:

var myname= 'JOKA';
var dhaba = false;

switch (myname) {
  case ('ROKA'):
  case ('MOKA'):
  case ('TOKA'):
    alert('EEE');
    break;

  case ('KOKA'):
    // This will work as Goto to final default:

    if (condition1 && condition2) {
      alert('FEEE');
      break;
    }

  default:
    if (dhaba && myname != 'ROKA' && myname != 'TOKA') {
      alert('TEEEE');
    } else {
      alert('CHEEE');
    }
}

Is there a better way to write this code?

Body:
I think switch is not the best option for your use case.

Also, as @NinaScholz has pointed out, the myname != 'ROKA' && myname != 'TOKA' will always be true, as otherwise you will fall in the first case.

Let's go step by step and see different ways to refactor your code:

 Simplified (Non-Switch) Code

The easies and most straightforward way to write your code is like this:

const myname = 'JOKA';
const dhaba = false;

if ('ROKA' === myname || 'MOKA' === myname || 'TOKA' === myname) {
    alert('EEE');
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}

Note how the redundant checks have been removed and the last if - else block have been replaced with a ternary operator.

It is possible that your code is not exactly like the example you provided or that it changes overtime. In that case, you may consider other options other than the above simplified code.

 Checking multiple matches from a single variable using Array.prototype.indexOf()

However, you may have a lot more elements to check in the first if. In that case you could use an Array and Array.prototype.indexOf() to check if there's any match inside it (it will return -1 if there isn't any):

const myname = 'JOKA';
const dhaba = false;

if (['ROKA', 'MOKA', 'TOKA'].indexOf(myname) !== -1) {
    alert('EEE');
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}

 N Input - Output (String) Pairs + Complex Default with Switch

It is also possible that you have multiple myname values that map to multiple alert() params, so you may feel tempted to write something like this:

const myname = 'JOKA';
const dhaba = false;

switch(myname) {
    case 'XXX-1': alert('YYY-1'); break;
    case 'XXX-2': alert('YYY-2'); break;

    ...

    case 'XXX-N': alert('YYY-N'); break;

    default:
        if (myname === 'KOKA' && true && true) {
            alert('FEEE');
        } else {
            alert(dhaba ? 'TEEEE' : 'CHEEE');
        }
}

While this is fine and, actually, I think it is cleaner and less error-prone than checking an additional condition inside a case block, as you did in your example, and based on that do something and break or let the next block execute, I would advise you to consider using object literal lookups instead.

 N Input - Output (String) Pairs + Complex Default with Object Literals Lookups

There are multiple advantages to use them: better readability, easier debugging, maintainability, concision (no need to add break, for example)... I think the most important one for you, as you added the tag performance in your question, is that it is more performant.

This is because while the switch has to evaluate each case condition until it fins a break, so their order matters, the object lookup is just a hash table lookup, that is, O(1).

With this in mind, we could refactor the last example like this:

const myname = 'JOKA';
const dhaba = false;

const output = {
    'XXX-1': 'YYY-1',
    'XXX-2': 'YYY-2',

    ...

    'XXX-N': 'YYY-N',
}[myname];

// Note output will be undefined if there isn't a match, so the first if
// will be evaluated to false in that scenario:

if (output) {
    alert(output);
} else if (myname === 'KOKA' && true && true) {
    alert('FEEE');
} else {
    alert(dhaba ? 'TEEEE' : 'CHEEE');
}

 N Input - Output (String) Pairs + Single-Value Default with Object Literals Lookups  and || (or) Operator

Also, note that if your default were just using another value inside the if, you could do that with a simple || operator:

const myname = 'JOKA';

const output = {
    'XXX-1': 'YYY-1',
    'XXX-2': 'YYY-2',

    ...

    'XXX-N': 'YYY-N',
}[myname] || 'DEFAULT OUTPUT';

alert(output);

 N Input - Output (Arbitrary Code) Pairs with Object Literals Lookups

Note you could also execute arbitrary code for each case in your objects using functions or arrow functions:

const myname = 'JOKA';

const output = {
    'XXX-1': () => { /* Do something... */ },
    'XXX-2': () => { /* Do something... */ },

    ...

    'XXX-N': () => { /* Do something... */ },
}[myname]();

...

Note that you could declare those functions above the object declaration and share them across multiple keys that should have the same behaviour:

const myname = 'JOKA';

const f1 = () => { /* Do something 1... */ };

const output = {
    'XXX-1': f1,
    'XXX-2': f1,

    ...

    'XXX-N': () => { /* Do something... */ },
}[myname]();

...

For more on replace switchs with object literal lookups, take a look at this post: https://toddmotto.com/deprecating-the-switch-statement-for-object-literals


问:
Add ng-click event to angular-ui accordion
I'm using angular-ui and have started using accordions.

I need to fire an ng-click event when someone opens or closes an accordion group.

I did some research and found this thread: angular-ui issue

It linked to a plunker which shows a solution which isn't satisfactory for my use case.

Here is the solutions html:

```<code><accordion>
  <accordion-group>
      <accordion-heading>
          <span ng-click="foo()">Try clicking me!</span>
      </accordion-heading>
      Some Body 3
  </accordion-group>
</accordion>
</code>```

However the ng-click event only fires if you click on the span text. If you click just outside of the text the accordion still opens or closes without any click event.

To fix this I tried making the spans width & height 100% and setting display: block.
I also considered removing the padding entirely but I was wondering if there is a better way than hacking at it.

Does anyone know how to attach the ng-click event to the entire accordian group? Or how to make the span fill the entire group?

My entire code:

```<code>  <accordion close-others="true">
    <accordion-group ng-repeat="question in level">
        <accordion-heading style="padding: 0">
            <div style="display: block; margin: 0px" ng-click="set_question(question.title)">{{ question.title }}</div>
            <i class="icon-check" ng-show="has_solved_all"></i>
        </accordion-heading>
        <span ng-bind-html-unsafe="question.content"></span>
    </accordion-group>
  </accordion>
    <br>
    Question Open: {{ question_open }}
</code>```

答:
Create a top level div under accordion heading or move

```<code><i class="icon-check" ng-show="has_solved_all"></i>
</code>```

inside the div element -

```<code><div style="display: block; margin: 0px"
</code>```

This should do the magic.
Below works for me-

```<code><accordion-group ng-repeat="group in groups" >
  <accordion-heading>
    <div ng-click="opened(group, $index)">
      <span>{{group.title}}</span>
    </div>
  </accordion-heading>
  {{group.content}}
</accordion-group>
</code>```

Modify and verify in the plunker http://plnkr.co/edit/B3LC1X?p=preview
console log.
I know the question is old but others can use this answer.

Body:
I'm using angular-ui and have started using accordions.

I need to fire an ng-click event when someone opens or closes an accordion group.

I did some research and found this thread: angular-ui issue

It linked to a plunker which shows a solution which isn't satisfactory for my use case.

Here is the solutions html:

<accordion>
  <accordion-group>
      <accordion-heading>
          Try clicking me!
      </accordion-heading>
      Some Body 3
  </accordion-group>
</accordion>

However the ng-click event only fires if you click on the span text. If you click just outside of the text the accordion still opens or closes without any click event.

To fix this I tried making the spans width & height 100% and setting display: block.
I also considered removing the padding entirely but I was wondering if there is a better way than hacking at it.

Does anyone know how to attach the ng-click event to the entire accordian group? Or how to make the span fill the entire group?

My entire code:

  <accordion close-others="true">
    <accordion-group ng-repeat="question in level">
        <accordion-heading style="padding: 0">

{{ question.title }}

        </accordion-heading>

    </accordion-group>
  </accordion>

    Question Open: {{ question_open }}

Body:
Create a top level div under accordion heading or move

<i class="icon-check" ng-show="has_solved_all"></i>

inside the div element -

<div style="display: block; margin: 0px"

This should do the magic.
Below works for me-

<accordion-group ng-repeat="group in groups" >
  <accordion-heading>
    <div ng-click="opened(group, $index)">
      <span>{{group.title}}</span>
    </div>
  </accordion-heading>
  {{group.content}}
</accordion-group>

Modify and verify in the plunker http://plnkr.co/edit/B3LC1X?p=preview
console log.
I know the question is old but others can use this answer.


问:
Unable to add any nuget package in vs 2017
Am trying to add nuget package prism.core in vs 2017 and target framework is 4.6.1,its giving this error

Severity  Code    Description Project File    Line    Suppression State
  Error       Failed to add reference to 'Microsoft.Practices.ServiceLocation'.
  Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)

tried to install newtonsoft.json package, got this error

Severity  Code    Description Project File    Line    Suppression State
  Error       Failed to add reference to 'Newtonsoft.Json'.
  Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED))          0

Not able to install any nuget package? is this is something to do with vs 2017?

答: After repairing the visual studio, it worked.


问:
ChartJS: Bar chart with axis ticks wider than categories
I'm using ChartJS to display a timeseries as a bar chart.  Is there some way to separate the tick resolution on the x axis from the width of the bars?

The snippet below demonstrates the problem; it is showing hourly data over one week.  Because options.scales.xAxes[0].time.unit is set to day, the tick marks appear one per day but the bars are also one day wide.  Setting the unit to hour makes the bars the right width but leads to hundreds of tick marks on the x axis and makes the labels unreadable.

Is there some way to have the best of both?

const RANGE = (a,b) => Array.from((function*(x,y){
  while (x <= y) yield x++;
})(a,b));

labels = [];
for(var ii = 0; ii < 170; ii++) {
  labels.push((1483228800 + ii * 3600) * 1000);
}

var canvas = document.getElementById('chart'),
    ctx = canvas.getContext('2d'),
    startingData = {
      labels: labels,
      datasets: [
          {
              fillColor: "rgba(220,220,220,0.2)",
              strokeColor: "rgba(220,220,220,1)",
              pointColor: "rgba(220,220,220,1)",
              pointStrokeColor: "#fff",
              data: RANGE(1, 170),
              label: 'Data'
          },
      ]
    },
    options = {
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            unit: 'day',
          }
        }]
      }
    };

// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx, {
  type: 'bar',
  data: startingData,
  options: options
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
</head>
<body>
  Hello, world.<br>
  <canvas id="chart" width="500" height="300"></canvas>
</body>
</html></code>```

答:
The property unitStepSize might be what you are looking for.

Here is a JSFiddle with a example

As per the documentation:

The number of units between grid lines.

Body:
I'm using ChartJS to display a timeseries as a bar chart.  Is there some way to separate the tick resolution on the x axis from the width of the bars?

The snippet below demonstrates the problem; it is showing hourly data over one week.  Because options.scales.xAxes[0].time.unit is set to day, the tick marks appear one per day but the bars are also one day wide.  Setting the unit to hour makes the bars the right width but leads to hundreds of tick marks on the x axis and makes the labels unreadable.

Is there some way to have the best of both?

const RANGE = (a,b) => Array.from((function*(x,y){
  while (x <= y) yield x++;
})(a,b));

labels = [];
for(var ii = 0; ii < 170; ii++) {
  labels.push((1483228800 + ii * 3600) * 1000);
}

var canvas = document.getElementById('chart'),
    ctx = canvas.getContext('2d'),
    startingData = {
      labels: labels,
      datasets: [
          {
              fillColor: "rgba(220,220,220,0.2)",
              strokeColor: "rgba(220,220,220,1)",
              pointColor: "rgba(220,220,220,1)",
              pointStrokeColor: "#fff",
              data: RANGE(1, 170),
              label: 'Data'
          },
      ]
    },
    options = {
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            unit: 'day',
          }
        }]
      }
    };

// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx, {
  type: 'bar',
  data: startingData,
  options: options
});

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

  Hello, world.

  <canvas id="chart" width="500" height="300"></canvas>


问:
How do I make my player with a Rigidbody move with isKinematic checked?
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?</p>

```<code>    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}
</code>```

答:
Being that your player can no longer be effected by the physics engine, you'd have to manipulate the object's transform manually. Your script isn't ideally setup for it currently, but if I was to hack it into it and try to make it work it would look something like this:

(you can change it from fixedUpdate to update if you're no longer utilizing the physics engine)

```<code>void update(){
    float x = Input.GetAxisRaw("Horizontal")* Time.Deltatime;
    float z = Input.GetAxisRaw("Vertical") * Time.Deltatime;
    transform.position = new Vector3(transform.position.x+x,0,transform.position.z+z);
</code>```

Body:
My game is a topdown zombie shooter and whenever the zombies get to the player they bunch up underneath them, to the point where the player can just walk over the zombies. I noticed that when I check isKinematic on the Rigidbody the zombies cant push the player up to go underneath him, so they just run into him(which is what I want). Despite this I am then unable to move. How can i fix this?

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerMoving1 : MonoBehaviour {
    public float moveSpeed;
    private Rigidbody myRigidbody;
    private Vector3 moveInput;
    private Vector3 moveVelocity;
    private Camera mainCamera;
    public GunController theGun;
      void Start () {
         myRigidbody = GetComponent <Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
     }

// Update is called once per frame
void Update () {
    moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    moveVelocity = moveInput * moveSpeed;
    Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
    Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    float rayLength;
    if(groundPlane.Raycast(cameraRay,out rayLength))
    {
        Vector3 pointToLook = cameraRay.GetPoint(rayLength);
        transform.LookAt(new Vector3(pointToLook.x,transform.position.y,pointToLook.z));
    }
    if (Input.GetMouseButtonDown(0))
        theGun.isFiring = true;
    if (Input.GetMouseButtonUp(0))
        theGun.isFiring = false;
}
void FixedUpdate(){
    myRigidbody.velocity = moveVelocity;
}
}

Body:
Being that your player can no longer be effected by the physics engine, you'd have to manipulate the object's transform manually. Your script isn't ideally setup for it currently, but if I was to hack it into it and try to make it work it would look something like this:

(you can change it from fixedUpdate to update if you're no longer utilizing the physics engine)

void update(){
    float x = Input.GetAxisRaw("Horizontal")* Time.Deltatime;
    float z = Input.GetAxisRaw("Vertical") * Time.Deltatime;
    transform.position = new Vector3(transform.position.x+x,0,transform.position.z+z);


答:
You can use LINQ.</p>

```<code>var years = new int[] { 1999, 2000, 2001, 2002 };  //etc...

Console.WriteLine(String.Join(Environment.NewLine, years
    .Select(y => $"{y} {(DateTime.IsLeapYear(y) ? "is" : "is not")} a leap year")
    .ToArray()));
</code>```

Body:
Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable.

int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}

Body:
You can use LINQ.

var years = new int[] { 1999, 2000, 2001, 2002 };  //etc...

Console.WriteLine(String.Join(Environment.NewLine, years
    .Select(y => $"{y} {(DateTime.IsLeapYear(y) ? "is" : "is not")} a leap year")
    .ToArray()));


问:
Dask graph execution and memory usage
I am constructing a very large DAG in dask to submit to the distributed scheduler, where nodes operate on dataframes which themselves can be quite large. One pattern is that I have about 50-60 functions that load data and construct pandas dataframes that are several hundred MB each (and logically represent partitions of a single table). I would like to concatenate these into a single dask dataframe for downstream nodes in the graph, while minimizing the data movement. I link the tasks like this:

```<code>dfs = [dask.delayed(load_pandas)(i) for i in disjoint_set_of_dfs]
dfs = [dask.delayed(pandas_to_dask)(df) for df in dfs]
return dask.delayed(concat_all)(dfs)
</code>```

where

```<code>def pandas_to_dask(df):
    return dask.dataframe.from_pandas(df).to_delayed()
</code>```

and I have tried various concat_all implentations, but this seems reasonable:

```<code>def concat_all(dfs):
    dfs = [dask.dataframe.from_delayed(df) for df in dfs]
    return dask.dataframe.multi.concat(dfs, axis='index', join='inner')
</code>```

All the pandas dataframes are disjoint on their index and sorted / monotonic.

However, I'm getting killed workers dying on this concat_all function (cluster manager is killing them for exceeding their memory budgets) even though the memory budget on each is actually reasonably large and I wouldn't expect it to be moving data around. I'm reasonably certain that I always slice to a reasonable subset of data before calling compute() within graph nodse that use the dask dataframe.

I am playing with --memory-limit without success so far. Am I approaching the problem correctly at least? Are there considerations I'm missing?

答:
Given your list of delayed values that compute to pandas dataframes

```<code>>>> dfs = [dask.delayed(load_pandas)(i) for i in disjoint_set_of_dfs]
>>> type(dfs[0].compute())  # just checking that this is true
pandas.DataFrame
</code>```

Pass them to the dask.dataframe.from_delayed function

```<code>>>> ddf = dd.from_delayed(dfs)
</code>```

By default this will run the first computation in order to determine metadata (column names, dtypes, etc. that are important for dask.dataframe).  You can avoid this by constructing an example dataframe and passing it to the meta= keyword.

```<code>>>> meta = pd.DataFrame({'value': [1.0], 'name': ['foo'], 'id': [0]})
>>> ddf = dd.from_delayed(dfs, meta=meta)
</code>```

This example notebook may also be helpful.

Generally you will never need to call dask functions from within other dask functions (as you were doing by delaying the from_pandas call).  Dask.dataframe functions are themselves already lazy and don't need to be delayed further.

Title: Dask graph execution and memory usage

Body:
I am constructing a very large DAG in dask to submit to the distributed scheduler, where nodes operate on dataframes which themselves can be quite large. One pattern is that I have about 50-60 functions that load data and construct pandas dataframes that are several hundred MB each (and logically represent partitions of a single table). I would like to concatenate these into a single dask dataframe for downstream nodes in the graph, while minimizing the data movement. I link the tasks like this:

dfs = [dask.delayed(load_pandas)(i) for i in disjoint_set_of_dfs]
dfs = [dask.delayed(pandas_to_dask)(df) for df in dfs]
return dask.delayed(concat_all)(dfs)

where

def pandas_to_dask(df):
    return dask.dataframe.from_pandas(df).to_delayed()

and I have tried various concat_all implentations, but this seems reasonable:

def concat_all(dfs):
    dfs = [dask.dataframe.from_delayed(df) for df in dfs]
    return dask.dataframe.multi.concat(dfs, axis='index', join='inner')

All the pandas dataframes are disjoint on their index and sorted / monotonic.

However, I'm getting killed workers dying on this concat_all function (cluster manager is killing them for exceeding their memory budgets) even though the memory budget on each is actually reasonably large and I wouldn't expect it to be moving data around. I'm reasonably certain that I always slice to a reasonable subset of data before calling compute() within graph nodse that use the dask dataframe.

I am playing with --memory-limit without success so far. Am I approaching the problem correctly at least? Are there considerations I'm missing?

Body:
Given your list of delayed values that compute to pandas dataframes

>>> dfs = [dask.delayed(load_pandas)(i) for i in disjoint_set_of_dfs]
>>> type(dfs[0].compute())  # just checking that this is true
pandas.DataFrame

Pass them to the dask.dataframe.from_delayed function

>>> ddf = dd.from_delayed(dfs)

By default this will run the first computation in order to determine metadata (column names, dtypes, etc. that are important for dask.dataframe).  You can avoid this by constructing an example dataframe and passing it to the meta= keyword.

>>> meta = pd.DataFrame({'value': [1.0], 'name': ['foo'], 'id': [0]})
>>> ddf = dd.from_delayed(dfs, meta=meta)

This example notebook may also be helpful.

Generally you will never need to call dask functions from within other dask functions (as you were doing by delaying the from_pandas call).  Dask.dataframe functions are themselves already lazy and don't need to be delayed further.


问:
Combine two SQL statements with arithmetic (not joining per se)
I have a plugin that counts helpful votes for reviews on my site ('helpful', 'funny', 'cool', and it gives the option of adding other descriptors as well. So I've added 'not helpful'.

Now I'm trying to customize the query used to display the reviews with the most votes by taking 'not helpful' votes into account (subtracting them from the helpful votes) instead of just counting a total of all votes.

So originally the query used for this was:

```<code>SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` GROUP BY review_id ORDER BY count DESC LIMIT 5
</code>```

And I've found that I can count the helpful votes (where the number in the 'rate' column is 0, 1, or 2), like so:

```<code>SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5
</code>```

And I can count the non-helpful votes (where the number in the 'rate' column is 3), like so:

```<code>SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5
</code>```

But what I can't figure out is how to combine these two select statements such that the top 5 'count' results show a difference of the counts from each query.

I don't want a union because no subtraction is done, and I've tried various permutations of multiple selects, but can't manage to work this out.

Any suggestions?

An example table: Example Table

In the example above, if all votes are counted blindly, review #4 is ranked higher than review #10, but if not-helpful votes are taken into account, #10 is ranked higher with a net total of 1 versus review #4's net total of 0.

Make sense?

答:
try this:

```<code>select a.review_id,b.review_id,a.count,b.count from
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5) as a
left join
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5) as b
on a.review_id = b.review_id
</code>```

this is work if review_id of first query = review_id of second query otherwise you can use also <> to both.

other option use union all

```<code>SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5
union all
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5
</code>```

Body:
I have a plugin that counts helpful votes for reviews on my site ('helpful', 'funny', 'cool', and it gives the option of adding other descriptors as well. So I've added 'not helpful'.

Now I'm trying to customize the query used to display the reviews with the most votes by taking 'not helpful' votes into account (subtracting them from the helpful votes) instead of just counting a total of all votes.

So originally the query used for this was:

SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` GROUP BY review_id ORDER BY count DESC LIMIT 5

And I've found that I can count the helpful votes (where the number in the 'rate' column is 0, 1, or 2), like so:

SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5

And I can count the non-helpful votes (where the number in the 'rate' column is 3), like so:

SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5

But what I can't figure out is how to combine these two select statements such that the top 5 'count' results show a difference of the counts from each query.

I don't want a union because no subtraction is done, and I've tried various permutations of multiple selects, but can't manage to work this out.

Any suggestions?

An example table: Example Table

In the example above, if all votes are counted blindly, review #4 is ranked higher than review #10, but if not-helpful votes are taken into account, #10 is ranked higher with a net total of 1 versus review #4's net total of 0.

Make sense?

Body:
try this:

select a.review_id,b.review_id,a.count,b.count from
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5) as a
left join
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5) as b
on a.review_id = b.review_id

this is work if review_id of first query = review_id of second query otherwise you can use also <> to both.

other option use union all

SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5
union all
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5


问:
how do i Get the first character of each item in a list scheme?
I want it to extract all the first words in the list.
Example:

(first 'hello world asd fdas qwerty )

return:

h w a f q.

答:
Try this:

```<code>(define (first-char lst)
  (map (lambda (w)
         (string->symbol
          (string
           (string-ref
            (symbol->string w) 0))))
       lst))
</code>```

For example:

```<code>(first-char '(hello world asd fdas qwerty))
=> '(h w a f q)
</code>```

Body:
Try this:

(define (first-char lst)
  (map (lambda (w)
         (string->symbol
          (string
           (string-ref
            (symbol->string w) 0))))
       lst))

For example:

(first-char '(hello world asd fdas qwerty))
=> '(h w a f q)


问:
DateTime validation not working despite a field with identical code working perfectly (in C# MVC, ASP.Net Core)

Edit 1

Just to Clarify a couple of points,

The datetime picker/script appears to be working fine, the times and dates are selectable and fill the textbox with the correct values as expected.

The issue occurs when a time/date is manually entered into the textbox by the user and an invalid time is entered (i.e. "78/5/2017 12:00" or "12/5/2017 12:62")

I've updated a typo in the code, the error is still occurring with the corrected code.

I have my fingers crossed I'm missing something obvious because this makes no sense to me. Any help you can offer would be much appreciated. I have included my code at the end of the question.

The Problem

I have two DateTime fields which are included in a form on a page in my application: StartTime and EndTime.

Both of the fields are setup and put onto the page using (what I believe to be) identical code.

The StartTime field works perfectly, only excepting valid times as input and displaying an error for nonsensical times such as 28:30 or 17:67 until the User corrects it.

The EndTime field however does not validate correctly. Bad inputs are switched back to the current Time/Date before being passed back to the controller, the controller never even sees the bad values meaning I can't catch it and return an error at that point.

If nonsensical values are given in both fields then the submission is prevented and both fields show a validation error which suggests that the EndTime validation does work, it just doesn't prevent form submission.

My Efforts

As I have one working field I have attempted to use that to correct the error. However I hit a stumbling block in realising that there are no differences between the two. Deciding that I must have missed something I switched the variable names round so that the StartTime would be using the EndTime code and vice versa, I did this in each of the sections below one by one hoping to find a point where the field which was working swapped. That, however, never happened. Even once the entirety of their code was switched over it was still found to be the EndTime variable/field which was broken and the StartTime variable/field which was working.

My Research

Despite spending nearly a week with this bug now I have been unable to find any similar problems online and am at a complete stumbling block as to where to go or what to try now. I have tried looking for issues caused by DateTime calendar pickers as well as validation errors in general but can't find anything of use to this situation.

This is one of the last bugs to fix before the project is completed and so any help or even ideas you can offer would be amazing.

The Code

I have included everything I could think to here that interacts with the fields in question. If I have missed anything or you need more info please let me know.

The Entity Model

I have the following two DateTime fields in my Record Entity

```<code>public partial class Record
{
    // Other entity fields
    // ....
    // ...
    // ..

    [DisplayName("Start Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime StartTime { get; set; }

    [DisplayName("End Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime EndTime { get; set; }

    // and in the constructor
    public Record()
    {
        // initialise the DateTime fields with the current DateTime,
        // adjusted for daylight savings

        BaseController b = new BaseController();
        StartTime = b.TimeNow();
        EndTime = b.TimeNow();
    }
}
</code>```

For the sake of completion this is the TimeNow() function's code:

```<code>public DateTime TimeNow()
{
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    DateTime t = DateTime.Now;

    if (tz.IsDaylightSavingTime(t))
        t = t.AddHours(1);

    return t;
}
</code>```

The ViewModel

The Record entity is then included into a ViewModel as follows:

```<code>public class Home_UserAddRecord
{
    [DisplayName("Record")]
    public Record record { get; set; }

    // Other ViewModel fields
    // ....
    // ...
    // ..

    // and the blank constructor:
    public Home_UserAddRecord()
    {
        record = new Record();
        Error = false;
        ErrorMessage = string.Empty;
    }
}
</code>```

The CSHTML Form

They are then included into a form on the page like so:

```<code>@using (Html.BeginForm())
{
    <div class="form-horizontal">

        <div class="form-group col-md-12">
            @Html.LabelFor(model => model.record.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">
                @Html.EditorFor(model => model.record.StartTime, new { htmlAttributes = new { @Value = Model.record.StartTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "StartDate" } })
                @Html.ValidationMessageFor(model => model.record.StartTime, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group col-md-12">
            @Html.LabelFor(model => model.record.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-5">
                @Html.EditorFor(model => model.record.EndTime, new{ htmlAttributes = new{ @Value = Model.record.EndTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "EndDate" } })
                @Html.ValidationMessageFor(model => model.record.EndTime, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>

    </div>
}
</code>```

An Attached Script

And then finally they have a script applied to them to allow the use of a calendar picker on each input. The script looks like this:

```<code>@section Scripts{

    <script>

        var Start = new dhtmlXCalendarObject("StartDate");
        Start.setDateFormat("%d/%m/%Y %H:%i");
        Start.showToday();
        Start.attachEvent("onTimeChange", function (d) {
            var DateText = Start.getDate(true)
            document.getElementById("StartDate").value = DateText;
        });

        var End = new dhtmlXCalendarObject("EndDate");
        End.setDateFormat("%d/%m/%Y %H:%i");
        End.showToday();
        End.attachEvent("onTimeChange", function (d) {
            var DateText = End.getDate(true)
            document.getElementById("EndDate").value = DateText;
        });

    </script>
}
</code>```

答:
Perhaps a suggestion is to use DateTime.TryParseExact method, which will validate the "String" representation of the date using your desired format, and will return an error when the string does not comply to your specified format.  Here is code, note dateFormats are based on Australian Standard dates.  You can of course add hours and minutes to this too.

Note parsedDate is a DateTime format.  Usage of below is:

```<code>public void test(){
   DateTime ParsedDate;
   string SomeDate = "12-May-2017";
   if(parseDate(SomeDate, out ParsedDate))
   {
       // Date was parsed successfully, you can now used ParsedDate, e.g.
       Customer.Orders[0].DateRequired = ParsedDate;
   }
   else
   {
    // Throw an error
   }
}
</code>```

And the method declaration.  Use either in static class, or directly in your class.

```<code>public static bool parseDate(string theDate, out DateTime parsedDate)
        {
            string[] dateFormats = { "d-M-yy", "d-MMM-yy", "d-MMM-yyyy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-mm-dd" };
            bool result = DateTime.TryParseExact(
                theDate,
                dateFormats,
                new CultureInfo("en-AU"),
                DateTimeStyles.None, out parsedDate);

            return result;
        } //Convert string-based date to DateTime.  Uses a variety of parse templates
</code>```

Body:
Edit 1

Just to Clarify a couple of points,

The datetime picker/script appears to be working fine, the times and dates are selectable and fill the textbox with the correct values as expected.

The issue occurs when a time/date is manually entered into the textbox by the user and an invalid time is entered (i.e. "78/5/2017 12:00" or "12/5/2017 12:62")

I've updated a typo in the code, the error is still occurring with the corrected code.

I have my fingers crossed I'm missing something obvious because this makes no sense to me. Any help you can offer would be much appreciated. I have included my code at the end of the question.

The Problem

I have two DateTime fields which are included in a form on a page in my application: StartTime and EndTime.

Both of the fields are setup and put onto the page using (what I believe to be) identical code.

The StartTime field works perfectly, only excepting valid times as input and displaying an error for nonsensical times such as 28:30 or 17:67 until the User corrects it.

The EndTime field however does not validate correctly. Bad inputs are switched back to the current Time/Date before being passed back to the controller, the controller never even sees the bad values meaning I can't catch it and return an error at that point.

If nonsensical values are given in both fields then the submission is prevented and both fields show a validation error which suggests that the EndTime validation does work, it just doesn't prevent form submission.

My Efforts

As I have one working field I have attempted to use that to correct the error. However I hit a stumbling block in realising that there are no differences between the two. Deciding that I must have missed something I switched the variable names round so that the StartTime would be using the EndTime code and vice versa, I did this in each of the sections below one by one hoping to find a point where the field which was working swapped. That, however, never happened. Even once the entirety of their code was switched over it was still found to be the EndTime variable/field which was broken and the StartTime variable/field which was working.

My Research

Despite spending nearly a week with this bug now I have been unable to find any similar problems online and am at a complete stumbling block as to where to go or what to try now. I have tried looking for issues caused by DateTime calendar pickers as well as validation errors in general but can't find anything of use to this situation.

This is one of the last bugs to fix before the project is completed and so any help or even ideas you can offer would be amazing.

The Code

I have included everything I could think to here that interacts with the fields in question. If I have missed anything or you need more info please let me know.

The Entity Model

I have the following two DateTime fields in my Record Entity

public partial class Record
{
    // Other entity fields
    // ....
    // ...
    // ..

    [DisplayName("Start Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime StartTime { get; set; }

    [DisplayName("End Time")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
    public DateTime EndTime { get; set; }

    // and in the constructor
    public Record()
    {
        // initialise the DateTime fields with the current DateTime,
        // adjusted for daylight savings

        BaseController b = new BaseController();
        StartTime = b.TimeNow();
        EndTime = b.TimeNow();
    }
}

For the sake of completion this is the TimeNow() function's code:

public DateTime TimeNow()
{
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    DateTime t = DateTime.Now;

    if (tz.IsDaylightSavingTime(t))
        t = t.AddHours(1);

    return t;
}

The ViewModel

The Record entity is then included into a ViewModel as follows:

public class Home_UserAddRecord
{
    [DisplayName("Record")]
    public Record record { get; set; }

    // Other ViewModel fields
    // ....
    // ...
    // ..

    // and the blank constructor:
    public Home_UserAddRecord()
    {
        record = new Record();
        Error = false;
        ErrorMessage = string.Empty;
    }
}

The CSHTML Form

They are then included into a form on the page like so:

@using (Html.BeginForm())
{

            @Html.LabelFor(model => model.record.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.record.StartTime, new { htmlAttributes = new { @Value = Model.record.StartTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "StartDate" } })
                @Html.ValidationMessageFor(model => model.record.StartTime, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.record.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.record.EndTime, new{ htmlAttributes = new{ @Value = Model.record.EndTime.ToString("dd/MM/yyyy HH:mm"), @class = "form-control", @id = "EndDate" } })
                @Html.ValidationMessageFor(model => model.record.EndTime, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

}

An Attached Script

And then finally they have a script applied to them to allow the use of a calendar picker on each input. The script looks like this:

@section Scripts{

}

Body:
Perhaps a suggestion is to use DateTime.TryParseExact method, which will validate the "String" representation of the date using your desired format, and will return an error when the string does not comply to your specified format.  Here is code, note dateFormats are based on Australian Standard dates.  You can of course add hours and minutes to this too.

Note parsedDate is a DateTime format.  Usage of below is:

public void test(){
   DateTime ParsedDate;
   string SomeDate = "12-May-2017";
   if(parseDate(SomeDate, out ParsedDate))
   {
       // Date was parsed successfully, you can now used ParsedDate, e.g.
       Customer.Orders[0].DateRequired = ParsedDate;
   }
   else
   {
    // Throw an error
   }
}

And the method declaration.  Use either in static class, or directly in your class.

public static bool parseDate(string theDate, out DateTime parsedDate)
        {
            string[] dateFormats = { "d-M-yy", "d-MMM-yy", "d-MMM-yyyy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-mm-dd" };
            bool result = DateTime.TryParseExact(
                theDate,
                dateFormats,
                new CultureInfo("en-AU"),
                DateTimeStyles.None, out parsedDate);

            return result;
        } //Convert string-based date to DateTime.  Uses a variety of parse templates


问:
Why does this 'sed' fail inside qx() in Perl?
This sed works, to replace the value for Java home in a shell script:

sed -i 's#^JAVA_HOME=.*$#JAVA_HOME="/usr/lib/jvm/java-1.7.0-oracle.x86_64"#' /apps/tempbsu.sh

but now I am trying to use/invoke that sed from inside a Perl app, using qx():

qx(sed -i 's#^JAVA_HOME=.*$#JAVA_HOME="/usr/lib/jvm/java-1.7.0-oracle.x86_64"#' /apps/tempbsu.sh);

and when I do that, I am getting an error:

sed: -e expression #1, char 58: unterminated `s' command

From checking, I gather that error is happening because the sed is missing the last delimiter, but it seems like it is correct, i.e.:

```<code>sed -i 's#.....#.......#' /apps/tempbssu.sh
</code>```

Can someone tell me why this sed is failing with I use in a qx() in Perl?

答: $#JAVA_HOME is treated as a Perl variable (the number of the last element of the array variable). Escape it: \$#JAVA_HOME

Body:
This sed works, to replace the value for Java home in a shell script:

sed -i 's#^JAVA_HOME=.*$#JAVA_HOME="/usr/lib/jvm/java-1.7.0-oracle.x86_64"#' /apps/tempbsu.sh

but now I am trying to use/invoke that sed from inside a Perl app, using qx():

qx(sed -i 's#^JAVA_HOME=.*$#JAVA_HOME="/usr/lib/jvm/java-1.7.0-oracle.x86_64"#' /apps/tempbsu.sh);

and when I do that, I am getting an error:

sed: -e expression #1, char 58: unterminated `s' command

From checking, I gather that error is happening because the sed is missing the last delimiter, but it seems like it is correct, i.e.:

sed -i 's#.....#.......#' /apps/tempbssu.sh

Can someone tell me why this sed is failing with I use in a qx() in Perl?


问:
Add or Update object in array in JSON using jq
I'm trying to use jq to parse a JSON (the output of the OpenShift oc process ... command, actually), and add/update the env array of a container with a new key/value pair.

Sample input:

```<code>{
  "kind": "List",
  "apiVersion": "v1",
  "metadata": {},
  "items": [
    {
      "apiVersion": "v1",
      "kind": "Service",
      "metadata": {
        "annotations": {
          "description": "Exposes and load balances the node.js application pods"
        },
        "name": "myapp-web"
      },
      "spec": {
        "ports": [
          {
            "name": "web",
            "port": 3000,
            "protocol": "TCP",
            "targetPort": 3000
          }
        ],
        "selector": {
          "name": "myapp"
        }
      }
    },
    {
      "apiVersion": "v1",
      "kind": "Route",
      "metadata": {
        "name": "myapp-web"
      },
      "spec": {
        "host": "app.internal.io",
        "port": {
          "targetPort": "web"
        },
        "to": {
          "kind": "Service",
          "name": "myapp-web"
        }
      }
    },
    {
      "apiVersion": "v1",
      "kind": "DeploymentConfig",
      "metadata": {
        "annotations": {
          "description": "Defines how to deploy the application server"
        },
        "name": "myapp"
      },
      "spec": {
        "replicas": 1,
        "selector": {
          "name": "myapp"
        },
        "strategy": {
          "type": "Rolling"
        },
        "template": {
          "metadata": {
            "labels": {
              "name": "myapp"
            },
            "name": "myapp"
          },
          "spec": {
            "containers": [
              {
                "env": [
                  {
                    "name": "A_ENV",
                    "value": "a-value"
                  }
                ],
                "image": "node",
                "name": "myapp-node",
                "ports": [
                  {
                    "containerPort": 3000,
                    "name": "app",
                    "protocol": "TCP"
                  }
                ]
              }
            ]
          }
        },
        "triggers": [
          {
            "type": "ConfigChange"
          }
        ]
      }
    }
  ]
}
</code>```

In this JSON, I want to do the following:

Find the DeploymentConfig object

Check if it has the env array in the first container

If it does, add a new object {"name": "B_ENV", "value": "b-value"} in it

If it does not, add the env array, with the object {"name": "B_ENV", "value": "b-value"} in it

So far, I'm able to tackle part of this, where I'm able to find the concerned object, and add the new env var to the container:

oc process -f <dc.yaml> -o json | jq '.items | map(if .kind == "DeploymentConfig"
    then .spec.template.spec.containers[0].env |= .+ [{"name": "B_ENV", "value": "b-value"}]
    else .
    end)'
```

<p>This is able to insert the new env var as expected, but the output is an array as shown below. <s>Also, it doesn't handle the part where the <code>env</code> array may not be there at all.</s></p>

<p>I want to be able to produce the same output as the input, but with the new env var added.</p>

<p><strong>Sample output</strong>:
</p>

```[
  {
    "apiVersion": "v1",
    "kind": "Service",
    "metadata": {
      "annotations": {
        "description": "Exposes and load balances the node.js application pods"
      },
      "name": "myapp-web"
    },
    "spec": {
      "ports": [
        {
          "name": "web",
          "port": 3000,
          "protocol": "TCP",
          "targetPort": 3000
        }
      ],
      "selector": {
        "name": "myapp"
      }
    }
  },
  {
    "apiVersion": "v1",
    "kind": "Route",
    "metadata": {
      "name": "myapp-web"
    },
    "spec": {
      "host": "app.internal.io",
      "port": {
        "targetPort": "web"
      },
      "to": {
        "kind": "Service",
        "name": "myapp-web"
      }
    }
  },
  {
    "apiVersion": "v1",
    "kind": "DeploymentConfig",
    "metadata": {
      "annotations": {
        "description": "Defines how to deploy the application server"
      },
      "name": "myapp"
    },
    "spec": {
      "replicas": 1,
      "selector": {
        "name": "myapp"
      },
      "strategy": {
        "type": "Rolling"
      },
      "template": {
        "metadata": {
          "labels": {
            "name": "myapp"
          },
          "name": "myapp"
        },
        "spec": {
          "containers": [
            {
              "env": [
                {
                  "name": "A_ENV",
                  "value": "a-value"
                },
                {
                  "name": "B_ENV",
                  "value": "b-value"
                }
              ],
              "image": "node",
              "name": "myapp-node",
              "ports": [
                {
                  "containerPort": 3000,
                  "name": "app",
                  "protocol": "TCP"
                }
              ]
            }
          ]
        }
      },
      "triggers": [
        {
          "type": "ConfigChange"
        }
      ]
    }
  }
]
```

Is this doable, or is it too much to do with jq, and I should probably do this in python or node?

EDIT 1:

I just realized that conditional add/update of env array is already handled by the |= syntax!
So, I basically just need to be able to get the same structure back as the input, with the relevant env var added in the concerned array.

答:
You pretty much had it, but you'll want to restructure your filter to preserve the full results.  You want to make sure that none of the filters changes the context.  By starting off with .items, you changed it from your root object to the items array.  That in of itself is not so much a problem but what you do with that matters.  Keep in mind that assignments/updates preserves the original context as a result with the change applied.  So if you wrote your filter in terms of an update, it will work for you.

So to do this, you'll want to find the env array of the first container in the DeploymentConfig item.  First let's find that:

```<code>.items[] | select(.kind == "DeploymentConfig").spec.template.spec.containers[0].env
</code>```

You don't need to do anything else in terms of error handling since select will simply produce no result.  From there, you just need to update the array by adding the new value.

```<code>(.items[] | select(.kind == "DeploymentConfig").spec.template.spec.containers[0].env) +=
    [{name:"B_ENV",value:"b-value"}]
</code>```

If the array exists, it will add the new item. If not, it will create a new env array.  If env is not an array, that would be a different problem.

Body:
I'm trying to use jq to parse a JSON (the output of the OpenShift oc process ... command, actually), and add/update the env array of a container with a new key/value pair.

Sample input:

{
  "kind": "List",
  "apiVersion": "v1",
  "metadata": {},
  "items": [
    {
      "apiVersion": "v1",
      "kind": "Service",
      "metadata": {
        "annotations": {
          "description": "Exposes and load balances the node.js application pods"
        },
        "name": "myapp-web"
      },
      "spec": {
        "ports": [
          {
            "name": "web",
            "port": 3000,
            "protocol": "TCP",
            "targetPort": 3000
          }
        ],
        "selector": {
          "name": "myapp"
        }
      }
    },
    {
      "apiVersion": "v1",
      "kind": "Route",
      "metadata": {
        "name": "myapp-web"
      },
      "spec": {
        "host": "app.internal.io",
        "port": {
          "targetPort": "web"
        },
        "to": {
          "kind": "Service",
          "name": "myapp-web"
        }
      }
    },
    {
      "apiVersion": "v1",
      "kind": "DeploymentConfig",
      "metadata": {
        "annotations": {
          "description": "Defines how to deploy the application server"
        },
        "name": "myapp"
      },
      "spec": {
        "replicas": 1,
        "selector": {
          "name": "myapp"
        },
        "strategy": {
          "type": "Rolling"
        },
        "template": {
          "metadata": {
            "labels": {
              "name": "myapp"
            },
            "name": "myapp"
          },
          "spec": {
            "containers": [
              {
                "env": [
                  {
                    "name": "A_ENV",
                    "value": "a-value"
                  }
                ],
                "image": "node",
                "name": "myapp-node",
                "ports": [
                  {
                    "containerPort": 3000,
                    "name": "app",
                    "protocol": "TCP"
                  }
                ]
              }
            ]
          }
        },
        "triggers": [
          {
            "type": "ConfigChange"
          }
        ]
      }
    }
  ]
}

In this JSON, I want to do the following:

Find the DeploymentConfig object

Check if it has the env array in the first container

If it does, add a new object {"name": "B_ENV", "value": "b-value"} in it

If it does not, add the env array, with the object {"name": "B_ENV", "value": "b-value"} in it

So far, I'm able to tackle part of this, where I'm able to find the concerned object, and add the new env var to the container:

oc process -f <dc.yaml> -o json | jq '.items | map(if .kind == "DeploymentConfig"
    then .spec.template.spec.containers[0].env |= .+ [{"name": "B_ENV", "value": "b-value"}]
    else .
    end)'

This is able to insert the new env var as expected, but the output is an array as shown below. <s>Also, it doesn't handle the part where the env array may not be there at all.</s>

I want to be able to produce the same output as the input, but with the new env var added.

Sample output:

[
  {
    "apiVersion": "v1",
    "kind": "Service",
    "metadata": {
      "annotations": {
        "description": "Exposes and load balances the node.js application pods"
      },
      "name": "myapp-web"
    },
    "spec": {
      "ports": [
        {
          "name": "web",
          "port": 3000,
          "protocol": "TCP",
          "targetPort": 3000
        }
      ],
      "selector": {
        "name": "myapp"
      }
    }
  },
  {
    "apiVersion": "v1",
    "kind": "Route",
    "metadata": {
      "name": "myapp-web"
    },
    "spec": {
      "host": "app.internal.io",
      "port": {
        "targetPort": "web"
      },
      "to": {
        "kind": "Service",
        "name": "myapp-web"
      }
    }
  },
  {
    "apiVersion": "v1",
    "kind": "DeploymentConfig",
    "metadata": {
      "annotations": {
        "description": "Defines how to deploy the application server"
      },
      "name": "myapp"
    },
    "spec": {
      "replicas": 1,
      "selector": {
        "name": "myapp"
      },
      "strategy": {
        "type": "Rolling"
      },
      "template": {
        "metadata": {
          "labels": {
            "name": "myapp"
          },
          "name": "myapp"
        },
        "spec": {
          "containers": [
            {
              "env": [
                {
                  "name": "A_ENV",
                  "value": "a-value"
                },
                {
                  "name": "B_ENV",
                  "value": "b-value"
                }
              ],
              "image": "node",
              "name": "myapp-node",
              "ports": [
                {
                  "containerPort": 3000,
                  "name": "app",
                  "protocol": "TCP"
                }
              ]
            }
          ]
        }
      },
      "triggers": [
        {
          "type": "ConfigChange"
        }
      ]
    }
  }
]

Is this doable, or is it too much to do with jq, and I should probably do this in python or node?

EDIT 1:

I just realized that conditional add/update of env array is already handled by the |= syntax!
So, I basically just need to be able to get the same structure back as the input, with the relevant env var added in the concerned array.

Body:
You pretty much had it, but you'll want to restructure your filter to preserve the full results.  You want to make sure that none of the filters changes the context.  By starting off with .items, you changed it from your root object to the items array.  That in of itself is not so much a problem but what you do with that matters.  Keep in mind that assignments/updates preserves the original context as a result with the change applied.  So if you wrote your filter in terms of an update, it will work for you.

So to do this, you'll want to find the env array of the first container in the DeploymentConfig item.  First let's find that:

.items[] | select(.kind == "DeploymentConfig").spec.template.spec.containers[0].env

You don't need to do anything else in terms of error handling since select will simply produce no result.  From there, you just need to update the array by adding the new value.

(.items[] | select(.kind == "DeploymentConfig").spec.template.spec.containers[0].env) +=
    [{name:"B_ENV",value:"b-value"}]

If the array exists, it will add the new item. If not, it will create a new env array.  If env is not an array, that would be a different problem.


问:
Pass longitude and latitude from CLLocationManager to URL?
i'm trying to pass my latitude and longitude to my url params but is returning Nil, but when i print within the delegate it returns the longitude and latitude and i can't seem to find the issue, i've tried many different ways and nothing seems to work

this are the variable where i store my latitude and longitude

var lat: Double!
 var long: Double!

this is my delegate

```<code>func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    currentLocation = manager.location!.coordinate

    let locValue:CLLocationCoordinate2D = currentLocation!

    self.long = locValue.longitude
    self.lat = locValue.latitude

    print(lat)
    print(long)

}
</code>```

and here pass them to variables i'm using in my URL parameters but they return nil and i don't understand why

```<code>let userLat = String(describing: lat)
let userLong = String(describing: long)
</code>```

Thank You

答:
Try something like:

Swift 3

```<code>func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    if let last = locations.last {
        sendLocation(last.coordinate)
    }

}

func sendLocation(_ coordinate: CLLocationCoordinate2D) {
    let userLat = NSString(format: "%f", coordinate.latitude) as String
    let userLong = NSString(format: "%f", coordinate.longitude) as String

    // Run API Call....
}
</code>```

Body:
i'm trying to pass my latitude and longitude to my url params but is returning Nil, but when i print within the delegate it returns the longitude and latitude and i can't seem to find the issue, i've tried many different ways and nothing seems to work

this are the variable where i store my latitude and longitude

var lat: Double!
 var long: Double!

this is my delegate

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    currentLocation = manager.location!.coordinate

    let locValue:CLLocationCoordinate2D = currentLocation!

    self.long = locValue.longitude
    self.lat = locValue.latitude

    print(lat)
    print(long)

}

and here pass them to variables i'm using in my URL parameters but they return nil and i don't understand why

let userLat = String(describing: lat)
let userLong = String(describing: long)

Thank You

Body:
Try something like:

Swift 3

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    if let last = locations.last {
        sendLocation(last.coordinate)
    }

}

func sendLocation(_ coordinate: CLLocationCoordinate2D) {
    let userLat = NSString(format: "%f", coordinate.latitude) as String
    let userLong = NSString(format: "%f", coordinate.longitude) as String

    // Run API Call....
}