问:
How to manually set colour of dots in R using tmap
I'm trying to create a map showing the location of wells based on some defined categories. I have categorized each well's water level relative to their full record, categorizing the water levels into terms "Highest-ever", "above-normal", "normal", "below-normal", "Lowest-ever". Using tmap, I would like to show each of these conditions using the following colors "Highest-ever" = dark blue, "above-normal" = light blue, "normal"=green,"below-normal"=yellow,  "Lowest-ever" = red

So far I have created an sf file for mapping

```<code>Library(tidyverse)
library(sf)
library(spData)
Library(tmap)
Library(tmaptools)
</code>```

My data

```<code>test <- structure(list(well = c(3698L, 3697L, 4702L, 15001L, 1501L, 3737L,
1674L, 5988L, 1475L, 15017L), con = c("N", "B", "H", "B", "L",
"B", "N", "A", "N", "B"), x = c(2834091L, 2838342L, 2802911L,
2845228L, 2834408L, 2834452L, 2838641L, 2834103L, 2803192L, 2929417L
), y = c(6166870L, 6165512L, 6125649L, 6174527L, 6161309L, 6168216L,
6170055L, 6164397L, 6140763L, 6227467L)), row.names = c(NA, -10L
), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Create sf file for mapping

```<code>test_sf <-test %>%
  st_as_sf(coords = c("x","y"),crs = 27200,agr="constant")
</code>```

Obtain background map

```<code>HB_map <- nz %>%
  filter(Name=="Hawke's Bay") %>%
  read_osm(type = "stamen-terrain")
</code>```

Plot data over map

```<code>qtm(HB_map)+ #this is part of tmap and used to draw a thematic map plot
  tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf)+
tm_dots("con",palette=c(H='blue',A='cyan',N='green',B='yellow',L='red'),stretch.palette = FALSE,size = 0.4,shape =21)
</code>```

The map produces the right colours but not associated with the correct categories. I could change the order of the colours but the map won't always contain each category and thus the colours would be wrongly assigned again (if that makes sense)

答:
You can convert your con-column to factor. The default order of the levels will be alphabetic, that's how you can assign the colors. If a level is empty, it will still be included in the legend.

```<code>test_sf$con <- as.factor(test_sf$con)

tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf[test_sf$con != "H",])+
  tm_dots(col = "con", palette=c(A='cyan', B='yellow', H='blue',L='red',N='green'), stretch.palette = FALSE,size = 0.4,shape =21)

</code>```

(read_osm() doesn't work for me..)

Body:
I'm trying to create a map showing the location of wells based on some defined categories. I have categorized each well's water level relative to their full record, categorizing the water levels into terms "Highest-ever", "above-normal", "normal", "below-normal", "Lowest-ever". Using tmap, I would like to show each of these conditions using the following colors "Highest-ever" = dark blue, "above-normal" = light blue, "normal"=green,"below-normal"=yellow,  "Lowest-ever" = red

So far I have created an sf file for mapping

Library(tidyverse)
library(sf)
library(spData)
Library(tmap)
Library(tmaptools)

My data

test <- structure(list(well = c(3698L, 3697L, 4702L, 15001L, 1501L, 3737L,
1674L, 5988L, 1475L, 15017L), con = c("N", "B", "H", "B", "L",
"B", "N", "A", "N", "B"), x = c(2834091L, 2838342L, 2802911L,
2845228L, 2834408L, 2834452L, 2838641L, 2834103L, 2803192L, 2929417L
), y = c(6166870L, 6165512L, 6125649L, 6174527L, 6161309L, 6168216L,
6170055L, 6164397L, 6140763L, 6227467L)), row.names = c(NA, -10L
), class = c("tbl_df", "tbl", "data.frame"))

Create sf file for mapping

test_sf <-test %>%
  st_as_sf(coords = c("x","y"),crs = 27200,agr="constant")

Obtain background map

HB_map <- nz %>%
  filter(Name=="Hawke's Bay") %>%
  read_osm(type = "stamen-terrain")

Plot data over map

qtm(HB_map)+ #this is part of tmap and used to draw a thematic map plot
  tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf)+
tm_dots("con",palette=c(H='blue',A='cyan',N='green',B='yellow',L='red'),stretch.palette = FALSE,size = 0.4,shape =21)

The map produces the right colours but not associated with the correct categories. I could change the order of the colours but the map won't always contain each category and thus the colours would be wrongly assigned again (if that makes sense)

Body:
You can convert your con-column to factor. The default order of the levels will be alphabetic, that's how you can assign the colors. If a level is empty, it will still be included in the legend.

test_sf$con <- as.factor(test_sf$con)

tm_shape(nz %>% filter(Name=="Hawke's Bay"))+ #define data source
  tm_borders(col = "grey40", lwd = 2, lty = "solid", alpha = NA)+
  tm_shape(test_sf[test_sf$con != "H",])+
  tm_dots(col = "con", palette=c(A='cyan', B='yellow', H='blue',L='red',N='green'), stretch.palette = FALSE,size = 0.4,shape =21)

(read_osm() doesn't work for me..)


来源: stackexchange

问:
Case Sensitive Directory Path in Windows
I have reviewed the questions/answers asking whether or not directory/file names are case sensitive in a Windows environment as well as those discussing a need for case-sensitive searching [usually in Python, not C], so I think I understand the essential facts, but none of the postings include my particular application architecture, and the problem I am having resolving the problem.
So, let me briefly explain the application architecture of which I am speaking.  The heart of the application is built using Adobe AIR. Yes, that means that much of the U/I involves the Flex framework, but the file handling problem I am needing help with has no dependency upon the Flex U/I part of the application.
As I am trying to process a very large list of recursive directory structures, I am using the low level C RunTime API via a well-behaved mechanism which AIR provides for such cases where access to the host's Native Environment is needed.

The suite of functions which I am using is FindFileFirst, FindFileNext and FindClose.  If I write a stand-alone test program, it nicely lists the directories, sub-directories and files. The case of the directories and files is correctly shown -- just as they are correctly shown in Windows Explorer, or using the dir command.

If, however, I launch precisely the same function via the Adobe ANE interface, I receive exactly the same output with the exception that all directory names will be reduced to lower case.

Now, I should clarify that when this code is being executed as a Native Extension, it is not passing data back to AIR, it is directly outputting the results in a file that is opened and closed entirely in the CRT world, so we are not talking about any sort of communication confusion via the passing of either text or byte arrays between two different worlds.

Without kludging up this forum with lots and lots of extraneous code, I think what will help anyone who is able to help me is these snippets:

```<code>// This is where the output gets written.
FILE* textFile = _wfopen (L"Peek.txt", L"wt,ccs=UTF8");

WIN32_FIND_DATAW fdf;
HANDLE find = NULL;
wchar_t fullPath[2048];

// I am just showing the third argument as a literal to exemplify
// what, in reality is passed into the recursively-called function as
// a variable.
wsprintf (fullPath, L"\\\\?\\%ls\\*.*", L"F:\\");
hFind = FindFirstFile (fullPath, &fdf);

// After checking for success there appears a do..while loop
// inside which there is the expected check for the "." and ".."
// pseudo directories and a test of fdf.dwFileAttributes for
// file versus sub-directory.
// When the NextFile is a file a function is called to format
// the output in the textFile, like this:

fwprintf (textF, L"%ls\t%ls\t%2.2x\t%4d/%02d/%02d/%02d/%02d/%02d  \t%9ld.\n",
     parentPath, fdf.cFileName,
    (fdf.dwFileAttributes & 0x0f),
    st.wYear, st.wMonth, st.wDay,
    st.wHour, st.wMinute, st.wSecond,
    fSize);
