问:
How to get the value of multidimensional array based on the ID
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id</p>

```<code><?php include_once('fake_db.php'); ?>

<--index.php-->

<div class="widget-body">
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <th>Name</th><th>Position</th><th>Action</th>
    </tr>
    </thead>
    <?php foreach($employees as $key => $value){ ?>
        <tr>
            <td><?= $value['name']?></td>
            <td><?= $value['position']; ?></td>
            <td><a href="profile.php?id=<?= $key; ?>">View Profile</a></td>
        </tr>
    <?php } ?>
</table>
</div>

<-- profile.php -->
<h3>Employee Profile : Employee Name</h3>
<a href="index.php">Back to Employee List</a>
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <td>Name </td>
        <td>Employee Position</td>
    </tr>
    </thead>
    <tr>

            <td></td>
            <td></td>
    </tr>
</table>

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

</code>```

答:
In the profile.php code it as below, I have put the selected employees information array to selected_employees array for ease.

```<code><?php if(isset($_GET["id"])):
    $selected_employee=$employees[$_GET["id"]];
    ?>

    <h1>Is Set</h1>
    <h3>Employee Profile : <?= $selected_employee["name"]; ?></h3>
    <a href="index.php">Back to Employee List</a>
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
            <tr>
                <td>Name <?= $selected_employee["name"]; ?></td>
                <td>Employee Position: <?= $selected_employee["position"]; ?></td>
            </tr>
        </thead>
    </table>

<?php endif; ?>
</code>```

Body:
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id

<?php include_once('fake_db.php'); ?>

<--index.php-->

        Name	Position	Action

    <?php foreach($employees as $key => $value){ ?>

            <?= $value['name']?>
            <?= $value['position']; ?>
            <a href="profile.php?id=<?= $key; ?>">View Profile

    <?php } ?>

<-- profile.php -->

Employee Profile : Employee Name

Back to Employee List

        Name
        Employee Position

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

Body:
In the profile.php code it as below, I have put the selected employees information array to selected_employees array for ease.

<?php if(isset($_GET["id"])):
    $selected_employee=$employees[$_GET["id"]];
    ?>

    <h1>Is Set</h1>
    <h3>Employee Profile : <?= $selected_employee["name"]; ?></h3>
    <a href="index.php">Back to Employee List</a>
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
            <tr>
                <td>Name <?= $selected_employee["name"]; ?></td>
                <td>Employee Position: <?= $selected_employee["position"]; ?></td>
            </tr>
        </thead>
    </table>

<?php endif; ?>


来源: stackexchange

问:
Undefined variable: data (laravel multiple image upload)

This is my controller for multiple image upload, I am getting an error saying, data is undefined on json_encode(data),, can some give me a solution?

答:
Try this</p>

```<code>$data = [];

    if($request->hasfile('image') as $image){
     foreach($request->file('image') as $id => $image){
                $ext = $image->getClientOriginalExtension();
                $name = $id.time().'.'.$ext;
                $path = public_path('\property\');
                $image->move($path, $name);
                $data[$id] = $name;
            }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this

$data = [];

    if($request->hasfile('image') as $image){
     foreach($request->file('image') as $id => $image){
                $ext = $image->getClientOriginalExtension();
                $name = $id.time().'.'.$ext;
                $path = public_path('\property\');
                $image->move($path, $name);
                $data[$id] = $name;
            }
    }


问:
How can i use espresso to click an item from a list view based on item' text?
I'm trying to click a list view item using espresso but no success.

I tried everything that's on stackOverflow

```<code>onData(anything()).inAdapterView(withId(R.id.more_menu_list)).atPosition(0).
                    onChildView(withId(R.id.mm_item_text)).
                    check(matches(withText("Log in")))
                    .perform(click());

            onView(allOf(is(instanceOf(MenuListAdapter.class)), hasSibling(withText("Log in")))).perform(click());

            onData(allOf(is(instanceOf(MenuListAdapter.class)), hasEntry(equalTo("STR"), is("Log in"))))
                            .perform(click());

            onData(anything()).inAdapterView(withContentDescription("Log in")).atPosition(0).perform(click());

            onData(hasToString(startsWith("Promotions")))
                    .inAdapterView(withId(R.id.more_menu_list)).atPosition(0)
                    .perform(click());

            onData(hasEntry(equalTo(MenuListAdapter.class),is("Log out")))
                    .onChildView(withId(R.id.more_menu_list));
            onView(withId(R.id.mm_item_text)).check(matches(withText("Log in")));

I also tried to create a custom matcher
    public static Matcher<Object> withItemValue(final String value) {
        return new BoundedMatcher<Object, ExtraMenu>(ExtraMenu.class) {
            @Override
            protected boolean matchesSafely(ExtraMenu item) {
                return item.getText().toUpperCase().equals(String.valueOf(value));

            }

            @Override
            public void describeTo(Description description) {
                description.appendText("has value " + value);
            }
        };
    }
</code>```

used as:

```<code>onData(withItemValue("Promotions")).inAdapterView(withId(R.id.more_menu_list)).perform(click());
</code>```

Most of the times i get this error. There s a menu with 5 items
Caused by: java.lang.RuntimeException: No data found matching: has value Promotions contained values: <[Data: 0 (class: java.lang.Integer) token: 0, Data: 1 (class: java.lang.Integer) token: 1, Data: 2 (class: java.lang.Integer) token: 2, Data: 3 (class: java.lang.Integer) token: 3, Data: 4 (class: java.lang.Integer) token: 4]>

答:
I found a way, i'll post it in order to help others.
I had to change the list view to a recycle view and used this command.

```<code>onView(withId(R.id.list))
                .perform(RecyclerViewActions.actionOnItem(
                        hasDescendant(withText("Your string")), click()));
</code>```

You might want to use Thread.sleep(2000) if you have multiple actions before this line of code.
Also you need this dependency in your build.gradle:

```<code>androidTestImplementation("com.android.support.test.espresso:espresso-contrib:2.2.2") {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'support-v7'
    exclude group: 'com.android.support', module: 'design'
    exclude module: 'support-annotations'
    exclude module: 'recyclerview-v7'
}
</code>```

Body:
I'm trying to click a list view item using espresso but no success.

I tried everything that's on stackOverflow

onData(anything()).inAdapterView(withId(R.id.more_menu_list)).atPosition(0).
                    onChildView(withId(R.id.mm_item_text)).
                    check(matches(withText("Log in")))
                    .perform(click());

            onView(allOf(is(instanceOf(MenuListAdapter.class)), hasSibling(withText("Log in")))).perform(click());

            onData(allOf(is(instanceOf(MenuListAdapter.class)), hasEntry(equalTo("STR"), is("Log in"))))
                            .perform(click());

            onData(anything()).inAdapterView(withContentDescription("Log in")).atPosition(0).perform(click());

            onData(hasToString(startsWith("Promotions")))
                    .inAdapterView(withId(R.id.more_menu_list)).atPosition(0)
                    .perform(click());

            onData(hasEntry(equalTo(MenuListAdapter.class),is("Log out")))
                    .onChildView(withId(R.id.more_menu_list));
            onView(withId(R.id.mm_item_text)).check(matches(withText("Log in")));

I also tried to create a custom matcher
    public static Matcher<Object> withItemValue(final String value) {
        return new BoundedMatcher<Object, ExtraMenu>(ExtraMenu.class) {
            @Override
            protected boolean matchesSafely(ExtraMenu item) {
                return item.getText().toUpperCase().equals(String.valueOf(value));

            }

            @Override
            public void describeTo(Description description) {
                description.appendText("has value " + value);
            }
        };
    }

used as:

onData(withItemValue("Promotions")).inAdapterView(withId(R.id.more_menu_list)).perform(click());

Most of the times i get this error. There s a menu with 5 items
Caused by: java.lang.RuntimeException: No data found matching: has value Promotions contained values: <[Data: 0 (class: java.lang.Integer) token: 0, Data: 1 (class: java.lang.Integer) token: 1, Data: 2 (class: java.lang.Integer) token: 2, Data: 3 (class: java.lang.Integer) token: 3, Data: 4 (class: java.lang.Integer) token: 4]>

Body:
I found a way, i'll post it in order to help others.
I had to change the list view to a recycle view and used this command.

onView(withId(R.id.list))
                .perform(RecyclerViewActions.actionOnItem(
                        hasDescendant(withText("Your string")), click()));

You might want to use Thread.sleep(2000) if you have multiple actions before this line of code.
Also you need this dependency in your build.gradle:

androidTestImplementation("com.android.support.test.espresso:espresso-contrib:2.2.2") {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'support-v7'
    exclude group: 'com.android.support', module: 'design'
    exclude module: 'support-annotations'
    exclude module: 'recyclerview-v7'
}


问:
Selenium C# WebDriver: Wait until element is present
I want to make sure that an element is present before the webdriver starts doing stuff.

I'm trying to get something like this to work:

```<code>WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));
</code>```

I'm mainly struggling how to setup up the anonymous function...

答:
WebDriverWait won't take effect.

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end
```

This would immediately throw an exception once the page was "interactive". I don't know why, but the timeout acts as if it does not exist.

Perhaps SeleniumExtras.WaitHelpers works, but I didn't try. It's official, but it was split out into another NuGet package. You can refer to C# Selenium 'ExpectedConditions is obsolete'.

I use FindElements and check Count == 0. If true, use await Task.Delay. It's really not quite efficient.

Body:
I want to make sure that an element is present before the webdriver starts doing stuff.

I'm trying to get something like this to work:

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));

I'm mainly struggling how to setup up the anonymous function...

Body:
WebDriverWait won't take effect.

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end

This would immediately throw an exception once the page was "interactive". I don't know why, but the timeout acts as if it does not exist.