</code>```

At that point parentPath will be a concatenated wide character string and
the other file attributes will be of the types shown.

So, to summarize:  All of this code works perfectly if I just write a stand-alone test.  When, however, the code is running as a task called from an Adobe ANE, the names of all the sub-directory parts are reduced to lower case.  I have tested every combination of file type attribute -- binary and text and encoding -- UTF-8 and UTF-16LE, but no matter what configuration I choose, the result remains the same:  Standalone the API delivers case-correct strings, running as a task in a dll invoked from AIR, the same API delivers only lower-case strings.

答:
First, my thanks to Messrs Ogilvie and Passant for helpful suggestions.

Second, I apologize for not really knowing the protocol here as a very infrequent visitor.  If I am supposed to flag either response as helpful and therefore correct, let these words at least reflect that fact.

I am providing an answer which was discovered by taking the advice above.

A. I discovered several tools that helped me get a handle on the contents of the .exe and .dll files. I should add some detail that was not part of the original posting: I have purposely been using the mingw-w64 toolchain rather than Visual Studio for this development work. So, as it turns out, both ldd and dumpbin helped me get a handle on whether or not the two slightly-different build environments were perhaps leaving me with different dependencies.

B. When I saw that one output included a reference to FindFirstFileExW, which function I had once tried in order to solve what I thought was the problem, I thought I had perhaps found a reason for the different results.  In the event, that was just a red-herring and I do not mean to waste the forum's time with my low-level of experience and understanding, but it seems useful to note this sort of trouble-shooting methodology as a possible assist to others.

C. So what was the problem?  There was, indeed, a small difference in the code between the stand-alone and the ANE-integrated implementations of the recursive directory search. In the production ANE use case, there is logic to apply a level of filtering to the returned results.  The actual application allows the user to qualify a search for duplicate files by interrogating parts of the parent string in addition to the filename string itself.

In one corner condition, the filter may be case-sensitive or case-insensitive and I was using _wcslwr in the mistaken belief that that function behaved the nice, Unicode-compliant way that string handling methods are provided in AIR/Actionscript3. I did not notice that the function actually does an in-place replacement of the original string with one reduced to lowercase.

User error, not, any untoward linking of non-standard CRT Kernel functions by Adobe's Native Extension interoperability, was the culprit.

ContentLicense: CC BY-SA 4.0

Body:
I have reviewed the questions/answers asking whether or not directory/file names are case sensitive in a Windows environment as well as those discussing a need for case-sensitive searching [usually in Python, not C], so I think I understand the essential facts, but none of the postings include my particular application architecture, and the problem I am having resolving the problem.
So, let me briefly explain the application architecture of which I am speaking.  The heart of the application is built using Adobe AIR. Yes, that means that much of the U/I involves the Flex framework, but the file handling problem I am needing help with has no dependency upon the Flex U/I part of the application.
As I am trying to process a very large list of recursive directory structures, I am using the low level C RunTime API via a well-behaved mechanism which AIR provides for such cases where access to the host's Native Environment is needed.

The suite of functions which I am using is FindFileFirst, FindFileNext and FindClose.  If I write a stand-alone test program, it nicely lists the directories, sub-directories and files. The case of the directories and files is correctly shown -- just as they are correctly shown in Windows Explorer, or using the dir command.

If, however, I launch precisely the same function via the Adobe ANE interface, I receive exactly the same output with the exception that all directory names will be reduced to lower case.

Now, I should clarify that when this code is being executed as a Native Extension, it is not passing data back to AIR, it is directly outputting the results in a file that is opened and closed entirely in the CRT world, so we are not talking about any sort of communication confusion via the passing of either text or byte arrays between two different worlds.

Without kludging up this forum with lots and lots of extraneous code, I think what will help anyone who is able to help me is these snippets:

// This is where the output gets written.
FILE* textFile = _wfopen (L"Peek.txt", L"wt,ccs=UTF8");

WIN32_FIND_DATAW fdf;
HANDLE find = NULL;
wchar_t fullPath[2048];

// I am just showing the third argument as a literal to exemplify
// what, in reality is passed into the recursively-called function as
// a variable.
wsprintf (fullPath, L"\\\\?\\%ls\\*.*", L"F:\\");
hFind = FindFirstFile (fullPath, &fdf);

// After checking for success there appears a do..while loop
// inside which there is the expected check for the "." and ".."
// pseudo directories and a test of fdf.dwFileAttributes for
// file versus sub-directory.
// When the NextFile is a file a function is called to format
// the output in the textFile, like this:

fwprintf (textF, L"%ls\t%ls\t%2.2x\t%4d/%02d/%02d/%02d/%02d/%02d  \t%9ld.\n",
     parentPath, fdf.cFileName,
    (fdf.dwFileAttributes & 0x0f),
    st.wYear, st.wMonth, st.wDay,
    st.wHour, st.wMinute, st.wSecond,
    fSize);

At that point parentPath will be a concatenated wide character string and
the other file attributes will be of the types shown.

So, to summarize:  All of this code works perfectly if I just write a stand-alone test.  When, however, the code is running as a task called from an Adobe ANE, the names of all the sub-directory parts are reduced to lower case.  I have tested every combination of file type attribute -- binary and text and encoding -- UTF-8 and UTF-16LE, but no matter what configuration I choose, the result remains the same:  Standalone the API delivers case-correct strings, running as a task in a dll invoked from AIR, the same API delivers only lower-case strings.


问:
How to reference object in another class
I'm a beginner in java. I have to make shopping cart.
But I'm stuck on reference.

Please help me!

I tried to make private member variable ShoppingCart in Customer class.
But I think it is not right way.

Customer.java

```<code>public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart s;

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}
</code>```

Test.java

```<code>public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Customer c1 = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        c1.s.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);

    }

}
</code>```

ShoppingCart.java

```<code>public class ShoppingCart {
    private int itemCount;
    private double totalPrice;
    private static int capacity;
    private Item[] cart;
    public ShoppingCart()
    {
        capacity = 5;
        itemCount = 0;
        totalPrice = 0.0;
        cart = new Item[capacity];
    }

    public void addBooktoCart(String title, String description, double price, int pageCount) {

        if (itemCount < 5) {

        Item item = new Book(title, description, price, pageCount);
        totalPrice += price;
        cart[itemCount] = item;
        itemCount += 1;
        }
        else {
            System.out.println("The maximum number that you can input is 5." +
                     "You cannot add item anymore");
        }

    }

}
</code>```

I want to call addBooktoCart that is in ShoppingCart class in the Test.java.
But it doesn't work. What do I do if I call addBooktoCart? And If there is another problem. Please let me know!

答:
In java by convention, we should keep all variables as private unless we have any specific reason not to do so. So , in your case you should keep ShoppingCart as private field in class Customer.Also, while naming variables java follows naming conventions :

Refer doc

Variable names are case-sensitive. A variable's name can be any legal
  identifier — an unlimited-length sequence of Unicode letters and
  digits, beginning with a letter, the dollar sign "$", or the
  underscore character "". The convention, however, is to always begin
  your variable names with a letter, not "$" or "". Additionally, the
  dollar sign character, by convention, is never used at all. You may
  find some situations where auto-generated names will contain the
  dollar sign, but your variable names should always avoid using it. A
  similar convention exists for the underscore character; while it's
  technically legal to begin your variable's name with "_", this
  practice is discouraged. White space is not permitted.

For your case you can have setter and getter methods for your ShoppingCart to fetch the object and later set it to the instance after your operations like :

Customer.java

```<code>public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart shoppingCart;

    public ShoppingCart getShoppingCart() {
      return shoppingCart;
    }

    public ShoppingCart setShoppingCart(ShoppingCart shoppingCart) {
      this.shoppingCart = shoppingCart;
    }

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}
</code>```

Test.java

```<code>public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ShoppingCart shoppingCart = new ShoppingCart();

        Customer customer = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        shoppingCart.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);
        customer.setShoppingCart(shoppingCart);
    }

}
</code>```

Body:
I'm a beginner in java. I have to make shopping cart.
But I'm stuck on reference.

Please help me!

I tried to make private member variable ShoppingCart in Customer class.
But I think it is not right way.

Customer.java

public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart s;

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}

Test.java

public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Customer c1 = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        c1.s.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);

    }

}

ShoppingCart.java

public class ShoppingCart {
    private int itemCount;
    private double totalPrice;
    private static int capacity;
    private Item[] cart;
    public ShoppingCart()
    {
        capacity = 5;
        itemCount = 0;
        totalPrice = 0.0;
        cart = new Item[capacity];
    }

    public void addBooktoCart(String title, String description, double price, int pageCount) {

        if (itemCount < 5) {

        Item item = new Book(title, description, price, pageCount);
        totalPrice += price;
        cart[itemCount] = item;
        itemCount += 1;
        }
        else {
            System.out.println("The maximum number that you can input is 5." +
                     "You cannot add item anymore");
        }

    }

}

I want to call addBooktoCart that is in ShoppingCart class in the Test.java.
But it doesn't work. What do I do if I call addBooktoCart? And If there is another problem. Please let me know!

Body:
In java by convention, we should keep all variables as private unless we have any specific reason not to do so. So , in your case you should keep ShoppingCart as private field in class Customer.Also, while naming variables java follows naming conventions :

Refer doc

Variable names are case-sensitive. A variable's name can be any legal
  identifier — an unlimited-length sequence of Unicode letters and
  digits, beginning with a letter, the dollar sign "$", or the
  underscore character "". The convention, however, is to always begin
  your variable names with a letter, not "$" or "". Additionally, the
  dollar sign character, by convention, is never used at all. You may
  find some situations where auto-generated names will contain the
  dollar sign, but your variable names should always avoid using it. A
  similar convention exists for the underscore character; while it's
  technically legal to begin your variable's name with "_", this
  practice is discouraged. White space is not permitted.

For your case you can have setter and getter methods for your ShoppingCart to fetch the object and later set it to the instance after your operations like :

Customer.java

public class Customer {
    private String id;
    private String firstName;
    private String lastName;
    private ShoppingCart shoppingCart;

    public ShoppingCart getShoppingCart() {
      return shoppingCart;
    }

    public ShoppingCart setShoppingCart(ShoppingCart shoppingCart) {
      this.shoppingCart = shoppingCart;
    }

    public Customer(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        s = new ShoppingCart();
    }

    @Override
    public String toString() {
        return ("Customer ID is: " + this.id + "\n" + "Customer's name is: "
                 + this.firstName + " " + this.lastName + "\n\n"
                + s.toString());

    }
}

Test.java

public class Test {
        public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ShoppingCart shoppingCart = new ShoppingCart();

        Customer customer = new Customer("12345", "David", "Smith");

        //This sentence doesn't work because of s.
        shoppingCart.addBooktoCart("Harry Potter", "Fantasy Genre", 10.99, 309);
        customer.setShoppingCart(shoppingCart);
    }

}


问:
Difference between member function and property
What is the difference?

```<code>val isFinished: Boolean
        get() = actor.actions.size == 0