Perhaps SeleniumExtras.WaitHelpers works, but I didn't try. It's official, but it was split out into another NuGet package. You can refer to C# Selenium 'ExpectedConditions is obsolete'.

I use FindElements and check Count == 0. If true, use await Task.Delay. It's really not quite efficient.


问:
How to use multiple tables using specific condition
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

```<code>If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB
</code>```

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

答:
or you can also try:

```<code>DECLARE @x AS INT
DECLARE @sqlquery AS NVARCHAR(100)

SET @x = 10 --ignore this if you already have a value for x

SET @sqlquery = 'SELECT * FROM '+ CASE WHEN @x = 10 THEN 'TableA' ELSE 'tableB' END

EXEC SP_EXECUTESQL @sqlquery
</code>```

you can read also:
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017

Body:
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

Body:
or you can also try:

DECLARE @x AS INT
DECLARE @sqlquery AS NVARCHAR(100)

SET @x = 10 --ignore this if you already have a value for x

SET @sqlquery = 'SELECT * FROM '+ CASE WHEN @x = 10 THEN 'TableA' ELSE 'tableB' END

EXEC SP_EXECUTESQL @sqlquery

you can read also:
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017


问:
GCC builtin functions - 2003 vs 2019 behaviour
At page 14 of the book "Introduction to GCC" by Brian Gough, the author wants to show a linker error due to not supplying gcc with the libm library, where the code for the function sqrt resides:

```<code>$ gcc -Wall calc.c -o calc
/tmp/ccbR6Ojm.o: In function ‘main’:
/tmp/ccbR6Ojm.o(.text+0x19): undefined reference to ‘sqrt’
</code>```

The file calc.c (where the functionsqrt is invoked) is this:

```<code>#include <math.h>
#include <stdio.h>
int main (void)
{
    double x = sqrt (2.0);
    printf ("The square root of 2.0 is %f\n", x);
    return 0;
}
</code>```

This book is from 2003.
On my current Ubuntu Linux 18, I can't reproduce the link error: it links and works, printing the correct result:

```<code>$ ./calc
1.414214
</code>```

I found with ldd calc that the libm.so shared library is not invoked at runtime. Nor of course is the static library libm.a involved here.
So how does gcc deal with the function sqrt? I found that in this case it uses the sqrt GCC built-in function.
Its code gets inserted in the calc.o object file at compile time. So no "undefined reference" error.

First question: this the whole story or am I missing something?

Second question: why did this behavior regarding the built-in functions of GCC change so much between 2003 (when the book was written) and now? (Practically invalidating the whole example, it seems to me)

Third question: why does the author make his examples  (e.g.$ gcc -Wall calc.c -lm -o cal) implying that the static library libc.a will be used, when in reality in Linux that syntax invokes the dynamic library libm.so? Is this specific to Linux and not to GNU GCC? What am I mising?

答:
I think this is due to optimization of a constant value. Modern GCC can compute exact value of sqrt (2.0). If you force it not to use the built-ins with -fno-builtin, it will still fail to link. Also, if you change the code a little bit so that the argument to sqrt() is not literal, it will fail to link:

```<code>#include <math.h>
#include <stdio.h>

double t = 2.0;

int main (void)
{
    double x = sqrt (t);
    printf ("The square root of 2.0 is %f\n", x);
    return 0;
}
</code>```

This produces link error:

```<code>> gcc -o test test.c
/usr/bin/ld: /tmp/ccLjHnQx.o: in function `main':
test.c:(.text+0x11): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
</code>```

Regarding your 3rd question, -lm does not imply static library, AFAIK.

Body:
At page 14 of the book "Introduction to GCC" by Brian Gough, the author wants to show a linker error due to not supplying gcc with the libm library, where the code for the function sqrt resides:

$ gcc -Wall calc.c -o calc
/tmp/ccbR6Ojm.o: In function ‘main’:
/tmp/ccbR6Ojm.o(.text+0x19): undefined reference to ‘sqrt’

The file calc.c (where the functionsqrt is invoked) is this:

#include <math.h>
#include <stdio.h>
int main (void)
{
    double x = sqrt (2.0);
    printf ("The square root of 2.0 is %f\n", x);
    return 0;
}

This book is from 2003.
On my current Ubuntu Linux 18, I can't reproduce the link error: it links and works, printing the correct result:

$ ./calc
1.414214

I found with ldd calc that the libm.so shared library is not invoked at runtime. Nor of course is the static library libm.a involved here.
So how does gcc deal with the function sqrt? I found that in this case it uses the sqrt GCC built-in function.
Its code gets inserted in the calc.o object file at compile time. So no "undefined reference" error.

First question: this the whole story or am I missing something?

Second question: why did this behavior regarding the built-in functions of GCC change so much between 2003 (when the book was written) and now? (Practically invalidating the whole example, it seems to me)

Third question: why does the author make his examples  (e.g.$ gcc -Wall calc.c -lm -o cal) implying that the static library libc.a will be used, when in reality in Linux that syntax invokes the dynamic library libm.so? Is this specific to Linux and not to GNU GCC? What am I mising?

Body:
I think this is due to optimization of a constant value. Modern GCC can compute exact value of sqrt (2.0). If you force it not to use the built-ins with -fno-builtin, it will still fail to link. Also, if you change the code a little bit so that the argument to sqrt() is not literal, it will fail to link:

#include <math.h>
#include <stdio.h>

double t = 2.0;

int main (void)
{
    double x = sqrt (t);
    printf ("The square root of 2.0 is %f\n", x);
    return 0;
}

This produces link error:

> gcc -o test test.c
/usr/bin/ld: /tmp/ccLjHnQx.o: in function `main':
test.c:(.text+0x11): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

Regarding your 3rd question, -lm does not imply static library, AFAIK.


问:
What is an idiomatic Scala way to "remove" one element from an immutable List?
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

```<code>def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
</code>```

答:
You could try this:

```<code>scala> val (left,right) = List(1,2,3,2,4).span(_ != 2)
left: List[Int] = List(1)
right: List[Int] = List(2, 3, 2, 4)

scala> left ::: right.tail
res7: List[Int] = List(1, 3, 2, 4)
</code>```

And as method:

```<code>def removeInt(i: Int, li: List[Int]) = {
   val (left, right) = li.span(_ != i)
   left ::: right.drop(1)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}

Body:
You could try this:

scala> val (left,right) = List(1,2,3,2,4).span(_ != 2)
left: List[Int] = List(1)
right: List[Int] = List(2, 3, 2, 4)

scala> left ::: right.tail
res7: List[Int] = List(1, 3, 2, 4)

And as method:

def removeInt(i: Int, li: List[Int]) = {
   val (left, right) = li.span(_ != i)
   left ::: right.drop(1)
}


问:
How to override react-skylight min-height in next.js?
These days I am developing the next.js project. I am using react-skylight to create a modal. I want to override min-height. In skylight already had skylight-dialog CSS class. I have already attached the image regarding CSS and prop.

```<code>const myBigGreenDialog = {
     backgroundColor: '#ffffff',
     color: '#000',
     width: '50%',
     height: '200px',
     padding: '3rem'
   };
</code>```

答:
React skylight in 2018-04-03 v0.5.1 Change dialog style height to minHeight. try like this prop.</p>

```<code>const myBigGreenDialog = {
  backgroundColor: '#ffffff',
  color: '#000',
  width: '50%',
  minHeight: '250px',
  padding: '3rem'
};
</code>```

Body:
These days I am developing the next.js project. I am using react-skylight to create a modal. I want to override min-height. In skylight already had skylight-dialog CSS class. I have already attached the image regarding CSS and prop.

const myBigGreenDialog = {
     backgroundColor: '#ffffff',
     color: '#000',
     width: '50%',
     height: '200px',
     padding: '3rem'
   };

Body:
React skylight in 2018-04-03 v0.5.1 Change dialog style height to minHeight. try like this prop.

const myBigGreenDialog = {
  backgroundColor: '#ffffff',
  color: '#000',
  width: '50%',
  minHeight: '250px',
  padding: '3rem'
};


问:
Sending push notifications to Mobile application with GCM SDK through FCM service
Our company provides a mobile application as addon to an onpremise product. We have built a web service to send push notifications to that application through both GCM and FCM.

Around 2 years ago the mobile app was updated to utilize the FCM SDK. This means any client version afterwards utilizes FCM.

However, a large portion of the clientbase do not update the application - so we still see large percentage traffic from devices with the GCM SDK. This is a problem since GCM will be turned off very soon.

We have checked Google's documentation but we don't find this case covered there - and we have trouble testing ourselves as the device cannot get a new token from GCM.
We want to be sure there is no way to support GCM SDK devices before communicating with end customers.

In short:

Is there a known way to send push notification through FCM's service to an app that works with GCM SDK's Notifications?

答:
Just to answer and close this - we ran several tests and it was not possible to send a notification to a GCM SDK device using FCM services in any way.

Now that GCM is deprecated and offline, this no longer matters.


问:
Hadoop: how to correctly decommission nodes on cluster?
I've been trying to change number of nodes in my Hadoop cluster (in total 5 nodes including 1 master and 4 workers) by following this solution change number of data nodes in Hadoop and this useful post Commissioning and Decommissioning of Datanode in Hadoop Cluster

Now I can see that on HDFS I have successfully decommissioned one node:
HDFS screenshot

I have set up a exclude file property in my hdfs-site.xml hdfs.xml screenshot as well as yarn-site.xml yarn-site.xml screenshot which includes the ip address of the node that I want to decommission. Like follow: excludes file

Also I have done refreshing the nodes commands.

Finally I run hadoop dfsadmin –report and I can see the node is actually decommissioned : nodes report

However, on MapReduce cluster metrics I found that there are 5 active nodes and the node that has been decommissioned on HDFS is not indentified in decommissioned nodes here.

see: hadoop cluster metrics

Why is that?

答: The issue solves when I changed name of the host on exclude file. The node name should not contain any port number</p>


问:
Not able to check in excel using Apache POI if specific cell as per row and column is empty in Selenium with Java
I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.

From another class I'm calling ExcelTest:

```<code>ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");

sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);
</code>```

ExcelTest Class

```<code>public class ExcelTest
 {
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;

public ExcelTest(String xlFilePath) throws Exception
{
    this.xlFilePath = xlFilePath;
    fis = new FileInputStream(xlFilePath);
    workbook = new XSSFWorkbook(fis);
    fis.close();
}

public void setCellData(String sheetName, String colName, int rowNum, String value)
{
    try
    {
        int col_Num = -1;
        sheet = workbook.getSheet(sheetName);

        row = sheet.getRow(0);
        for (int i = 0; i < row.getLastCellNum(); i++)
        {
            if(row.getCell(i).getStringCellValue().trim().equals(colName))
            {
                col_Num = i;
            }
        }

        sheet.autoSizeColumn(col_Num);

        for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);

            isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();

            if (this.isEmptyStringCell)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }
            else
            {
                j=j+1;
            }

            }

        /*row = sheet.getRow(rowNum - 1);
        if(row==null)
            row = sheet.createRow(rowNum - 1);

        cell = row.getCell(col_Num);
        if(cell == null)
            cell = row.createCell(col_Num);

        cell.setCellValue(value);*/

        System.out.println("The cell value is "+cell.getStringCellValue());

        fos = new FileOutputStream(xlFilePath);
        workbook.write(fos);
        fos.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();

    }
   }
</code>```

}

If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.

```<code>          for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);

            isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();

            if (this.isEmptyStringCell)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }
            else
            {
                j=j+1;
            }

        }
</code>```

Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.

答:
I've found solution for the above question and only need to change few code and now it is working as expected:</p>

```<code>          for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);
            //it will check if cell contains no value then create cell and set value
            if(cell == null)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }

            }
</code>```

Body:
I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.

From another class I'm calling ExcelTest:

ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");

sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);

ExcelTest Class

public class ExcelTest
 {
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;

public ExcelTest(String xlFilePath) throws Exception
{
    this.xlFilePath = xlFilePath;
    fis = new FileInputStream(xlFilePath);
    workbook = new XSSFWorkbook(fis);
    fis.close();
}

public void setCellData(String sheetName, String colName, int rowNum, String value)
{
    try
    {
        int col_Num = -1;
        sheet = workbook.getSheet(sheetName);

        row = sheet.getRow(0);
        for (int i = 0; i < row.getLastCellNum(); i++)
        {
            if(row.getCell(i).getStringCellValue().trim().equals(colName))
            {
                col_Num = i;
            }
        }

        sheet.autoSizeColumn(col_Num);

        for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);

            isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();

            if (this.isEmptyStringCell)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }
            else
            {
                j=j+1;
            }

            }

        /*row = sheet.getRow(rowNum - 1);
        if(row==null)
            row = sheet.createRow(rowNum - 1);

        cell = row.getCell(col_Num);
        if(cell == null)
            cell = row.createCell(col_Num);

        cell.setCellValue(value);*/

        System.out.println("The cell value is "+cell.getStringCellValue());

        fos = new FileOutputStream(xlFilePath);
        workbook.write(fos);
        fos.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();

    }
   }

}

If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.

          for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);

            isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();

            if (this.isEmptyStringCell)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }
            else
            {
                j=j+1;
            }

        }

Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.

Body:
I've found solution for the above question and only need to change few code and now it is working as expected:

          for(int j=2; j<7; j++)
            {
            row = sheet.getRow(j - 1);
            if(row==null)
                row = sheet.createRow(j - 1);

            cell = row.getCell(col_Num);
            //it will check if cell contains no value then create cell and set value
            if(cell == null)
            {
                cell = row.createCell(col_Num);
                cell.setCellValue(value);
                break;
            }

            }


问:
How to change the whole values of DataFrame?
At first attempt, I want to create a DataFrame but forgot to put some values:

```<code>a=[0,1/4,2/4,3/4,4]
b=[0,1/4,2/4,3/4,4]
z=DataFrame(index=a,columns=b)
</code>```

Then I got this.

```<code>>      0.00 0.25 0.50 0.75 4.00
> 0.00  NaN  NaN  NaN  NaN  NaN
> 0.25  NaN  NaN  NaN  NaN  NaN
> 0.50  NaN  NaN  NaN  NaN  NaN
> 0.75  NaN  NaN  NaN  NaN  NaN
> 4.00  NaN  NaN  NaN  NaN  NaN
</code>```

I want to replace all of values by np.arange(25).reshape(5,5)

Then I tried this:

```<code>z.values=np.arange(25).reshape(5,5)
</code>```

Result:

object.setattr(self, name, value)

AttributeError: can't set attribute

I mean I could re-create the DataFrame with values in it but it seems to be very .... ( dont know how to say).

Question:

1/ Why I can not do it ?

2/ How to solve it ?

3/ On the condition that I want every single values of z.values would be the result of multiplication of columns and rows(rows * columns). How can I do it ?

Expected result of 3/

```<code>     0.00    0.25   0.50    0.75 4.00
0.00    0       0      0       0    0
0.25    0  0.0625  0.125  0.1875    1
0.50    0   0.125   0.25   0.375    2
0.75    0  0.1875  0.375  0.5625    3
4.00    0       1      2       3   16
</code>```

Body:
At first attempt, I want to create a DataFrame but forgot to put some values:

a=[0,1/4,2/4,3/4,4]
b=[0,1/4,2/4,3/4,4]
z=DataFrame(index=a,columns=b)

Then I got this.

>      0.00 0.25 0.50 0.75 4.00
> 0.00  NaN  NaN  NaN  NaN  NaN
> 0.25  NaN  NaN  NaN  NaN  NaN
> 0.50  NaN  NaN  NaN  NaN  NaN
> 0.75  NaN  NaN  NaN  NaN  NaN
> 4.00  NaN  NaN  NaN  NaN  NaN

I want to replace all of values by np.arange(25).reshape(5,5)

Then I tried this:

z.values=np.arange(25).reshape(5,5)

Result:

object.setattr(self, name, value)

AttributeError: can't set attribute

I mean I could re-create the DataFrame with values in it but it seems to be very .... ( dont know how to say).

Question:

1/ Why I can not do it ?

2/ How to solve it ?

3/ On the condition that I want every single values of z.values would be the result of multiplication of columns and rows(rows * columns). How can I do it ?

Expected result of 3/

     0.00    0.25   0.50    0.75 4.00
0.00    0       0      0       0    0
0.25    0  0.0625  0.125  0.1875    1
0.50    0   0.125   0.25   0.375    2
0.75    0  0.1875  0.375  0.5625    3
4.00    0       1      2       3   16

Body:
>>> z
     0.00 0.25 0.50 0.75 4.00
0.00  NaN  NaN  NaN  NaN  NaN
0.25  NaN  NaN  NaN  NaN  NaN
0.50  NaN  NaN  NaN  NaN  NaN
0.75  NaN  NaN  NaN  NaN  NaN
4.00  NaN  NaN  NaN  NaN  NaN
>>> def cross_mul(x):
...     return x.index * x.name
...
>>> z.apply(cross_mul)
      0.00    0.25   0.50    0.75  4.00
0.00   0.0  0.0000  0.000  0.0000   0.0
0.25   0.0  0.0625  0.125  0.1875   1.0
0.50   0.0  0.1250  0.250  0.3750   2.0
0.75   0.0  0.1875  0.375  0.5625   3.0
4.00   0.0  1.0000  2.000  3.0000  16.0
>>> z.apply(lambda x: x.index * x.name) // One Liner


问:
SolrClient python update document
I'm currently trying to create a small python program using SolrClient to index some files.

My need is that I want to index some file content and then add some attributes to enrich the document.
I used the post command line tool to index the files. Then I use a python program trying to enrich documents, something like this:

```<code>doc = solr.get('collection', id)
doc['new_attribute'] = 'value'
solr.index_json('collection',json.dumps([doc]))
solr.commit(openSearcher=True)
</code>```

Problem is that I have the feeling that we lost file content index. If I run a query with a word present in all attributes of the doc, I find it.

If I run a query with a word only in the file, it does not work (it works indexing only the file with post without my update tentative).

I'm not sure to understand how to update the doc keeping the index created by the post command.

I hope I'm clear enough, maybe I misunderstood the way it works...

thanks a lot

答:
It has worked for me in this way, it can be useful for someone</p>

```<code>from SolrClient import SolrClient
solrConect = SolrClient("http://xx.xx.xxx.xxx:8983/solr/")
doc = [{'id': 'my_id', 'count_related_like':{'set': 10}}]
solrConect.index_json("my_collection", json.dumps(doc) )
solrConect.commit("my_collection", softCommit=True)
</code>```

Title: SolrClient python update document

Body:
I'm currently trying to create a small python program using SolrClient to index some files.

My need is that I want to index some file content and then add some attributes to enrich the document.
I used the post command line tool to index the files. Then I use a python program trying to enrich documents, something like this:

doc = solr.get('collection', id)
doc['new_attribute'] = 'value'
solr.index_json('collection',json.dumps([doc]))
solr.commit(openSearcher=True)

Problem is that I have the feeling that we lost file content index. If I run a query with a word present in all attributes of the doc, I find it.

If I run a query with a word only in the file, it does not work (it works indexing only the file with post without my update tentative).

I'm not sure to understand how to update the doc keeping the index created by the post command.

I hope I'm clear enough, maybe I misunderstood the way it works...

thanks a lot

Body:
It has worked for me in this way, it can be useful for someone

from SolrClient import SolrClient
solrConect = SolrClient("http://xx.xx.xxx.xxx:8983/solr/")
doc = [{'id': 'my_id', 'count_related_like':{'set': 10}}]
solrConect.index_json("my_collection", json.dumps(doc) )
solrConect.commit("my_collection", softCommit=True)


问:
Trying to run "npm run start" in VS Code's Debug on Windows 10
Normally, I run npm run start to run my program. I am trying to use the VS Code debugger to debug my program while running it.

Here's my launch.json file:

```<code>{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch electron",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "npm",
      "args": ["run", "start"],
      //"preLaunchTask": "build:win32",
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true
    }
  ]
}
</code>```

When I run this using VS Code the error I get is: launch program '' does not exist.

This all works fine if I use node under program for my debug sessions.

Other things:

```<code>$ which npm
/c/Program Files/nodejs/npm
</code>```

I tried changing program to exactly that path but it didn't work.

答:
I think the reason is in your "program" field, which is supposed to locate the executable files. Some common values are like "program": "${workspaceFolder}/app.js"

```<code>program - executable or file to run when launching the debugger
</code>```

Body:
Normally, I run npm run start to run my program. I am trying to use the VS Code debugger to debug my program while running it.

Here's my launch.json file:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch electron",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "npm",
      "args": ["run", "start"],
      //"preLaunchTask": "build:win32",
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": true
    }
  ]
}

When I run this using VS Code the error I get is: launch program '' does not exist.

This all works fine if I use node under program for my debug sessions.

Other things:

$ which npm
/c/Program Files/nodejs/npm

I tried changing program to exactly that path but it didn't work.

Body:
I think the reason is in your "program" field, which is supposed to locate the executable files. Some common values are like "program": "${workspaceFolder}/app.js"

program - executable or file to run when launching the debugger


问:
How do you produce a random 0 or 1 with random.rand
I'm trying to produce a 0 or 1 with numpy's random.rand.

np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.

Thank you.

答:
You can use np.random.randint(low, high=None, size=None).

```<code>>>> np.random.randint(0,2,10)
array([0, 1, 1, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(2)
0
>>> np.random.randint(2)
1
</code>```

Fore more details, you can refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html

Body:
You can use np.random.randint(low, high=None, size=None).

>>> np.random.randint(0,2,10)
array([0, 1, 1, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(2)
0
>>> np.random.randint(2)
1

Fore more details, you can refer to https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html


问:
How to remove ESC characters from string in JAVA
I want to remove ESC character from string in file.
I'm reading data from file line by line and i want to remove ESC chars.
Here is sample

```<code>public static void main(String[] args) {
    String rootFolder = "D:\\sample-files";
    File folder = new File(rootFolder);
    List<File> files = new ArrayList<File>();

    if (folder.exists()) {
        files = (List<File>) FileUtils.listFiles(folder, null, true);
        for (File file : files) {
            Path path = Paths.get(file.getPath());
            try {
                List<String> lines = Files.readAllLines(path);
                for (String line : lines) {
                    line = line.replaceAll("[\\u0000-\\u001f]", "");
                    line = line.replaceAll("\\r\\n", "\n");
                    line = line.replaceAll("\\r", "\n");
                }

                Path outputPath = Paths.get(file.getParent() + "\\" + file.getName() + "_result.txt");
                Files.write(outputPath, lines);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
Here is how I've done it:</p>

```<code>import java.io.BufferedReader;;
import java.io.FileReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    /**
     * Use {@link StringBuilder} to convert a `Character` list to {@code String}.
     */
    public static String charactersToString(java.util.List<Character> chars)
    {
        StringBuilder sb = new StringBuilder(chars.size());
        for (Character c : chars) {
            sb.append(c.charValue());
        }
        return sb.toString();
    }

    /**
     * Use {@link Stream} to convert {@code String} to a list of {@code chars}.
     */
    public static java.util.List<Character> stringToCharacters(String text) {
        return text.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
    }

    public static void main(String[] args)
    {
        java.io.File file = new java.io.File("file.txt");
        java.util.List<String> content = new java.util.ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                /* Convert String to Character array so that
                 * it can be easily processed each char at a time
                 */
                java.util.List<Character> chars = stringToCharacters(line);
                /*
                 * Check if ascii value of char matches ESC
                 */
                chars.removeIf(c -> (int)c == 27);
                /*
                 * Add the processed line to a list that will later
                 * be used to write back to the same file
                 */
                content.add(charactersToString(chars));
            }
            /*
             * Write all processed lines back to the same file
             */
            java.nio.file.Files.write(file.toPath(), content);
        }
        catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I want to remove ESC character from string in file.
I'm reading data from file line by line and i want to remove ESC chars.
Here is sample

public static void main(String[] args) {
    String rootFolder = "D:\\sample-files";
    File folder = new File(rootFolder);
    List<File> files = new ArrayList<File>();

    if (folder.exists()) {
        files = (List<File>) FileUtils.listFiles(folder, null, true);
        for (File file : files) {
            Path path = Paths.get(file.getPath());
            try {
                List<String> lines = Files.readAllLines(path);
                for (String line : lines) {
                    line = line.replaceAll("[\\u0000-\\u001f]", "");
                    line = line.replaceAll("\\r\\n", "\n");
                    line = line.replaceAll("\\r", "\n");
                }

                Path outputPath = Paths.get(file.getParent() + "\\" + file.getName() + "_result.txt");
                Files.write(outputPath, lines);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Body:
Here is how I've done it:

import java.io.BufferedReader;;
import java.io.FileReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    /**
     * Use {@link StringBuilder} to convert a `Character` list to {@code String}.
     */
    public static String charactersToString(java.util.List<Character> chars)
    {
        StringBuilder sb = new StringBuilder(chars.size());
        for (Character c : chars) {
            sb.append(c.charValue());
        }
        return sb.toString();
    }

    /**
     * Use {@link Stream} to convert {@code String} to a list of {@code chars}.
     */
    public static java.util.List<Character> stringToCharacters(String text) {
        return text.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
    }

    public static void main(String[] args)
    {
        java.io.File file = new java.io.File("file.txt");
        java.util.List<String> content = new java.util.ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                /* Convert String to Character array so that
                 * it can be easily processed each char at a time
                 */
                java.util.List<Character> chars = stringToCharacters(line);
                /*
                 * Check if ascii value of char matches ESC
                 */
                chars.removeIf(c -> (int)c == 27);
                /*
                 * Add the processed line to a list that will later
                 * be used to write back to the same file
                 */
                content.add(charactersToString(chars));
            }
            /*
             * Write all processed lines back to the same file
             */
            java.nio.file.Files.write(file.toPath(), content);
        }
        catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}


问:
Problem with a try-except clause that makes sure users don't input whitespace strings
I'm trying to write a function that prompts the user to keep inputting until anything but whitespace is entered. I know I could do it with string comparison but I really want to know why this particular method isn't working.I know it's probably something quite simple but I've been staring at it for too long!

def inputSomething(prompt, errorMessage = 'invalid input - try again'):
    while True:
        value = input(prompt)
        isEmpty = value.isspace()
        try:
            isEmpty != True

        except :
            print(errorMessage)
            continue

        return value

isSomething = inputSomething('enter anything: ')
print('x', isSomething)
```

It never throws an exception or prompts the user to input again.
Thanks in advance!

答:
The except block triggers only when a line of code inside the try block raises an exception. Usually, this approach for repeated user input is used when the parsing itself fails leading to a ValueError, such as with integers for example.

In your case, the input is a string and hence there are no exceptions thrown. You only need to validate it according to your conditions. Hence, an if-else block is appropriate.

The following should work:

```<code>def inputSomething(prompt, errorMessage = 'invalid input - try again'):
    while True:
        value = input(prompt)
        if value.isspace():
            print(errorMessage)
            continue

        return value
</code>```

Body:
I'm trying to write a function that prompts the user to keep inputting until anything but whitespace is entered. I know I could do it with string comparison but I really want to know why this particular method isn't working.I know it's probably something quite simple but I've been staring at it for too long!

def inputSomething(prompt, errorMessage = 'invalid input - try again'):
    while True:
        value = input(prompt)
        isEmpty = value.isspace()
        try:
            isEmpty != True

        except :
            print(errorMessage)
            continue

        return value

isSomething = inputSomething('enter anything: ')
print('x', isSomething)

It never throws an exception or prompts the user to input again.
Thanks in advance!

Body:
The except block triggers only when a line of code inside the try block raises an exception. Usually, this approach for repeated user input is used when the parsing itself fails leading to a ValueError, such as with integers for example.

In your case, the input is a string and hence there are no exceptions thrown. You only need to validate it according to your conditions. Hence, an if-else block is appropriate.

The following should work:

def inputSomething(prompt, errorMessage = 'invalid input - try again'):
    while True:
        value = input(prompt)
        if value.isspace():
            print(errorMessage)
            continue

        return value


问:
Issue on trying to query GeoJson multipolygons in SQL Server 2016
I am trying to run a query (which I gleened from here) against GeoJson multipolygon data. It processes many of the spatial records but is stopping on a some.

I get the following error in the query messages:

Msg 6522, Level 16, State 1, Line 10

      A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":

      System.FormatException: 24142: Expected "(" at position 15. The input has ",".

      System.FormatException:

      at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeToken(Char token)     at Microsoft.SqlServer.Types.WellKnownTextReader.ParseLineStringText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseMultiPolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)

      at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)

This is my statement with some test data:

```<code>declare @CountiesGeoJson nvarchar(max) = '{"type":"FeatureCollection","features":[
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "700", "COUNTYNS": "01498555", "GEOID": "51700", "NAME": "Newport News" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.622252, 37.142146], [-76.577819, 37.187025], [-76.591432, 37.214721], [-76.565092, 37.220645], [-76.458516, 37.100661], [-76.435519, 37.094882], [-76.451274, 37.076878], [-76.442269, 37.018448], [-76.424757, 37.025107], [-76.387711304409194, 36.989671332859004], [-76.411768, 36.962847], [-76.428869, 36.969947], [-76.464471, 37.027547], [-76.518242, 37.055351], [-76.536875, 37.083942], [-76.564219, 37.077507], [-76.618252, 37.119347], [-76.622252, 37.142146]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "620", "COUNTYNS": "01498424", "GEOID": "51620", "NAME": "Franklin" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.963021, 36.704696], [-76.912221, 36.698408], [-76.909672, 36.648175], [-76.962339, 36.667515], [-76.949327, 36.67873], [-76.968027, 36.682971], [-76.963021, 36.704696]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "595", "COUNTYNS": "01498422", "GEOID": "51595", "NAME": "Emporia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.557359, 36.713166], [-77.510273, 36.718229], [-77.509246, 36.682998], [-77.556524, 36.674874], [-77.557359, 36.713166]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "670", "COUNTYNS": "01498428", "GEOID": "51670", "NAME": "Hopewell" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.334549, 37.312468], [-77.273379, 37.316116], [-77.253234, 37.295668], [-77.31081, 37.261451], [-77.328291, 37.271748], [-77.334549, 37.312468]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "510", "COUNTYNS": "01498415", "GEOID": "51510", "NAME": "Alexandria" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.140872, 38.826905], [-77.110799, 38.843446], [-77.087805, 38.827357], [-77.085609, 38.84419], [-77.044487611898006, 38.839598699716696], [-77.040372554526996, 38.785355394851003], [-77.143135, 38.805321], [-77.140872, 38.826905]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "059", "COUNTYNS": "01480119", "GEOID": "51059", "NAME": "Fairfax" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.53576, 38.847474], [-77.32828109319901, 39.057794871536501], [-77.246003, 39.024909], [-77.255703, 39.002409], [-77.234803, 38.97631], [-77.148179, 38.965002], [-77.119759, 38.934343], [-77.172276, 38.893245], [-77.194712, 38.899073], [-77.194234, 38.886146], [-77.149701, 38.87567], [-77.110799, 38.843446], [-77.140872, 38.826905], [-77.143135, 38.805321], [-77.040372554526996, 38.785355394851003], [-77.042298, 38.718515], [-77.122001, 38.685816], [-77.1302, 38.635017], [-77.204302, 38.617817], [-77.277032, 38.695026], [-77.355884, 38.725425], [-77.370878, 38.710433], [-77.442956, 38.803796], [-77.492801, 38.797821], [-77.50834, 38.841032], [-77.53576, 38.847474]], [[-77.334852, 38.853737], [-77.318689, 38.834651], [-77.27052, 38.840902], [-77.270597, 38.866075], [-77.334852, 38.853737]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "680", "COUNTYNS": "01498429", "GEOID": "51680", "NAME": "Lynchburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-79.26745, 37.44744], [-79.183302, 37.465908], [-79.120451, 37.398311], [-79.085244, 37.394743], [-79.214924, 37.33258], [-79.257188, 37.355608], [-79.231933, 37.394911], [-79.256628, 37.406573], [-79.244548, 37.419941], [-79.268727, 37.431028], [-79.26745, 37.44744]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "037", "COUNTYNS": "01492442", "GEOID": "51037", "NAME": "Charlotte" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.902227, 37.026799], [-78.824209, 37.205361], [-78.808198, 37.201852], [-78.778353, 37.228639], [-78.734351, 37.220256], [-78.681477, 37.24969], [-78.692432, 37.203673], [-78.644621, 37.194323], [-78.634927, 37.170064], [-78.583642, 37.140635], [-78.547128, 37.150431], [-78.480891, 37.085196], [-78.443644, 37.079371], [-78.493028, 36.89122], [-78.648541, 36.697909], [-78.691328, 36.741847], [-78.666145, 36.764363], [-78.682652, 36.797222], [-78.666995, 36.811822], [-78.686878, 36.824331], [-78.666125, 36.840482], [-78.671463, 36.857951], [-78.749727, 36.920065], [-78.727686, 36.937454], [-78.743891, 37.005439], [-78.756549, 37.00717], [-78.748358, 36.987057], [-78.774715, 36.980976], [-78.785452, 36.952783], [-78.817455, 36.98402], [-78.892702, 36.976694], [-78.902227, 37.026799]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "099", "COUNTYNS": "01480137", "GEOID": "51099", "NAME": "King George" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.330384, 38.334951], [-77.286201505089011, 38.347024428844499], [-77.240072, 38.331598], [-77.17934, 38.341915], [-77.138224, 38.367917], [-77.08481, 38.368297], [-77.043526, 38.400548], [-77.011827, 38.374554], [-77.030683, 38.311623], [-76.99767, 38.278047], [-77.044799, 38.260407], [-77.048482, 38.182444], [-77.073796, 38.141331], [-77.084596, 38.160231], [-77.115997, 38.149931], [-77.2143, 38.197029], [-77.254001, 38.18943], [-77.242001, 38.210729], [-77.251801, 38.229628], [-77.229757, 38.245208], [-77.275302, 38.247528], [-77.291402, 38.223729], [-77.290302, 38.238728], [-77.309419, 38.234737], [-77.345728, 38.26139], [-77.330384, 38.334951]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "161", "COUNTYNS": "01480165", "GEOID": "51161", "NAME": "Roanoke" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-80.261984, 37.340694], [-80.200161, 37.378568], [-80.147625, 37.382342], [-80.073985, 37.422305], [-79.865099, 37.328417], [-79.840367, 37.302681], [-79.858058, 37.267138], [-79.847082, 37.225468], [-79.962301, 37.137099], [-80.030562, 37.17481], [-80.088553, 37.160482], [-80.128119, 37.122912], [-80.172264, 37.108156], [-80.189835, 37.233476], [-80.25852, 37.308344], [-80.261984, 37.340694]], [[-80.088062, 37.282334], [-80.050761, 37.252635], [-80.033464, 37.26289], [-80.02883, 37.24365], [-79.998113, 37.252193], [-79.950384, 37.211274], [-79.924496, 37.224634], [-79.900048, 37.257297], [-79.909493, 37.278054], [-79.879276, 37.304047], [-79.974023, 37.335419], [-80.022226, 37.308338], [-80.033596, 37.324293], [-80.12049, 37.287053], [-80.088062, 37.282334]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "135", "COUNTYNS": "01493928", "GEOID": "51135", "NAME": "Nottoway" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.238161, 37.194822], [-78.231234, 37.29622], [-77.795926, 37.192592], [-77.805982, 37.175933], [-77.900254, 37.143885], [-77.889813, 36.988818], [-77.932749, 36.984246], [-77.968114, 36.987292], [-78.003639, 37.022756], [-78.082023, 37.011121], [-78.172207, 37.055963], [-78.170716, 37.076188], [-78.224286, 37.089685], [-78.239354, 37.120089], [-78.238161, 37.194822]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "683", "COUNTYNS": "01498430", "GEOID": "51683", "NAME": "Manassas" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.526457, 38.732466], [-77.475711, 38.781214], [-77.44751, 38.761115], [-77.451642, 38.738337], [-77.471425, 38.728152], [-77.507299, 38.740479], [-77.506167, 38.705741], [-77.526457, 38.732466]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "630", "COUNTYNS": "01498425", "GEOID": "51630", "NAME": "Fredericksburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.530283, 38.309175], [-77.506782, 38.325925], [-77.467053, 38.31866], [-77.447126, 38.284614], [-77.457837, 38.271108], [-77.492045, 38.273637], [-77.530283, 38.309175]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "610", "COUNTYNS": "01498423", "GEOID": "51610", "NAME": "Falls Church" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.194712, 38.899073], [-77.172276, 38.893245], [-77.149701, 38.87567], [-77.189719, 38.87801], [-77.194712, 38.899073]]]] } },
]}';
--DECLARE @@CountiesGeoJson nvarchar(max)
--SELECT @@CountiesGeoJson = BulkColumn
--FROM OPENROWSET
--(BULK 'C:\MapData\countiesEdited.json', SINGLE_CLOB)
--as JSON

--Insert Into [Tox].[dbo].[GeoCounties] (GEOID, GEO_NAME, FIPS_ST_CD, FIPS_CNTY_CD, RESOLUTION_ACCURACY, GEO_OBJECT)
select GEOID, GNAME, STATEFP, COUNTYFP, 10, Geo=fixed
from   openjson (@CountiesGeoJson, '$.features')
with
(
    GEOID char(5) '$.properties.GEOID',
    GNAME varchar(40) '$.properties.NAME',
    STATEFP char(2) '$.properties.STATEFP',
    COUNTYFP char(3) '$.properties.COUNTYFP',
    [type] Varchar(64) '$.geometry.type',
    [coordinates] nvarchar(max) '$.geometry.coordinates' as json
)
as GeoData
cross apply (
select
   stuff(
      (
        select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
        from openjson(GeoData.coordinates,'$[0]')
        order by cast([key] as int)
        for xml path('')
      ),1,3,'') [path]
) PolygonData
OUTER APPLY (
    SELECT  STUFF(
        (
            SELECT CONCAT(',  ', polygon)
            FROM OPENJSON(GeoData.coordinates) as Poly
            CROSS APPLY OPENJSON(Poly.value) as Shape
            CROSS APPLY (
                SELECT '(' + stuff(
                (
                    select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
                    from OPENJSON(Shape.value)
                    order by cast([key] as int)
                    for xml path('')
                ),1,3,'')+')' polygon
        ) Polygons
        for xml path('')
    ),1,3,'') multi
    WHERE LEN(Path) = 0
) MultigonData
cross apply (
    SELECT concat(upper(GeoData.[type]),'((',IsNull(NULLIF(path,''),multi),'))') WKT
) shapeDef
outer apply (
    select geography::STGeomFromText(WKT,4326).MakeValid()/*.ReorientObject()*/ as geom
) geography
outer apply (
    select CASE WHEN geom.EnvelopeAngle() > 90 THEN geom.ReorientObject() ELSE geom END as fixed
) fixes
</code>```

The query will run and produce some results but when it hits records where the NAME = 'Fairfax' and 'Roanoke', it stops with the above error.

Can anyone see the issue and know how to resolve this?

[EDIT 2019-05-31 17:35]
GeoJson Header:

```<code>{
  "type": "FeatureCollection",
  "name": "USCounty_Simplify_01",
  "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4269" } },
  "features": [
...
</code>```

答:
The failing multipolygons are those that contain holes. You can detect them by searching for ]],.

Multipolygon is collection of polygons. Each of them is collection of loops - first loop is polygon shell and other loops are holes. Each loop is collection of points.

The script tries to convert GeoJSON to WKT by unpacking these arrays, then concatenating them wrapping using WKT's ( and ), but fails to handle polygon with holes case. I suspect the bug is in Poly.value - this does not handle array case, but I'm not OPENJSON expert.

I guess it is possible to continue making this complicated SQL even more complex, and handle holes case as well, but I think it is more practical to convert GeoJSON to WKT strings using something with real GeoJSON parser and WKT formatter, e.g. ogr2ogr tool.

Body:
I am trying to run a query (which I gleened from here) against GeoJson multipolygon data. It processes many of the spatial records but is stopping on a some.

I get the following error in the query messages:

Msg 6522, Level 16, State 1, Line 10

      A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":

      System.FormatException: 24142: Expected "(" at position 15. The input has ",".

      System.FormatException:

      at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeToken(Char token)     at Microsoft.SqlServer.Types.WellKnownTextReader.ParseLineStringText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseMultiPolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)

      at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)