</code>```

```<code>fun isFinished() = actor.actions.size == 0
</code>```

I have no idea.

I expect them to be the same.

答:
The first statement defines a property and the second statement defines a method.
Assume you define both in a class Foo.

```<code>val foo = Foo()
if(foo.isFinished) {} // property

if(foo.isFinished()) {} // method - see () at invocation
</code>```

Under the hood, both variants call a  function.

Body:
What is the difference?

val isFinished: Boolean
        get() = actor.actions.size == 0

fun isFinished() = actor.actions.size == 0

I have no idea.

I expect them to be the same.

Body:
The first statement defines a property and the second statement defines a method.
Assume you define both in a class Foo.

val foo = Foo()
if(foo.isFinished) {} // property

if(foo.isFinished()) {} // method - see () at invocation

Under the hood, both variants call a  function.


问:
'create-react-app' is not recognized as an internal or external command or operable program or batch file
I tried to create React Project but create-react-app my-app command is not working..please help

here is command

npm install -g create-react-app

create-react-app my-app

here is screenshort of my commands

答:
First Check your Node version. if your node version is 8 or greater then 8 then use

 'npx create-react-app my-app'
In the above version we need to change only one word that is npx
You don't need to do another things. I hope this will help you

ContentLicense: CC BY-SA 3.0


问:
@google-cloud/bigquery Query API returning empty Promise when used in Cloud Function
I'm trying to use the '@google-cloud/bigquery' library to query BigQuery from a Google Cloud function. When the Promise returns, all I get back is an Array with another empty Array inside it, even though when I run the same query from the Big Query console I get a non-empty response back.

I've tried using an async function instead of a promise, but that was not successful. I also gave my Service Account "BigQuery Admin" and "Editor" privileges but that has not worked out either.

I do know the API is hitting Big Query. When I tried creating a new dataset from my Cloud Function, that call worked just fine, but for some reason I'm unable to get query results back from BQ.

```<code>  function warningAndPreventionIntent(agent) {
    let userCountry = agent.parameters['geo-country'];
    console.log(String(userCountry[0]));

    const gotCountry = userCountry.length > 0;

    if(gotCountry) {
      agent.add('Im looking into your trip');

      const OPTIONS = {
              query: 'SELECT disease.name FROM `projectId.dataset.table`, unnest(disease) disease WHERE country = @country',
              timeoutMs: 10000,
              useLegacySql: false,
              params: {country: userCountry[0]}
      };

      return bigquery
      .query(OPTIONS)
      .then(results => {
          console.log(JSON.stringify(results[0]))
          const ROWS = results[0];

          let diseaseList = [];

          for(var row of ROWS) {
            diseaseList.push(row.name);
            console.log(diseaseList);
          }

          return true;

      })
      .catch(err => {
        console.error('ERROR:', err);
      });
    }
  }
</code>```

I should get a JSON result object with values, but I only get and array with an empty array [[]]

答:
Please find a working example using a public dataset you can use to test your query with</p>

```<code>if (!global._babelPolyfill) {
    var a = require("babel-polyfill")
}

import BigQuery from '@google-cloud/bigquery'

describe('Check google-cloud', async () => {

    it('Test query', async () => {
        let result = await test('panada')

    })

    async function test(p1) {
        try {
            const bigquery = new BigQuery({
                projectId: `projectId`,
                keyFilename: '/Users/tamirklein/ssh/mydata.json'
            })

            let query = [
                'SELECT url',
                'FROM `publicdata.samples.github_nested`',
                'WHERE repository.owner = @owner'

            ].join(' ')

            console.log(`query is: ${query}`)
            let [result] = await bigquery.query({
                query,
                params: {
                    owner: p1
                }
            })

            result.forEach((row, index) => {
                console.log(`row number ${index}, url is: ${row.url}`)
            })
        } catch (err) {
            console.log("err", err)
        }
    }
})
</code>```

Body:
I'm trying to use the '@google-cloud/bigquery' library to query BigQuery from a Google Cloud function. When the Promise returns, all I get back is an Array with another empty Array inside it, even though when I run the same query from the Big Query console I get a non-empty response back.

I've tried using an async function instead of a promise, but that was not successful. I also gave my Service Account "BigQuery Admin" and "Editor" privileges but that has not worked out either.

I do know the API is hitting Big Query. When I tried creating a new dataset from my Cloud Function, that call worked just fine, but for some reason I'm unable to get query results back from BQ.

  function warningAndPreventionIntent(agent) {
    let userCountry = agent.parameters['geo-country'];
    console.log(String(userCountry[0]));

    const gotCountry = userCountry.length > 0;

    if(gotCountry) {
      agent.add('Im looking into your trip');

      const OPTIONS = {
              query: 'SELECT disease.name FROM `projectId.dataset.table`, unnest(disease) disease WHERE country = @country',
              timeoutMs: 10000,
              useLegacySql: false,
              params: {country: userCountry[0]}
      };

      return bigquery
      .query(OPTIONS)
      .then(results => {
          console.log(JSON.stringify(results[0]))
          const ROWS = results[0];

          let diseaseList = [];

          for(var row of ROWS) {
            diseaseList.push(row.name);
            console.log(diseaseList);
          }

          return true;

      })
      .catch(err => {
        console.error('ERROR:', err);
      });
    }
  }

I should get a JSON result object with values, but I only get and array with an empty array [[]]

Body:
Please find a working example using a public dataset you can use to test your query with

if (!global._babelPolyfill) {
    var a = require("babel-polyfill")
}

import BigQuery from '@google-cloud/bigquery'

describe('Check google-cloud', async () => {

    it('Test query', async () => {
        let result = await test('panada')

    })

    async function test(p1) {
        try {
            const bigquery = new BigQuery({
                projectId: `projectId`,
                keyFilename: '/Users/tamirklein/ssh/mydata.json'
            })

            let query = [
                'SELECT url',
                'FROM `publicdata.samples.github_nested`',
                'WHERE repository.owner = @owner'

            ].join(' ')

            console.log(`query is: ${query}`)
            let [result] = await bigquery.query({
                query,
                params: {
                    owner: p1
                }
            })

            result.forEach((row, index) => {
                console.log(`row number ${index}, url is: ${row.url}`)
            })
        } catch (err) {
            console.log("err", err)
        }
    }
})


问:
ImportError: cannot import name 'bytes_type' in flask_oauthlib
i try to build a apps with flask_oauthlib and deploy it to heroku, but i get some error

```<code>2019-02-10T03:14:55.112096+00:00 app[web.1]:   File "/app/flask_oauthlib/client.py", line 20, in <module>
2019-02-10T03:14:55.112098+00:00 app[web.1]:     from .utils import to_bytes
2019-02-10T03:14:55.112099+00:00 app[web.1]:   File "/app/flask_oauthlib/utils.py", line 5, in <module>
2019-02-10T03:14:55.112102+00:00 app[web.1]:     from oauthlib.common import to_unicode, bytes_type
2019-02-10T03:14:55.112106+00:00 app[web.1]: ImportError: cannot import name 'bytes_type'
2019-02-10T03:14:55.112616+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [11] [INFO] Worker exiting (pid: 11)
2019-02-10T03:14:55.112784+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [10] [INFO] Worker exiting (pid: 10)
2019-02-10T03:14:55.267604+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Shutting down: Master
2019-02-10T03:14:55.267763+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Reason: Worker failed to boot.
2019-02-10T03:17:31.597353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=askfess.herokuapp.com request_id=1e14f0da-5bbe-4849-9308-3ecf8a49306f fwd="140.213.38.39" dyno= connect= service= status=503 bytes= protocol=https
</code>```

any ideas to fix it? the app error only when i try to deploy in heroku, but working fine in localhost

答:
Run pip to install requests-oauthlib:

```<code>pip install requests-oauthlib==1.1.0
</code>```

solved the issue for me!!

Body:
i try to build a apps with flask_oauthlib and deploy it to heroku, but i get some error

2019-02-10T03:14:55.112096+00:00 app[web.1]:   File "/app/flask_oauthlib/client.py", line 20, in <module>
2019-02-10T03:14:55.112098+00:00 app[web.1]:     from .utils import to_bytes
2019-02-10T03:14:55.112099+00:00 app[web.1]:   File "/app/flask_oauthlib/utils.py", line 5, in <module>
2019-02-10T03:14:55.112102+00:00 app[web.1]:     from oauthlib.common import to_unicode, bytes_type
2019-02-10T03:14:55.112106+00:00 app[web.1]: ImportError: cannot import name 'bytes_type'
2019-02-10T03:14:55.112616+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [11] [INFO] Worker exiting (pid: 11)
2019-02-10T03:14:55.112784+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [10] [INFO] Worker exiting (pid: 10)
2019-02-10T03:14:55.267604+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Shutting down: Master
2019-02-10T03:14:55.267763+00:00 app[web.1]: [2019-02-10 03:14:55 +0000] [4] [INFO] Reason: Worker failed to boot.
2019-02-10T03:17:31.597353+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=askfess.herokuapp.com request_id=1e14f0da-5bbe-4849-9308-3ecf8a49306f fwd="140.213.38.39" dyno= connect= service= status=503 bytes= protocol=https

any ideas to fix it? the app error only when i try to deploy in heroku, but working fine in localhost

Body:
Run pip to install requests-oauthlib:

pip install requests-oauthlib==1.1.0

solved the issue for me!!


问:
A member-function of a managed type cannot be compiled as an unmanaged function
This is the 2nd form in my program, and it generates the above error. The constructor function is what generates the error, and I can't see why. It's pretty much the same as my main window's constructor, which works just fine.

The only difference is that this one takes an argument. (even if I remove the argument in the SettingsForm constructor, and revert back to void, I still get the same error.

Can anybody tell me why it seems to think this constructor is being compiled as an unmanaged
function?

SettingsForm.h

```<code>#pragma once
#pragma managed(push, off)
#include "SpriteyData.h"
#pragma managed(pop)