This is my statement with some test data:

declare @CountiesGeoJson nvarchar(max) = '{"type":"FeatureCollection","features":[
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "700", "COUNTYNS": "01498555", "GEOID": "51700", "NAME": "Newport News" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.622252, 37.142146], [-76.577819, 37.187025], [-76.591432, 37.214721], [-76.565092, 37.220645], [-76.458516, 37.100661], [-76.435519, 37.094882], [-76.451274, 37.076878], [-76.442269, 37.018448], [-76.424757, 37.025107], [-76.387711304409194, 36.989671332859004], [-76.411768, 36.962847], [-76.428869, 36.969947], [-76.464471, 37.027547], [-76.518242, 37.055351], [-76.536875, 37.083942], [-76.564219, 37.077507], [-76.618252, 37.119347], [-76.622252, 37.142146]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "620", "COUNTYNS": "01498424", "GEOID": "51620", "NAME": "Franklin" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.963021, 36.704696], [-76.912221, 36.698408], [-76.909672, 36.648175], [-76.962339, 36.667515], [-76.949327, 36.67873], [-76.968027, 36.682971], [-76.963021, 36.704696]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "595", "COUNTYNS": "01498422", "GEOID": "51595", "NAME": "Emporia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.557359, 36.713166], [-77.510273, 36.718229], [-77.509246, 36.682998], [-77.556524, 36.674874], [-77.557359, 36.713166]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "670", "COUNTYNS": "01498428", "GEOID": "51670", "NAME": "Hopewell" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.334549, 37.312468], [-77.273379, 37.316116], [-77.253234, 37.295668], [-77.31081, 37.261451], [-77.328291, 37.271748], [-77.334549, 37.312468]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "510", "COUNTYNS": "01498415", "GEOID": "51510", "NAME": "Alexandria" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.140872, 38.826905], [-77.110799, 38.843446], [-77.087805, 38.827357], [-77.085609, 38.84419], [-77.044487611898006, 38.839598699716696], [-77.040372554526996, 38.785355394851003], [-77.143135, 38.805321], [-77.140872, 38.826905]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "059", "COUNTYNS": "01480119", "GEOID": "51059", "NAME": "Fairfax" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.53576, 38.847474], [-77.32828109319901, 39.057794871536501], [-77.246003, 39.024909], [-77.255703, 39.002409], [-77.234803, 38.97631], [-77.148179, 38.965002], [-77.119759, 38.934343], [-77.172276, 38.893245], [-77.194712, 38.899073], [-77.194234, 38.886146], [-77.149701, 38.87567], [-77.110799, 38.843446], [-77.140872, 38.826905], [-77.143135, 38.805321], [-77.040372554526996, 38.785355394851003], [-77.042298, 38.718515], [-77.122001, 38.685816], [-77.1302, 38.635017], [-77.204302, 38.617817], [-77.277032, 38.695026], [-77.355884, 38.725425], [-77.370878, 38.710433], [-77.442956, 38.803796], [-77.492801, 38.797821], [-77.50834, 38.841032], [-77.53576, 38.847474]], [[-77.334852, 38.853737], [-77.318689, 38.834651], [-77.27052, 38.840902], [-77.270597, 38.866075], [-77.334852, 38.853737]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "680", "COUNTYNS": "01498429", "GEOID": "51680", "NAME": "Lynchburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-79.26745, 37.44744], [-79.183302, 37.465908], [-79.120451, 37.398311], [-79.085244, 37.394743], [-79.214924, 37.33258], [-79.257188, 37.355608], [-79.231933, 37.394911], [-79.256628, 37.406573], [-79.244548, 37.419941], [-79.268727, 37.431028], [-79.26745, 37.44744]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "037", "COUNTYNS": "01492442", "GEOID": "51037", "NAME": "Charlotte" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.902227, 37.026799], [-78.824209, 37.205361], [-78.808198, 37.201852], [-78.778353, 37.228639], [-78.734351, 37.220256], [-78.681477, 37.24969], [-78.692432, 37.203673], [-78.644621, 37.194323], [-78.634927, 37.170064], [-78.583642, 37.140635], [-78.547128, 37.150431], [-78.480891, 37.085196], [-78.443644, 37.079371], [-78.493028, 36.89122], [-78.648541, 36.697909], [-78.691328, 36.741847], [-78.666145, 36.764363], [-78.682652, 36.797222], [-78.666995, 36.811822], [-78.686878, 36.824331], [-78.666125, 36.840482], [-78.671463, 36.857951], [-78.749727, 36.920065], [-78.727686, 36.937454], [-78.743891, 37.005439], [-78.756549, 37.00717], [-78.748358, 36.987057], [-78.774715, 36.980976], [-78.785452, 36.952783], [-78.817455, 36.98402], [-78.892702, 36.976694], [-78.902227, 37.026799]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "099", "COUNTYNS": "01480137", "GEOID": "51099", "NAME": "King George" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.330384, 38.334951], [-77.286201505089011, 38.347024428844499], [-77.240072, 38.331598], [-77.17934, 38.341915], [-77.138224, 38.367917], [-77.08481, 38.368297], [-77.043526, 38.400548], [-77.011827, 38.374554], [-77.030683, 38.311623], [-76.99767, 38.278047], [-77.044799, 38.260407], [-77.048482, 38.182444], [-77.073796, 38.141331], [-77.084596, 38.160231], [-77.115997, 38.149931], [-77.2143, 38.197029], [-77.254001, 38.18943], [-77.242001, 38.210729], [-77.251801, 38.229628], [-77.229757, 38.245208], [-77.275302, 38.247528], [-77.291402, 38.223729], [-77.290302, 38.238728], [-77.309419, 38.234737], [-77.345728, 38.26139], [-77.330384, 38.334951]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "161", "COUNTYNS": "01480165", "GEOID": "51161", "NAME": "Roanoke" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-80.261984, 37.340694], [-80.200161, 37.378568], [-80.147625, 37.382342], [-80.073985, 37.422305], [-79.865099, 37.328417], [-79.840367, 37.302681], [-79.858058, 37.267138], [-79.847082, 37.225468], [-79.962301, 37.137099], [-80.030562, 37.17481], [-80.088553, 37.160482], [-80.128119, 37.122912], [-80.172264, 37.108156], [-80.189835, 37.233476], [-80.25852, 37.308344], [-80.261984, 37.340694]], [[-80.088062, 37.282334], [-80.050761, 37.252635], [-80.033464, 37.26289], [-80.02883, 37.24365], [-79.998113, 37.252193], [-79.950384, 37.211274], [-79.924496, 37.224634], [-79.900048, 37.257297], [-79.909493, 37.278054], [-79.879276, 37.304047], [-79.974023, 37.335419], [-80.022226, 37.308338], [-80.033596, 37.324293], [-80.12049, 37.287053], [-80.088062, 37.282334]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "135", "COUNTYNS": "01493928", "GEOID": "51135", "NAME": "Nottoway" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.238161, 37.194822], [-78.231234, 37.29622], [-77.795926, 37.192592], [-77.805982, 37.175933], [-77.900254, 37.143885], [-77.889813, 36.988818], [-77.932749, 36.984246], [-77.968114, 36.987292], [-78.003639, 37.022756], [-78.082023, 37.011121], [-78.172207, 37.055963], [-78.170716, 37.076188], [-78.224286, 37.089685], [-78.239354, 37.120089], [-78.238161, 37.194822]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "683", "COUNTYNS": "01498430", "GEOID": "51683", "NAME": "Manassas" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.526457, 38.732466], [-77.475711, 38.781214], [-77.44751, 38.761115], [-77.451642, 38.738337], [-77.471425, 38.728152], [-77.507299, 38.740479], [-77.506167, 38.705741], [-77.526457, 38.732466]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "630", "COUNTYNS": "01498425", "GEOID": "51630", "NAME": "Fredericksburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.530283, 38.309175], [-77.506782, 38.325925], [-77.467053, 38.31866], [-77.447126, 38.284614], [-77.457837, 38.271108], [-77.492045, 38.273637], [-77.530283, 38.309175]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "610", "COUNTYNS": "01498423", "GEOID": "51610", "NAME": "Falls Church" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.194712, 38.899073], [-77.172276, 38.893245], [-77.149701, 38.87567], [-77.189719, 38.87801], [-77.194712, 38.899073]]]] } },
]}';
--DECLARE @@CountiesGeoJson nvarchar(max)
--SELECT @@CountiesGeoJson = BulkColumn
--FROM OPENROWSET
--(BULK 'C:\MapData\countiesEdited.json', SINGLE_CLOB)
--as JSON

--Insert Into [Tox].[dbo].[GeoCounties] (GEOID, GEO_NAME, FIPS_ST_CD, FIPS_CNTY_CD, RESOLUTION_ACCURACY, GEO_OBJECT)
select GEOID, GNAME, STATEFP, COUNTYFP, 10, Geo=fixed
from   openjson (@CountiesGeoJson, '$.features')
with
(
    GEOID char(5) '$.properties.GEOID',
    GNAME varchar(40) '$.properties.NAME',
    STATEFP char(2) '$.properties.STATEFP',
    COUNTYFP char(3) '$.properties.COUNTYFP',
    [type] Varchar(64) '$.geometry.type',
    [coordinates] nvarchar(max) '$.geometry.coordinates' as json
)
as GeoData
cross apply (
select
   stuff(
      (
        select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
        from openjson(GeoData.coordinates,'$[0]')
        order by cast([key] as int)
        for xml path('')
      ),1,3,'') [path]
) PolygonData
OUTER APPLY (
    SELECT  STUFF(
        (
            SELECT CONCAT(',  ', polygon)
            FROM OPENJSON(GeoData.coordinates) as Poly
            CROSS APPLY OPENJSON(Poly.value) as Shape
            CROSS APPLY (
                SELECT '(' + stuff(
                (
                    select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
                    from OPENJSON(Shape.value)
                    order by cast([key] as int)
                    for xml path('')
                ),1,3,'')+')' polygon
        ) Polygons
        for xml path('')
    ),1,3,'') multi
    WHERE LEN(Path) = 0
) MultigonData
cross apply (
    SELECT concat(upper(GeoData.[type]),'((',IsNull(NULLIF(path,''),multi),'))') WKT
) shapeDef
outer apply (
    select geography::STGeomFromText(WKT,4326).MakeValid()/*.ReorientObject()*/ as geom
) geography
outer apply (
    select CASE WHEN geom.EnvelopeAngle() > 90 THEN geom.ReorientObject() ELSE geom END as fixed
) fixes