namespace Spritey {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace SpriteyData;

    /// <summary>
    /// Summary for SettingsForm
    /// </summary>
    public ref class SettingsForm : public System::Windows::Forms::Form
    {

    public:
        SpriteySettings* currentSetLocCopy;//A local copy of our current settings.

        SettingsForm(SpriteySettings* currentSettings)<------ERROR OCCURS HERE
        {
            InitializeComponent();

            currentSetLocCopy = new SpriteySettings(*currentSettings); //take a copy of our current settings
            //initialise the elements on our form to the values stored in the SpriteySettings
            this->anchorDevCheckBox->Checked = currentSetLocCopy->isAnchorDevAllowed();
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~SettingsForm()
        {
            if (components)
            {
                delete components;

            }
            if(currentSetLocCopy)
            {
                delete currentSetLocCopy;
            }
        }
    private: System::Windows::Forms::Button^  CancelButton;
    private: System::Windows::Forms::Button^  ApplyButton;
    private: System::Windows::Forms::GroupBox^  editorSettingsGroup;
    private: System::Windows::Forms::CheckBox^  anchorDevCheckBox;
    private:
</code>```

Note: The above is just the constructor + a bit more of the code, and is merely a code sample of the part that is causing the error.

Also this is a mixed managed & unmanaged project.

答: I was also facing the same issue. On adding .Net Target Framework Version as v4.5.1 (which was missing previously) , the issue was resolved</p>

Body:
This is the 2nd form in my program, and it generates the above error. The constructor function is what generates the error, and I can't see why. It's pretty much the same as my main window's constructor, which works just fine.

The only difference is that this one takes an argument. (even if I remove the argument in the SettingsForm constructor, and revert back to void, I still get the same error.

Can anybody tell me why it seems to think this constructor is being compiled as an unmanaged
function?

SettingsForm.h

#pragma once
#pragma managed(push, off)
#include "SpriteyData.h"
#pragma managed(pop)

namespace Spritey {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace SpriteyData;

    ///
    /// Summary for SettingsForm
    ///
    public ref class SettingsForm : public System::Windows::Forms::Form
    {

    public:
        SpriteySettings* currentSetLocCopy;//A local copy of our current settings.

        SettingsForm(SpriteySettings* currentSettings)<------ERROR OCCURS HERE
        {
            InitializeComponent();

            currentSetLocCopy = new SpriteySettings(*currentSettings); //take a copy of our current settings
            //initialise the elements on our form to the values stored in the SpriteySettings
            this->anchorDevCheckBox->Checked = currentSetLocCopy->isAnchorDevAllowed();
        }

    protected:
        ///
        /// Clean up any resources being used.
        ///
        ~SettingsForm()
        {
            if (components)
            {
                delete components;

            }
            if(currentSetLocCopy)
            {
                delete currentSetLocCopy;
            }
        }
    private: System::Windows::Forms::Button^  CancelButton;
    private: System::Windows::Forms::Button^  ApplyButton;
    private: System::Windows::Forms::GroupBox^  editorSettingsGroup;
    private: System::Windows::Forms::CheckBox^  anchorDevCheckBox;
    private:

Note: The above is just the constructor + a bit more of the code, and is merely a code sample of the part that is causing the error.

Also this is a mixed managed & unmanaged project.


问:
Make a redirect without rendering the redirect page
After a user submitted some data to make a new object I want the backend to redirect him to the object detail, as usual:

I'm doing something like:

```<code>if obj.is_valid():
    obj.save()
    flash('%s created' % obj, )
    return redirect(url_for('provider', provider_id=obj.id))
</code>```

But doing te request via curl (I'm building an API, testing it with curl)

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/provider/11">/provider/11</a>.  If not click the link.
user@box
</code>```

Which is unfortunate because I only want the response of /provider/:id not the intermediate step.

What's the correct way to address this issue?

答:
I had similar query, as flask redirected to the Redirect Page before redirecting to the destination itself.

Just removing the code actually solved the problem. You can also specify custom route/handler for each code.

```<code>redirect(url_for('home'), code=302)
</code>```

to,

```<code>redirect(url_for('home'))
</code>```

Or as @Sean Vieira pointed out, use this decorator to handle redirect

```<code>@app.errorhandler(302)
def custom_redirect():
    # Return template
</code>```

Body:
After a user submitted some data to make a new object I want the backend to redirect him to the object detail, as usual:

I'm doing something like:

if obj.is_valid():
    obj.save()
    flash('%s created' % obj, )
    return redirect(url_for('provider', provider_id=obj.id))

But doing te request via curl (I'm building an API, testing it with curl)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>

Redirecting...

You should be redirected automatically to target URL: /provider/11.  If not click the link.
user@box

Which is unfortunate because I only want the response of /provider/:id not the intermediate step.

What's the correct way to address this issue?

Body:
I had similar query, as flask redirected to the Redirect Page before redirecting to the destination itself.

Just removing the code actually solved the problem. You can also specify custom route/handler for each code.

redirect(url_for('home'), code=302)

to,

redirect(url_for('home'))

Or as @Sean Vieira pointed out, use this decorator to handle redirect

@app.errorhandler(302)
def custom_redirect():
    # Return template


问:
How to active a button only when a file uploaded and checked terms and conditions?
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

```<code>    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });
</code>```

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>
```

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

答:
Try like this.

$(document).ready(function(){
  $("#employeelist").change(function(evt){
    window.selectedFile = evt.target.files[0];
    var terms = $('#termsNcon').is(":checked");
    if(window.selectedFile && terms){
      $('#stripe-button').prop("disabled", false);
    } else {
      $('#stripe-button').prop("disabled", true);
    }
    //convertToExcel();
    return false;
  });

  $('#termsNcon').change(function(){
    var terms = $('#termsNcon').is(":checked");
    if(window.selectedFile && terms){
      $('#stripe-button').prop("disabled", false);
    } else {
      $('#stripe-button').prop("disabled", true);
    }
    //convertToExcel();
    return false;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//File
<input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

//CheckBox
<input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

//button
<button id="stripe-button" disabled>Continue to Pay</button></code>```

Body:
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

Body:
Try like this.

$(document).ready(function(){
  $("#employeelist").change(function(evt){
    window.selectedFile = evt.target.files[0];
    var terms = $('#termsNcon').is(":checked");
    if(window.selectedFile && terms){
      $('#stripe-button').prop("disabled", false);
    } else {
      $('#stripe-button').prop("disabled", true);
    }
    //convertToExcel();
    return false;
  });

  $('#termsNcon').change(function(){
    var terms = $('#termsNcon').is(":checked");
    if(window.selectedFile && terms){
      $('#stripe-button').prop("disabled", false);
    } else {
      $('#stripe-button').prop("disabled", true);
    }
    //convertToExcel();
    return false;
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//File
<input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

//CheckBox
<input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

//button
<button id="stripe-button" disabled>Continue to Pay</button>


问:
IllegalArgumentException: Unable to locate adb in Android Studio v2.3
Does anyone know how to fix this?

```<code>IllegalArgumentException: Unable to locate adb
</code>```

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.

答:
I had a similar problem one day ago by deleting a file that avast notified as a virus, you can try the following steps, it works for me:

You have to download the "SDK Platform-Tools for your OS" at this link: https://developer.android.com/studio/releases/platform-tools.html

Unzip the downloaded package

Open the unzipped folder, then copy the "platform-tools" folder

Close Android Studio

Rename the existing "platform-tools" and then paste the new "platform-tools" to your sdk location, in my case: C:\Users\YourUserName\AppData\Local\Android\Sdk

Launch Android Studio and try to run your project

You should be good to go!

Good luck!

Body:
Does anyone know how to fix this?

IllegalArgumentException: Unable to locate adb

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.


问:
Unable to fetch referral code after install android app from app store
In my application have a referral program.I want when a customer share app link, that link redirect to playstore and after install app referral code retrieve from playstore. I already do that link but I don't understand how can i receive that referral code after install.</p>

```<code>public static void shareMyApp(Context context) {

    String link = "https://play.google.com/store/apps/details?id="+context.getPackageName();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("text/*");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
    context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));
}
</code>```

答:
For that, you have to use below the library

implementation 'com.android.installreferrer:installreferrer:1.0'

https://developer.android.com/google/play/installreferrer/library

https://developer.android.com/training/app-links/deep-linking.html

Thanks, it may help you

Body:
In my application have a referral program.I want when a customer share app link, that link redirect to playstore and after install app referral code retrieve from playstore. I already do that link but I don't understand how can i receive that referral code after install.

public static void shareMyApp(Context context) {

    String link = "https://play.google.com/store/apps/details?id="+context.getPackageName();

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("text/*");
    sharingIntent.putExtra(Intent.EXTRA_TEXT, link);
    context.startActivity(Intent.createChooser(sharingIntent, "Share Via"));
}


问:
How to navigate from a table view to a XIB file
I have loaded a XIB file(xyz) which is in the form of tableView
Now I have to load another XIB file(abc) on clicking any cell present in the xyz file . I have written this code in the didSelectRowAtIndexPath method

```<code>abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
[self.navigationController pushViewController:vc animated:YES];
</code>```

It is throwing a SIGABRT error in main. Please help!!

答:
Select the xib file and open file inspector. Now under Target Membership tick the check mark.

And check either abc view controller or navigationController is nil

```<code>if (![[abc alloc] initWithNibName:@"abc" bundle:nil]) {
    NSLog(@"xib file with name abc not found");
} else if (!self.navigationController) {
    NSLog(@"Navigation controller is nil");
} else {
    abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}
</code>```

Body:
I have loaded a XIB file(xyz) which is in the form of tableView
Now I have to load another XIB file(abc) on clicking any cell present in the xyz file . I have written this code in the didSelectRowAtIndexPath method

abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
[self.navigationController pushViewController:vc animated:YES];

It is throwing a SIGABRT error in main. Please help!!

Body:
Select the xib file and open file inspector. Now under Target Membership tick the check mark.

And check either abc view controller or navigationController is nil

if (![[abc alloc] initWithNibName:@"abc" bundle:nil]) {
    NSLog(@"xib file with name abc not found");
} else if (!self.navigationController) {
    NSLog(@"Navigation controller is nil");
} else {
    abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}


问:
How to properly authenticate Kusto using a Python client?
I'm trying to test a connection between my node and Azure Data Explorer (ADX/ Kusto). I'm thinking to create a table on Kusto using a python script.

Please be aware that I'm not very familiar with any of this, hence the detailed steps below.

I'm following this quickstart guide on Microsoft docs.

Generate application ID and key

Using App Registrations service:

Create new registration (named kusto test):

Create a client secrets:

Create Kusto DB

From the cluster, create a database from the UI (called kusto-test)

Authorization

On the ADX cluster > Access control (IAM) > Add role assignment.

Python script

from azure.kusto.data.request import KustoClient, KustoConnectionStringBuilder
from azure.kusto.data.exceptions import KustoServiceError
from azure.kusto.data.helpers import dataframe_from_result_table

KUSTO_DATABASE = "kusto-test"
CLUSTER = "https://mynode.myregion.kusto.windows.net"

CLIENT_ID = "KUSTO_TEST_APP_ID" # From image above
CLIENT_SECRET = "KUSTO_TEST_PASS" # From image above

AUTHORITY_ID = "<insert here your tenant id>" #Got from https://login.windows.net/<YourDomain>/.well-known/openid-configuration/

KCSB_DATA = KustoConnectionStringBuilder.with_aad_application_key_authentication(
    CLUSTER, CLIENT_ID, CLIENT_SECRET, AUTHORITY_ID
)

KUSTO_CLIENT = KustoClient(KCSB_DATA)
CREATE_TABLE_COMMAND = ".create table StormEvents (StartTime: datetime, EndTime: datetime, EpisodeId: int, EventId: int, State: string, EventType: string, InjuriesDirect: int, InjuriesIndirect: int, DeathsDirect: int, DeathsIndirect: int, DamageProperty: int, DamageCrops: int, Source: string, BeginLocation: string, EndLocation: string, BeginLat: real, BeginLon: real, EndLat: real, EndLon: real, EpisodeNarrative: string, EventNarrative: string, StormSummary: dynamic)"

RESPONSE = KUSTO_CLIENT.execute_mgmt(KUSTO_DATABASE, CREATE_TABLE_COMMAND)

dataframe_from_result_table(RESPONSE.primary_results[0])
```

<p>Expected:</p>

<ul>
<li>Have the table successfully created on ADX.</li>
</ul>

<p>Actual:</p>

<ul>
<li>Getting the <em>UnauthorizedDatabaseAccessException</em> error.</li>
</ul>

```azure.kusto.data.exceptions.KustoServiceError: (KustoServiceError(...), [{u'error': {u'code': u'Forbidden', u'@permanent': True, u'@message': u"Principal '....' is not authorized to access database 'kusto-test'.", ...}, u'message': u'Caller is not authorized to perform this action', u'@type': u'Kusto.DataNode.Exceptions.UnauthorizedDatabaseAccessException'}}])

```

答:
Adding an owner in the Azure portal "access control" only provides that entity with permission to manage the resource (also known as the 'control plane') and is not applicable to the permissions on the database itself (also known as the 'data plane').

To provide that application permission to operate in the data plane for example to run queries, create tables etc. you need to give it permission in the applicable database "Permissions" section:

Body:
I'm trying to test a connection between my node and Azure Data Explorer (ADX/ Kusto). I'm thinking to create a table on Kusto using a python script.

Please be aware that I'm not very familiar with any of this, hence the detailed steps below.

I'm following this quickstart guide on Microsoft docs.

Generate application ID and key

Using App Registrations service:

Create new registration (named kusto test):

Create a client secrets:

Create Kusto DB

From the cluster, create a database from the UI (called kusto-test)

Authorization

On the ADX cluster > Access control (IAM) > Add role assignment.

Python script

from azure.kusto.data.request import KustoClient, KustoConnectionStringBuilder
from azure.kusto.data.exceptions import KustoServiceError
from azure.kusto.data.helpers import dataframe_from_result_table

KUSTO_DATABASE = "kusto-test"
CLUSTER = "https://mynode.myregion.kusto.windows.net"

CLIENT_ID = "KUSTO_TEST_APP_ID" # From image above
CLIENT_SECRET = "KUSTO_TEST_PASS" # From image above

AUTHORITY_ID = "<insert here your tenant id>" #Got from https://login.windows.net/<YourDomain>/.well-known/openid-configuration/

KCSB_DATA = KustoConnectionStringBuilder.with_aad_application_key_authentication(
    CLUSTER, CLIENT_ID, CLIENT_SECRET, AUTHORITY_ID
)

KUSTO_CLIENT = KustoClient(KCSB_DATA)
CREATE_TABLE_COMMAND = ".create table StormEvents (StartTime: datetime, EndTime: datetime, EpisodeId: int, EventId: int, State: string, EventType: string, InjuriesDirect: int, InjuriesIndirect: int, DeathsDirect: int, DeathsIndirect: int, DamageProperty: int, DamageCrops: int, Source: string, BeginLocation: string, EndLocation: string, BeginLat: real, BeginLon: real, EndLat: real, EndLon: real, EpisodeNarrative: string, EventNarrative: string, StormSummary: dynamic)"

RESPONSE = KUSTO_CLIENT.execute_mgmt(KUSTO_DATABASE, CREATE_TABLE_COMMAND)

dataframe_from_result_table(RESPONSE.primary_results[0])

Expected:

Have the table successfully created on ADX.

Actual:

Getting the UnauthorizedDatabaseAccessException error.

azure.kusto.data.exceptions.KustoServiceError: (KustoServiceError(...), [{u'error': {u'code': u'Forbidden', u'@permanent': True, u'@message': u"Principal '....' is not authorized to access database 'kusto-test'.", ...}, u'message': u'Caller is not authorized to perform this action', u'@type': u'Kusto.DataNode.Exceptions.UnauthorizedDatabaseAccessException'}}])


问:
How can I hide some content based on user role in JSF?
I'm using JAAS and have applied security on some folders for different roles. I want to hide some navigation for different users because, although the pages are not accessible, the user can still see the links that he has no rights on? What's the simple way to achieve this in JSF? Do I need to call a method to check the role in the "rendered" property of each navigation link? Any sample code? Please help!</p>

答:
Use rendered for view, take

```<code>rendered="#{userBean.role =='ADMIN'}"
</code>```

also configure filter or use Spring security's filter to restrict them to access the URL

Body:
Use rendered for view, take

rendered="#{userBean.role =='ADMIN'}"

also configure filter or use Spring security's filter to restrict them to access the URL


问:
How to properly cleanup incorrectly initialized object?
I was asked this question in an interview.

There is a class, lets call it A. It has a default constructor and it initializes  2 different connections in its constructor.

Methods initDB & initSocket creates a DB connection and a socket connection and saves them in an instance field. They are just an example. They could also be file open or anything else.

Lets say a client instantiates an instance of this class. Now initDB executed successfully, but initSocket threw exception. So the object creation was aborted. But the DB connection was not closed prior to the exception. This resulted in a resource leak. How would I tackle this kind of resource leak?

E.g.

```<code>class A {
    public A(){
        this.dbConnection = initDB();
        this.socketConnection = initSocket(); // throws exception
    }
}
</code>```

My initial answer was that I would not initialize these in constructor but in a separate init(). He countered by suggesting that this could be a legacy class, and I have been asked to maintain this. In which case I need to somehow clear the resource leak. How would I approach this problem?

I got stumped because instance creation threw an exception I lost any kind of reference to those connection fields. So I cannot call close() on them. But they will still be present in the OS level (this is my guess).

Note 1

As stated by Interviewer, I cannot change the behavior of the already written constructor. I can extend or do something around it, but cannot change the code.

Note 2

I think interviewer was not looking for explicitly any code that would handle this scenario. Would any JMX stuff help? I took a jibe at it & then we moved on. For those who think this is a very good question, I think interviewer knew this is not a general practice and probably would not be able to answer.

答:
We have a few options here...

Box the thing off somewhere else. It's clearly problematic legacy code. Perhaps this "blob" which has access control issues can be moved into something some other process that can communicate with the rest of the system via RPC. You are better off doing this if the system is horribly broken. You can extend it other ways, such as composition; but if it's so sealed off you can't get it it, then you're boned

Use byte code modification. You could do this and you could get enough leverage to get what you need. ByteBuddy would come in handy for this. I wouldn't do this personally but hey, sometimes desperate measures call for desperate solutions...

If you can influence initDB, then you can decorate the return value with something else. For example, let's supposed it was some from some base class we did control or some other method we controlled, then we could perhaps do something like this

```<code>Connection initDb() {
  try {
    this.wrappedProvider.initDb();
  } catch(Exception e) {
     // .. destroy the connection...
  }
}
</code>```

... and then since you can influence this, you can change the effective semantics of it.

Can you influence the "Connection" of "A"? How does it get "A"? If it gets it  from some DI container or something you can influence, then you can sub out the implementation for that class for something that "times out" if not talked to or initialized in some given time. Hacky, sure but without more info that's the best we're going to get...

Body:
I was asked this question in an interview.

There is a class, lets call it A. It has a default constructor and it initializes  2 different connections in its constructor.

Methods initDB & initSocket creates a DB connection and a socket connection and saves them in an instance field. They are just an example. They could also be file open or anything else.

Lets say a client instantiates an instance of this class. Now initDB executed successfully, but initSocket threw exception. So the object creation was aborted. But the DB connection was not closed prior to the exception. This resulted in a resource leak. How would I tackle this kind of resource leak?

E.g.

class A {
    public A(){
        this.dbConnection = initDB();
        this.socketConnection = initSocket(); // throws exception
    }
}

My initial answer was that I would not initialize these in constructor but in a separate init(). He countered by suggesting that this could be a legacy class, and I have been asked to maintain this. In which case I need to somehow clear the resource leak. How would I approach this problem?

I got stumped because instance creation threw an exception I lost any kind of reference to those connection fields. So I cannot call close() on them. But they will still be present in the OS level (this is my guess).

Note 1

As stated by Interviewer, I cannot change the behavior of the already written constructor. I can extend or do something around it, but cannot change the code.

Note 2

I think interviewer was not looking for explicitly any code that would handle this scenario. Would any JMX stuff help? I took a jibe at it & then we moved on. For those who think this is a very good question, I think interviewer knew this is not a general practice and probably would not be able to answer.

Body:
We have a few options here...

Box the thing off somewhere else. It's clearly problematic legacy code. Perhaps this "blob" which has access control issues can be moved into something some other process that can communicate with the rest of the system via RPC. You are better off doing this if the system is horribly broken. You can extend it other ways, such as composition; but if it's so sealed off you can't get it it, then you're boned

Use byte code modification. You could do this and you could get enough leverage to get what you need. ByteBuddy would come in handy for this. I wouldn't do this personally but hey, sometimes desperate measures call for desperate solutions...

If you can influence initDB, then you can decorate the return value with something else. For example, let's supposed it was some from some base class we did control or some other method we controlled, then we could perhaps do something like this

Connection initDb() {
  try {
    this.wrappedProvider.initDb();
  } catch(Exception e) {
     // .. destroy the connection...
  }
}

... and then since you can influence this, you can change the effective semantics of it.

Can you influence the "Connection" of "A"? How does it get "A"? If it gets it  from some DI container or something you can influence, then you can sub out the implementation for that class for something that "times out" if not talked to or initialized in some given time. Hacky, sure but without more info that's the best we're going to get...


问:
How to set up Vue routes or override back button to function like an app
I am building a cordova Vue app. In many cases there is deeper links like this

/profile/:id/:contact_type/contacts:contact_id

Where you would first be on /profile/:id and then click a link to go to /profile/:id/:contact_type/contacts:contact_id

The standard router.go(-1) works fine if you were on the profile page first.  But if you get a notification or something, and are sent from any page, for example /settings/:id.  Your back button should behave more like an Up button, pressing back on /profile/:id/:contact_type/contacts:contact_id should take you to /profile/:id and not /settings/:id.
How do I set this up?  I tried a few things like splitting the current route on / and popping it, then joining back and pushing to that.  But that doesn't work with parameters, especially if there is more than 1.

```<code>const path = router.currentRoute.path
const URLSplit = path.split('/')
URLSplit.length = URLSplit.length - 1
const newTarget = URLSplit.join('/')
if (newTarget) {
  router.push(newTarget)
} else {
  router.push('/home')
}
</code>```

I also tried using child routes, but that requires a router-view in each page, which isn't what I want to do.

I have already captured the back button operation, I just want to know if there is a way to set up Vue to do this sort of back operation, or is there a way I am supposed to set up the router to do this, or a function that can figure out the current route and go up to it?

答:
That sounds like it would defeat the original purpose of navigating between historical/visited pages (rather than going up one level in the routes).

I would instead add a dedicated, in-app back button for this (like Google apps do have one); otherwise, you might have to try and intercept the browser's default behavior for that particular button, by listening to the popstate event of the Window interface which is fired when the active history entry changes. But if you have to, there is a workaround for that with Global Before (navigation) Guards.

With an in-app back (or technically "up") button I mentioned earlier, you could use In-Component Guards.

For example, given the following routes settings...

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/profile/:id',
      name: 'profile',
      component: Profile,

      children: [{
        path: ':contact_type/contacts:contact_id',
        name: 'contact',
        component: Contact
      }]
    }
  ]
})
```

<p>...you would directly define the route navigation guards inside the route component (e.g. <code>Contacts.vue</code>):</p>

```<template>

    <router-link :to="{ name: 'profile' }"><- back to profile</router-link>

    Some contact information.

</template>

```

Not necessarily the best approach, but that should work.

Body:
I am building a cordova Vue app. In many cases there is deeper links like this

/profile/:id/:contact_type/contacts:contact_id

Where you would first be on /profile/:id and then click a link to go to /profile/:id/:contact_type/contacts:contact_id

The standard router.go(-1) works fine if you were on the profile page first.  But if you get a notification or something, and are sent from any page, for example /settings/:id.  Your back button should behave more like an Up button, pressing back on /profile/:id/:contact_type/contacts:contact_id should take you to /profile/:id and not /settings/:id.
How do I set this up?  I tried a few things like splitting the current route on / and popping it, then joining back and pushing to that.  But that doesn't work with parameters, especially if there is more than 1.

const path = router.currentRoute.path
const URLSplit = path.split('/')
URLSplit.length = URLSplit.length - 1
const newTarget = URLSplit.join('/')
if (newTarget) {
  router.push(newTarget)
} else {
  router.push('/home')
}

I also tried using child routes, but that requires a router-view in each page, which isn't what I want to do.

I have already captured the back button operation, I just want to know if there is a way to set up Vue to do this sort of back operation, or is there a way I am supposed to set up the router to do this, or a function that can figure out the current route and go up to it?

Body:
That sounds like it would defeat the original purpose of navigating between historical/visited pages (rather than going up one level in the routes).

I would instead add a dedicated, in-app back button for this (like Google apps do have one); otherwise, you might have to try and intercept the browser's default behavior for that particular button, by listening to the popstate event of the Window interface which is fired when the active history entry changes. But if you have to, there is a workaround for that with Global Before (navigation) Guards.

With an in-app back (or technically "up") button I mentioned earlier, you could use In-Component Guards.

For example, given the following routes settings...

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/profile/:id',
      name: 'profile',
      component: Profile,

      children: [{
        path: ':contact_type/contacts:contact_id',
        name: 'contact',
        component: Contact
      }]
    }
  ]
})

...you would directly define the route navigation guards inside the route component (e.g. Contacts.vue):

<template>
  <div>
    <router-link :to="{ name: 'profile' }">&lt;- back to profile</router-link>

    Some contact information.
  </div>
</template>

<script>
  export default {
    beforeRouteLeave(to, from, next) {
      if (from.name === 'contact' && to.name !== 'profile') {
        next({
          name: 'profile',
          params: {
            id: from.params.id
          }
        });
      }
      else {
        next();
      }
    }
  }
</script>

Not necessarily the best approach, but that should work.


问:
Unexpected Indentation of Nested Opening Brackets
EDIT: I don't want to put opening curly brackets on a separate line, in general. I simply want to do so in this case where two opening brackets are on the same line. ESLint does it correctly but Beautify does not, but ESLint is only for inline Javascript.

I'm using the Beautify extension in VSCode to try to format this chunk of inline javascript as follows:

```<code>    const dogs = [
        {
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];
</code>```

Instead, it does this:

```<code>    const dogs = [{
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];
</code>```

As you can see, it puts the opening square and curly brackets on the same line. Is there a rule (in .jsbeautifyrc) to force the desired behavior or is this a bug in js-beautify?

答:
Try paste this rule in your .jsbeautifyrc

```<code>
    {
        "js": {
            "brace_style": "expand"
        }
    }

</code>```

Also you can try this extension too: Visual Studio Code Format

Body:
EDIT: I don't want to put opening curly brackets on a separate line, in general. I simply want to do so in this case where two opening brackets are on the same line. ESLint does it correctly but Beautify does not, but ESLint is only for inline Javascript.

I'm using the Beautify extension in VSCode to try to format this chunk of inline javascript as follows:

    const dogs = [
        {
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];

Instead, it does this:

    const dogs = [{
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];

As you can see, it puts the opening square and curly brackets on the same line. Is there a rule (in .jsbeautifyrc) to force the desired behavior or is this a bug in js-beautify?

Body:
Try paste this rule in your .jsbeautifyrc

    {
        "js": {
            "brace_style": "expand"
        }
    }

Also you can try this extension too: Visual Studio Code Format


问:
Why mysql workbench 8.0 is throwing error for not closing if's, though all "if's" are closed properly?
Though my procedure code has proper "if"s (that is "if"s that are opened and closed properly), mysql workbench 8.0 is throwing an error that all "if"s are not closed properly. I can't find any other mistake too. Please help me out.

If I am adding extra "if"s in the end, the errors are gone. But it is not correct since those "end if"s do not have any if so that they can be closed.Though it is not showing any error, while applying the procedure with the additional "end if"s, it is not getting applied instead throws some other error.

```<code>IF(Ser ='search') THEN

        IF(Value = 0) THEN

            IF EXISTS(SELECT Role FROM U WHERE Name = name) THEN

                IF(O = 0) THEN

                    IF(F1 <> NULL AND F1V <> NULL AND
                        F2 = NULL AND F2V = NULL
                        ) THEN

                        IF EXISTS (SELECT * FROM Com ) THEN

                            SET V=0;

                        END IF;

                    ELSE IF (F1<> NULL AND F1V <> NULL AND
                            F2 <> NULL AND F2V <> NULL
                            ) THEN

                        IF EXISTS ( SELECT * FROM Com ) THEN

                                                        SET V=1;

                        END IF;

                    END IF;

                ELSE IF(O = 1) THEN

                                SET A=0;

                     END IF;

        END IF;
    END IF;
END IF;
</code>```

答: I changed the else if condition to if and it started working.</p>

Body:
Though my procedure code has proper "if"s (that is "if"s that are opened and closed properly), mysql workbench 8.0 is throwing an error that all "if"s are not closed properly. I can't find any other mistake too. Please help me out.

If I am adding extra "if"s in the end, the errors are gone. But it is not correct since those "end if"s do not have any if so that they can be closed.Though it is not showing any error, while applying the procedure with the additional "end if"s, it is not getting applied instead throws some other error.

IF(Ser ='search') THEN

        IF(Value = 0) THEN

            IF EXISTS(SELECT Role FROM U WHERE Name = name) THEN

                IF(O = 0) THEN

                    IF(F1 <> NULL AND F1V <> NULL AND
                        F2 = NULL AND F2V = NULL
                        ) THEN

                        IF EXISTS (SELECT * FROM Com ) THEN

                            SET V=0;

                        END IF;

                    ELSE IF (F1<> NULL AND F1V <> NULL AND
                            F2 <> NULL AND F2V <> NULL
                            ) THEN

                        IF EXISTS ( SELECT * FROM Com ) THEN

                                                        SET V=1;

                        END IF;

                    END IF;

                ELSE IF(O = 1) THEN

                                SET A=0;

                     END IF;

        END IF;
    END IF;
END IF;


问:
calculating price with two values
So I have something like this...

I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7     . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.

this is my index.php

```<code>   <div class="container">

      <div class="row">
       <div class="col-xs-3 col-xs-offset-2">
        <h3>gender:</h3>
        <!-- select gender -->
         <select class="form-control" id="gender">
         <option>female</option>
        <option>male</option>
         </select>
        </div>
       <div class="col-xs-3">
         <h3>weight </h3>
          <!-- input weight -->
       <input type="" name="weight" id="weight">
        </div>

         </div>
      <div id="ticketInfo">
        <h3 id="yourTicket">No gender Selected</h3>
     </div>
     </div>
    <script src="js/jquery-1.12.2.js"></script>
   <script src="js/bootstrap.js"></script>
     <script src="js/scripts.js"></script>
</code>```

this is my script

```<code>  function Ticket(gender, weight) {
  this.gender=gender;
  this.weight=weight;

     }

   Ticket.prototype.getPrice=function() {
     var price;

   if((this.gender==="male ")||(this.weight=>"200 ")){
       price=20;
        }
    if((this.gender==="female ")||(this.weight=>"200 ")) {
      price=15;
     }
     if((this.gender==="male ")||(this.weight=<"200 ")) {
    price=10;
    }
   if((this.gender==="female ")||(this.weight=<"200 ")) {
    price=7;
   }

  return price;
 }

$("select").change(function() {
  var genderOptions=[];
  $("select option:selected").each(function() {
   genderOptions.push($(this).text() + " ");
 });
 var newTicket = new
 Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
 $("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
 newTicket.getPrice().toFixed(2));
   });
</code>```

at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.

答:
Try this with Syed's solution.

Logic should be using && operator not ||

    function Ticket(gender, weight) {
        this.gender=gender;
      this.weight=weight;
    }

    Ticket.prototype.getPrice=function() {
      var price;
      if(this.gender==="male" && this.weight > 200){
    price=20;
  }
  else if(this.gender==="female" && this.weight > 200) {
    price=15;
  }
  else if(this.gender==="male" && this.weight <= 200) {
    price=10;
  }
  else if(this.gender==="female" && this.weight <= 200) {
    price=7;

      }
      return price;
    }

    $("#calculate").click(function() {
        var genderOptions=[];
        $("select option:selected").each(function() {
            genderOptions.push($(this).text() + " ");
        });

        var newTicket = new
        Ticket($("#gender").val(),$('#weight').val());
        var multiplyVal = newTicket.weight * newTicket.getPrice();
        $("#yourTicket").text("Gender: " + newTicket.gender + " Weight: " + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
    });
```

```

gender:

  <select class="form-control" id="gender">
    <option value="female" selected>female</option>
    <option value="male">male</option>
  </select>

weight

  <input type="" name="weight" id="weight">

No gender Selected

<button id="calculate" >Calculate</button>
```

Title: calculating price with two values

Body:
So I have something like this...

I have a form where you select your gender and input your weight. each gender has different ranges of prices for example if your a male and your weight is greater than 200 your price is 20, if your a female and your weight is greater than 200 your price is 15, and if your male and your weight is less than 200 your price is 10, for the female if her weight is less than 200 her price is 7     . i have been trying to make it possible with jquery and PHP but it only seems to work with select option and won't work with input data.

this is my index.php

gender:

         <select class="form-control" id="gender">
         <option>female</option>
        <option>male</option>
         </select>

weight

       <input type="" name="weight" id="weight">

No gender Selected

this is my script

  function Ticket(gender, weight) {
  this.gender=gender;
  this.weight=weight;

     }

   Ticket.prototype.getPrice=function() {
     var price;

   if((this.gender==="male ")||(this.weight=>"200 ")){
       price=20;
        }
    if((this.gender==="female ")||(this.weight=>"200 ")) {
      price=15;
     }
     if((this.gender==="male ")||(this.weight=<"200 ")) {
    price=10;
    }
   if((this.gender==="female ")||(this.weight=<"200 ")) {
    price=7;
   }

  return price;
 }

$("select").change(function() {
  var genderOptions=[];
  $("select option:selected").each(function() {
   genderOptions.push($(this).text() + " ");
 });
 var newTicket = new
 Ticket(genderOptions[0],genderOptions[1],genderOptions[2]);
 $("#yourTicket").text(newTicket.gender + newTicket.weight + " $" +
 newTicket.getPrice().toFixed(2));
   });

at the end in trying to multiply the price by the weight. any help will be really appreciated, thanks in advance.

Body:
Try this with Syed's solution.

Logic should be using && operator not ||

    function Ticket(gender, weight) {
        this.gender=gender;
      this.weight=weight;
    }

    Ticket.prototype.getPrice=function() {
      var price;
      if(this.gender==="male" && this.weight > 200){
    price=20;
  }
  else if(this.gender==="female" && this.weight > 200) {
    price=15;
  }
  else if(this.gender==="male" && this.weight <= 200) {
    price=10;
  }
  else if(this.gender==="female" && this.weight <= 200) {
    price=7;

      }
      return price;
    }

    $("#calculate").click(function() {
        var genderOptions=[];
        $("select option:selected").each(function() {
            genderOptions.push($(this).text() + " ");
        });

        var newTicket = new
        Ticket($("#gender").val(),$('#weight').val());
        var multiplyVal = newTicket.weight * newTicket.getPrice();
        $("#yourTicket").text("Gender: " + newTicket.gender + " Weight: " + newTicket.weight + " $" + newTicket.getPrice().toFixed(2) + " and your multiplied value is " + multiplyVal);
    });

<div class="col-xs-3 col-xs-offset-2">
  <h3>gender:</h3>
  <!-- select gender -->
  <select class="form-control" id="gender">
    <option value="female" selected>female</option>
    <option value="male">male</option>
  </select>
</div>
<div class="col-xs-3">
  <h3>weight </h3>
  <!-- input weight -->
  <input type="" name="weight" id="weight">
</div>
<div id="ticketInfo">
  <h3 id="yourTicket">No gender Selected</h3>
</div>
<button id="calculate" >Calculate</button>


问:
Netbeans fails to build because the .jar file cannot be deleted
Netbeans fails to build because .jar file from the previous build cannot be deleted. I am unable to delete the file manually or change/view its owners either even with Administrative Privileges. Is netbeans locking these files?</p>

答:
I think I just had this problem. Netbeans isn't the real issue here. The problem is that Java SE is getting stuck for some odd reason. Windows has this problem with apps hanging in the background in general but it also could be the program not exiting correctly due to code.

Here's how I fixed it:
1) Closed NetBeans (may not actually be necessary though)
2) Opened task manager
3) Manually ended Netbeans processes if it's still hanging (again, may not be necessary)
4) Look for any process with "Java SE" in the name and end that process
5) Try to build again.

Worked for me.


答:
Prettier is also used for formatting the code in VS code. This extension does not have this problem. You can try installing this extension and try once. I have checked this and did not see this issue.

Extension name: Prettier - Code formatter

Title: Unexpected Indentation of Nested Opening Brackets


问:
How can I join the last X entries in a string array?
I've got an array like this:

```<code>string[] parts = line.Split(',');

string store = parts[0];
string sku = parts[1];
string subcatcode = parts[2];
string price = parts[3];
string date = parts[4];
string desc = parts[5];
</code>```

I want description to equal the joined value of all the parts with an index of 5 or higher. Will this work or is there a better way to do it?

```<code>string desc = string.Join(",", parts.Skip(5).ToArray());
</code>```

The issue is that the last part of the CSV I'm parsing can contain commas (parts 0-4 are guaranteed not to).

答: Sure this should work just fine. If you want to get rid of the trailing comma's you can .TrimEnd() your string first.</p>

OwnerDisplayName: John Sheehan

ContentLicense: CC BY-SA 2.5

Body:
I've got an array like this:

string[] parts = line.Split(',');

string store = parts[0];
string sku = parts[1];
string subcatcode = parts[2];
string price = parts[3];
string date = parts[4];
string desc = parts[5];

I want description to equal the joined value of all the parts with an index of 5 or higher. Will this work or is there a better way to do it?

string desc = string.Join(",", parts.Skip(5).ToArray());

The issue is that the last part of the CSV I'm parsing can contain commas (parts 0-4 are guaranteed not to).

OwnerDisplayName: Tim J


问:
onchange on date inputs

Possible Duplicate:

  What events does an <input type=“number” /> fire when it's value is changed?

I have a date input field

```<code><input type="date" name="..">
</code>```

In webkit and firefox, it will be added two up/down arrows on the side of the input. When clicking them, the date goes forward or backwards, but the onchange event doesn't trigger until the field loses focus. Is there a workaround for this?

答:
You could store the value in a global and check for a difference onclick.

```<code><input type="date" name="myDate" id="myDate" />

var myApp = {};
myApp.myDate = "";

document.getElementById('myDate').onclick = function (e) {
    if (this.value != myApp.myDate) {
        // run onchange code

        // then set last value to current value
        myApp.myDate = this.value;
    }
};
</code>```

See example →

EDIT: Or, duplicate question, like comments suggest.  (See oninput event)

Title: onchange on date inputs

Body:
Possible Duplicate:

  What events does an <input type=“number” /> fire when it's value is changed?

I have a date input field

<input type="date" name="..">

In webkit and firefox, it will be added two up/down arrows on the side of the input. When clicking them, the date goes forward or backwards, but the onchange event doesn't trigger until the field loses focus. Is there a workaround for this?

Body:
You could store the value in a global and check for a difference onclick.

<input type="date" name="myDate" id="myDate" />

var myApp = {};
myApp.myDate = "";

document.getElementById('myDate').onclick = function (e) {
    if (this.value != myApp.myDate) {
        // run onchange code

        // then set last value to current value
        myApp.myDate = this.value;
    }
};

See example →

EDIT: Or, duplicate question, like comments suggest.  (See oninput event)


问:
The callback function in celery
Now I have two consumer:

task_A.py:

```<code>from B import task_b

@app_a.task
def task_a(args):
    # do something
    task_c.apply_async(args, link=task_a_a.s(args))

@app_a.task
def task_a_a()
    # do something
</code>```

task_B.py:

```<code>@app_b.task
def task_b(*args)
    # do something
    return res
</code>```

But I get error in task_B just like:

```<code>KeyError: 'task_A.task_a_a'
</code>```

How to make it right

答:
Check Task_c is not present in function task_a.

```<code>task_c.apply_async(args, link=task_a_a.s(args))
</code>```

It could be :

```<code>task_b.apply_async(args, link=task_a_a.s(args))
</code>```

Title: The callback function in celery

Body:
Now I have two consumer:

task_A.py:

from B import task_b

@app_a.task
def task_a(args):
    # do something
    task_c.apply_async(args, link=task_a_a.s(args))

@app_a.task
def task_a_a()
    # do something

task_B.py:

@app_b.task
def task_b(*args)
    # do something
    return res

But I get error in task_B just like:

KeyError: 'task_A.task_a_a'

How to make it right

Body:
Check Task_c is not present in function task_a.

task_c.apply_async(args, link=task_a_a.s(args))

It could be :

task_b.apply_async(args, link=task_a_a.s(args))


问:
How to retrieve the bounding box of a scalebar from a AnchoredSizeBar from Matplotlib
I am facing serious difficulties in retrieving the bounding box of a mpl_toolkits.axes_grid1.anchored_artists "AnchoredSizeBar" object.

So far, all I found was how to insert (create) an AnchoredSizeBar into my figure. But I can't retrieve its position. A relative position in respect to its given axes would also be welcome.

Ultimately, I would like to make a AnchoredSizeBar as Behnam asks in1. But in order to do so, I would need to create a series of AnchoredSizeBars all contiguous one to another in the figure. In order to do so, I would need a function to retrieve their relative positions and apply those into the creation of the other AnchoredSizeBars, creating finally a full scalebar.

This subject is related to other links presented below:

1) How to insert scale bar in a map in matplotlib

2) Add fill_bar argument to AnchoredSizeBar

Here is a snippet code of a desired API for AnchoredSizeBar object extent retrieval.

```<code>import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar

fig, ax = plt.subplots(figsize=(3, 3))

bar0 = AnchoredSizeBar(ax.transData, 0.3, 'unfilled', loc=3, frameon=False,
                       size_vertical=0.05, fill_bar=False)
ax.add_artist(bar0)

bar0_extent = bar0.get_extent()

fig.show()
</code>```

I thank you for your time, sincerely yours,

Philipe Leal

答:
To get the extent you can pass in ax.figure.canvas.renderer where ax is the axes to which the object has been added to:

bar0_extent = bar0.get_extent(ax.figure.canvas.renderer)
```

But I second @ImportanceOfBeingErnest's suggestion for your particular use case. The doc-string for AnchoredSizeBar suggests that methods:

Docstring:      An offset box placed according to the legend location
  loc. AnchoredOffsetbox has a single child. When multiple children is
  needed, use other OffsetBox class to enclose them.  By default, the
  offset box is anchored against its parent axes. You may explicitly
  specify the bbox_to_anchor.

Hope this helps.

Body:
I am facing serious difficulties in retrieving the bounding box of a mpl_toolkits.axes_grid1.anchored_artists "AnchoredSizeBar" object.

So far, all I found was how to insert (create) an AnchoredSizeBar into my figure. But I can't retrieve its position. A relative position in respect to its given axes would also be welcome.

Ultimately, I would like to make a AnchoredSizeBar as Behnam asks in1. But in order to do so, I would need to create a series of AnchoredSizeBars all contiguous one to another in the figure. In order to do so, I would need a function to retrieve their relative positions and apply those into the creation of the other AnchoredSizeBars, creating finally a full scalebar.

This subject is related to other links presented below:

1) How to insert scale bar in a map in matplotlib

2) Add fill_bar argument to AnchoredSizeBar

Here is a snippet code of a desired API for AnchoredSizeBar object extent retrieval.

import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar

fig, ax = plt.subplots(figsize=(3, 3))

bar0 = AnchoredSizeBar(ax.transData, 0.3, 'unfilled', loc=3, frameon=False,
                       size_vertical=0.05, fill_bar=False)
ax.add_artist(bar0)

bar0_extent = bar0.get_extent()

fig.show()

I thank you for your time, sincerely yours,

Philipe Leal

Body:
To get the extent you can pass in ax.figure.canvas.renderer where ax is the axes to which the object has been added to:

bar0_extent = bar0.get_extent(ax.figure.canvas.renderer)

But I second @ImportanceOfBeingErnest's suggestion for your particular use case. The doc-string for AnchoredSizeBar suggests that methods:

Docstring:      An offset box placed according to the legend location
  loc. AnchoredOffsetbox has a single child. When multiple children is
  needed, use other OffsetBox class to enclose them.  By default, the
  offset box is anchored against its parent axes. You may explicitly
  specify the bbox_to_anchor.

Hope this helps.