The query will run and produce some results but when it hits records where the NAME = 'Fairfax' and 'Roanoke', it stops with the above error.

Can anyone see the issue and know how to resolve this?

[EDIT 2019-05-31 17:35]
GeoJson Header:

{
  "type": "FeatureCollection",
  "name": "USCounty_Simplify_01",
  "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4269" } },
  "features": [
...


问:
spring security spring session，session not stored in spring session
I've  Store some session attributes in spring-security UserDetailService#loadUserByUsername(),  but it was not store in spring session,   just response a new cookie which name is JSESSIONID.    how to store it in spring session ? Is spring session filter execute after spring security filter?</p>

答:
If you want to add more additional user information for spring boot environment after authentication using 'UserDetailsService' interface, create new class implementing 'AuthenticationSuccessHandler' interface, and add user information to Httpsession.

Spring session(of boot) only store user credential id except extra information, not like Spring(not of boot)

example link(not spring boot though..): https://javapointers.com/tutorial/spring-custom-authenticationsuccesshandler-example-2/


问:
Reusing an Open Source CRM
I am looking into creating a simplified version of a CRM without having to reinvent the wheel on some of the base functionality.

Would you please recommend an open source CRM product that I could use?

NOTE: I would be interested in solutions with PHP or Java.

答:
Have you looked at SugarCRM?  It's pretty mature so it might not meet your "simplified" qualifier, but if I were in your shoes I'd probably consider starting there.  It started life as an open-source project and there is still a "community edition".

Consider, however, that I have little familiarity with CRM in specific, so I can't comment one way or another on the quality of SugarCRM.  Good luck.

Title: Reusing an Open Source CRM


问:
How to get query string on search page in shopify
I have a shopify store. I am passing new parameters on search page using query string anyone tell me how can i get this new query string on search page</p>

答:
You can't get new parameters outside the default ones using liquid. Liquid is now aware of additional query parameters.

If you really really have to take them in liquid then you will have a hacky option to capture the content_for_header argument and you can extract the arguments from there ( since there is a URL with the query params there ) with a few splits. You will need to look for the pageurl string there. But like I said this is a hacky way which should be used as a last resort.


问:
Apple / Android pay in nativeScript
what is the best way to use Apple / Android pay in nativeScript for in App purchase? Is there any plugin around? Can anyone give me a direction?</p>

答:
nativescript-purchase currently supports both android and iOS.
And it is constantly being updated.</p>

Title: Apple / Android pay in nativeScript


问:
open multiple text files and read until specific character
I would like to read several text files but they are too long so i want to stop reading them at the first '}'.

EDIT: The code below works without error but it fails to cut the text file when it encounters '}' for the first time. I would like to stop reading at the end of the second line of the sample (where there is '}')

EDIT 2: I have added readline statement in the code.

SAMPLE:

```<code>{"offset":"14758816658","bids":[["968899.79379","0.01000000","0.01000000","0","1093577338","29194","5","14758816598","1"],["968899.35295","0.02100000","0.02100000","0","1093577193","29194","5","14758816186","1"],
...["9999999.00000","0.01000000","0.01000000","0","568775590","75620","5","12301971393","1"]]}
{"offset":"14758825743","bids":[["968019.05000","0.09815250","0.09815250","0","1093580802","243454","5","14758825261","1"],["968019.00000","0.18740000","0.18740000","0","1093580826","221763","5","14758825331","1"],
</code>```

THE CODE:

```<code>        with open(fileName, 'r') as fileName:
            line = fileName.readline()
                for x in line:
                    if x == '}':
                        break
            data = pd.read_csv(fileName, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)
            print(data)
</code>```

EDIT: I run the code as below. Correct output for the print but still the entire set of data when I pd.read.csv

```<code>with open(fileName, 'r', encoding='utf-8') as fileName:
      print(re.findall(r'(\{[^\{\}]*})', fileName.readline())[0])
      data = pd.read_csv(fileName, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)
</code>```

EDIT 2: THE SOLUTION

```<code> with open(fileName, 'r', encoding='utf-8') as fileName:
            d = io.StringIO(re.findall(r'(\{[^\{\}]*})', fileName.readline())[0])
            data = pd.read_csv(d, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)
</code>```

答:
Use regex match and get the value. Below snippet will give you first <code>{.*}</code> from file. </p>

```<code>import re
with open('string.txt') as s:
    print(re.findall(r'(\{[^\{\}]*})', s.read())[0])
</code>```

Body:
I would like to read several text files but they are too long so i want to stop reading them at the first '}'.

EDIT: The code below works without error but it fails to cut the text file when it encounters '}' for the first time. I would like to stop reading at the end of the second line of the sample (where there is '}')

EDIT 2: I have added readline statement in the code.

SAMPLE:

{"offset":"14758816658","bids":[["968899.79379","0.01000000","0.01000000","0","1093577338","29194","5","14758816598","1"],["968899.35295","0.02100000","0.02100000","0","1093577193","29194","5","14758816186","1"],
...["9999999.00000","0.01000000","0.01000000","0","568775590","75620","5","12301971393","1"]]}
{"offset":"14758825743","bids":[["968019.05000","0.09815250","0.09815250","0","1093580802","243454","5","14758825261","1"],["968019.00000","0.18740000","0.18740000","0","1093580826","221763","5","14758825331","1"],

THE CODE:

        with open(fileName, 'r') as fileName:
            line = fileName.readline()
                for x in line:
                    if x == '}':
                        break
            data = pd.read_csv(fileName, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)
            print(data)

EDIT: I run the code as below. Correct output for the print but still the entire set of data when I pd.read.csv

with open(fileName, 'r', encoding='utf-8') as fileName:
      print(re.findall(r'(\{[^\{\}]*})', fileName.readline())[0])
      data = pd.read_csv(fileName, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)

EDIT 2: THE SOLUTION

 with open(fileName, 'r', encoding='utf-8') as fileName:
            d = io.StringIO(re.findall(r'(\{[^\{\}]*})', fileName.readline())[0])
            data = pd.read_csv(d, lineterminator= str(']'), low_memory= False, error_bad_lines=False, header= None)

Body:
Use regex match and get the value. Below snippet will give you first {.*} from file.

import re
with open('string.txt') as s:
    print(re.findall(r'(\{[^\{\}]*})', s.read())[0])


问:
django form: how to check out checkbox state in template
I have a form with checkboxes that works fine, but when the user submits the form with errors and my checkbox is checked I need to change div class which holds the checkbox. So I was experimenting with {{ form.mycheckbox.data }} in the template and it says False on page load. Now when user is click on a checkbox and the form has errors, it says on. So I tried:

{{ if form.mycheckbox.data == True }} doesn't work

{{ if form.mycheckbox.data != False }} doesn't work

{{ if form.mycheckbox.data == 'on' }} doesn't work

{{ if form.mycheckbox.data == on }} doesn't work

答:
While, first you should use BooleanField in your model, not the CharField.
Then, there are two accesses:

just put {{form.yourField}} in your template (preferred)

or, use {% if form.yourFiled.value %} checked {%endif%}


问:
How to create Custom UITableViewCell with dynamic number of labels
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}
</code>```

答:
if in your cell you didn't add any label in your <code>.xib</code> file.
then try this </p>

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
var x : CGFloat = 0
for subView in cell.contentView.subviews{
     if subView.isKind(of: UILabel.self){
         return cell
     }
}
</code>```

Body:
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}

Body:
if in your cell you didn't add any label in your .xib file.
then try this

let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
var x : CGFloat = 0
for subView in cell.contentView.subviews{
     if subView.isKind(of: UILabel.self){
         return cell
     }
}


问:
Two square bracket overloading
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

```<code>M1[1][2]=5;
</code>```

OR

```<code>int X;

X=M1[4][5];
</code>```

答:
there is no operator[][], you can implement operator[] to return a reference to the row/column object, in which you can implement the operator[] to return you the cell reference.

You can do something like the following to avoid all that hassle..

```<code>struct loc
{
  int x;
  int y;
};
</code>```

then in your operator[] overload, accept a loc, something like

```<code>T& operator[](loc const& cLoc)
{
 // now you have x/y you can return the object there.
}
</code>```

To call, you can simply do something like:

```<code>matrix[loc(2,3)] = 5;
</code>```

Title: Two square bracket overloading

Body:
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

M1[1][2]=5;

OR

int X;

X=M1[4][5];

Body:
there is no operator[][], you can implement operator[] to return a reference to the row/column object, in which you can implement the operator[] to return you the cell reference.

You can do something like the following to avoid all that hassle..

struct loc
{
  int x;
  int y;
};

then in your operator[] overload, accept a loc, something like

T& operator[](loc const& cLoc)
{
 // now you have x/y you can return the object there.
}

To call, you can simply do something like:

matrix[loc(2,3)] = 5;


问:
Send data to MySQL received from serial port
I have this code in python, what it does is read a data that comes from the serial port; The data is sent from one XBee and received by another XBee, the second XBee is connected to a computer port, and the data it receives is what I read, then I try to send this data to a mysql database, but I send the following error:

"MySQLdb._exceptions.ProgrammingError: %b requires a bytes-like object, or an object that implements bytes, not 'dict'"

CODE:

```<code>import serial
from xbee import XBee
import MySQLdb

serial_port = serial.Serial('COM5', 9600)
xbee = XBee(serial_port)

while True:
    try:
        value = xbee.wait_read_frame()
        sql_conn = MySQLdb.connect('localhost', 'root', 'pass', 'XBee')
        cursor = sql_conn.cursor()
        cursor.execute("INSERT INTO xbeedata (value) VALUES (%s)", (value))
        data = cursor.fetchall()
        cursor.close()
        print (xbee.wait_read_frame())

    except KeyboardInterrupt:
        break

serial_port.close()
</code>```

Regards.

答:
There are some problems with your code:

You don't need to connect to your MySQL DB each time in a loop.

Accordign to docs:

Information returned from this library is a dictionary in the following format:

```<code>{'id':str,
 'param':binary data,
 ...}
</code>```

The id field is always a human-readable name of the packet type
  received. All following fields, shown above with the key ‘param’, map
  binary data to each of the possible fields contained within the
  received data frame.

So the value is a dictionary type and you need to use the param key which is your valid data. I'm not sure what is the param in your example but you can simply put a print(value) and see the results. If you still insist on adding value to your table, you need to serialize it like a JSON string.

```<code>import serial
from xbee import XBee
import MySQLdb
import json
from pprint import pprint

serial_port = serial.Serial('COM5', 9600)
xbee = XBee(serial_port)

sql_conn = MySQLdb.connect('localhost', 'root', 'pass', 'XBee')
cursor = sql_conn.cursor()

while True:
    try:
        value = xbee.wait_read_frame()
        if value:
            pprint(value)
            # Assumed results in 'rf_data' ('param') key
            # the 'rf_data' is byte string so it is better to decode it first
            cursor.execute(
                """INSERT INTO xbeedata (value) VALUES ('%s')""" % (value['rf_data'].decode()))
            # or if you want to insert whole value
            # cursor.execute(
            #     """INSERT INTO xbeedata (value) VALUES ('%s')""" % (json.dumps(value)))
            sql_conn.commit()

    except KeyboardInterrupt:
        break

sql_conn.close()
serial_port.close()
</code>```

Body:
I have this code in python, what it does is read a data that comes from the serial port; The data is sent from one XBee and received by another XBee, the second XBee is connected to a computer port, and the data it receives is what I read, then I try to send this data to a mysql database, but I send the following error:

"MySQLdb._exceptions.ProgrammingError: %b requires a bytes-like object, or an object that implements bytes, not 'dict'"

CODE:

import serial
from xbee import XBee
import MySQLdb

serial_port = serial.Serial('COM5', 9600)
xbee = XBee(serial_port)

while True:
    try:
        value = xbee.wait_read_frame()
        sql_conn = MySQLdb.connect('localhost', 'root', 'pass', 'XBee')
        cursor = sql_conn.cursor()
        cursor.execute("INSERT INTO xbeedata (value) VALUES (%s)", (value))
        data = cursor.fetchall()
        cursor.close()
        print (xbee.wait_read_frame())

    except KeyboardInterrupt:
        break

serial_port.close()

Regards.

Body:
There are some problems with your code:

You don't need to connect to your MySQL DB each time in a loop.

Accordign to docs:

Information returned from this library is a dictionary in the following format:

{'id':str,
 'param':binary data,
 ...}

The id field is always a human-readable name of the packet type
  received. All following fields, shown above with the key ‘param’, map
  binary data to each of the possible fields contained within the
  received data frame.

So the value is a dictionary type and you need to use the param key which is your valid data. I'm not sure what is the param in your example but you can simply put a print(value) and see the results. If you still insist on adding value to your table, you need to serialize it like a JSON string.

import serial
from xbee import XBee
import MySQLdb
import json
from pprint import pprint

serial_port = serial.Serial('COM5', 9600)
xbee = XBee(serial_port)

sql_conn = MySQLdb.connect('localhost', 'root', 'pass', 'XBee')
cursor = sql_conn.cursor()

while True:
    try:
        value = xbee.wait_read_frame()
        if value:
            pprint(value)
            # Assumed results in 'rf_data' ('param') key
            # the 'rf_data' is byte string so it is better to decode it first
            cursor.execute(
                """INSERT INTO xbeedata (value) VALUES ('%s')""" % (value['rf_data'].decode()))
            # or if you want to insert whole value
            # cursor.execute(
            #     """INSERT INTO xbeedata (value) VALUES ('%s')""" % (json.dumps(value)))
            sql_conn.commit()

    except KeyboardInterrupt:
        break

sql_conn.close()
serial_port.close()


问:
sum of nested list in Python
I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :

```<code>def nested_sum(L):
    sum=0
    for i in range(len(L)):
       if (len(L[i])>1):
          sum=sum+nested_sum(L[i])
       else:
          sum=sum+L[i]
    return sum
</code>```

The above code gives following error:

object of type 'int' has no len()

I also tried len([L[i]]), still not working.

Anyone can help? It is Python 3.3

答:
A simple solution would be to use nested loops.

```<code>def nested_sum(t):

    sum=0
    for i in t:
        if isinstance(i, list):
            for j in i:
                sum +=j
        else:
            sum += i
    return sum
</code>```

Title: sum of nested list in Python

Body:
I try to sum a list of nested elements

e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30

I wrote the following code :

def nested_sum(L):
    sum=0
    for i in range(len(L)):
       if (len(L[i])>1):
          sum=sum+nested_sum(L[i])
       else:
          sum=sum+L[i]
    return sum

The above code gives following error:

object of type 'int' has no len()

I also tried len([L[i]]), still not working.

Anyone can help? It is Python 3.3

Body:
A simple solution would be to use nested loops.

def nested_sum(t):

    sum=0
    for i in t:
        if isinstance(i, list):
            for j in i:
                sum +=j
        else:
            sum += i
    return sum


问:
Jquery - add class on hover
I want when mouse goes on li jquery add a class to the element:

```<code><ul class="menu">
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
  <li>Menu Item</li>
</ul>

<script type="text/javascript">
var myMenu = $('.menu').children('li');

myMenu.on({
  mouseenter: function() { $( this ).addClass( "is_hovered" ); },
  mouseleave: function() { $( this ).removeClass( "is_hovered" ); }
});
</script>
</code>```

But I want to remove class only if mouse goes on another li, if not keep class on element.

Is this possible?

答:
This will work, when you mouse over li it will add is_hovered to li and remove from other li.

```<code>$(".menu li").mouseover(function(){
    $(".menu li").removeClass("is_hovered");
    $(this).addClass("is_hovered");
});
</code>```

Title: Jquery - add class on hover

Body:
I want when mouse goes on li jquery add a class to the element:

Menu Item

Menu Item

Menu Item

Menu Item

But I want to remove class only if mouse goes on another li, if not keep class on element.

Is this possible?

Body:
This will work, when you mouse over li it will add is_hovered to li and remove from other li.

$(".menu li").mouseover(function(){
    $(".menu li").removeClass("is_hovered");
    $(this).addClass("is_hovered");
});