问:
python re regular expression freezes processing on random text
I have troubles with using re.
There are 2 re:

```<code>re.findall(r'\w+@\w+.\w+', text)
re.findall(r'[\+0-9\-\(\)]{8,20}', text)
</code>```

I have ~10000 texts. And this regular expressions freezes python on random text while processing!

It could be 4000 or 4299 or another one.

Texts processes sequently. So I have no ideas why it could be...

Help me, please)

答:
Not enough reputation to comment, so I'll response as an answer.

What is your purpose with the regex?

Is the first for email address and the second for phone number?

The second regex matches something like +9-()+8-()...

Try your regex here: https://regex101.com/

Or you can print out evey 10th or 20th line of text to find out which text failed.

Body:
I have troubles with using re.
There are 2 re:

re.findall(r'\w+@\w+.\w+', text)
re.findall(r'[\+0-9\-\(\)]{8,20}', text)

I have ~10000 texts. And this regular expressions freezes python on random text while processing!

It could be 4000 or 4299 or another one.

Texts processes sequently. So I have no ideas why it could be...

Help me, please)


来源: stackexchange

问:
Trying to get property 'password' of non-object
I have a problem with this error code, when i intentionally failed to log in, it will pop out the error in the title above.

```<code>    if ($password == $user->password ) {
        $_SESSION['id'] = $user->u_id;
        $_SESSION['name'] = $user->u_name;

        header("Location: http://website/index/main.php");
    } else{
        echo"fail";
    }
</code>```

So what should i do? well i thought of changing echo "fail"; to header("Location: http://website/index/login.php") but that just seem plain wrong. Any suggestion?

答:
Before you get the password from the $user object check if it is NULL or not  by using isset method</p>

```<code> if(isset($user)){
 if ($password == $user->password ) {
    $_SESSION['id'] = $user->u_id;
    $_SESSION['name'] = $user->u_name;

    header("Location: http://website/index/main.php");
  } else{
    //back to login page using header
 }
 }
else
{
//back to login page using header
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with this error code, when i intentionally failed to log in, it will pop out the error in the title above.

    if ($password == $user->password ) {
        $_SESSION['id'] = $user->u_id;
        $_SESSION['name'] = $user->u_name;

        header("Location: http://website/index/main.php");
    } else{
        echo"fail";
    }

So what should i do? well i thought of changing echo "fail"; to header("Location: http://website/index/login.php") but that just seem plain wrong. Any suggestion?

Body:
Before you get the password from the $user object check if it is NULL or not  by using isset method

 if(isset($user)){
 if ($password == $user->password ) {
    $_SESSION['id'] = $user->u_id;
    $_SESSION['name'] = $user->u_name;

    header("Location: http://website/index/main.php");
  } else{
    //back to login page using header
 }
 }
else
{
//back to login page using header
}


问:
How to Integration of 4 digit pin in my app
In my Android app, I have to integrate 4 digit pin whenever user starts app if he is login.
If user is on dashboard and he close the app and when he reopen app next time app should ask for security pin. It should work on all activities.
How could I do this?</p>

答:
Wherever you are using the login authentication, save a key-value pair in SharedPreferences. For example, in LoginActivity, if all credentials are same,
use :

```<code>SharedPrefernces sp = getSharedPreferences("PreferenceFile",MODE_PRIVATE);
sp.edit().putBoolean("isLoggedIn",true).apply();
sp.edit().putBoolean("Password",1234).apply();
</code>```

And then redirect user to MainActivity/Dashboard.

Now in any activity where you want to have security pin checking, just get the text from user, and check:

```<code>SharedPrefernces sp = getSharedPreferences("PreferenceFile",MODE_PRIVATE);
sp.getBoolean("isLoggedIn",false);
String checker = sp.getBoolean("Password",0);

if( (editText.getText().toString().trim()).equals(checker) ) {
    //Do Secure Work
} else  {
    //Add warning Toast
}
</code>```

For extra checking that the activity has started because of intent or it came from background, you can have an isBack variable.

In Any Activity, use

```<code>onCreate() {
    isBack = false;
}
onStop() {
    isBack = true;
}
</code>```

Then in onStart, you can use

```<code>onStart() {
    if(isBack) {
        // Do the work which you want to do if the activity comes from background
    } else {
        // Do the work which you want to do if activity comes due to any intent
    }
    // After doing all the necessary work, remember to update isBack
    // because now the activity is in focus
    isBack = false;
}
</code>```

Body:
Wherever you are using the login authentication, save a key-value pair in SharedPreferences. For example, in LoginActivity, if all credentials are same,
use :

SharedPrefernces sp = getSharedPreferences("PreferenceFile",MODE_PRIVATE);
sp.edit().putBoolean("isLoggedIn",true).apply();
sp.edit().putBoolean("Password",1234).apply();

And then redirect user to MainActivity/Dashboard.

Now in any activity where you want to have security pin checking, just get the text from user, and check:

SharedPrefernces sp = getSharedPreferences("PreferenceFile",MODE_PRIVATE);
sp.getBoolean("isLoggedIn",false);
String checker = sp.getBoolean("Password",0);

if( (editText.getText().toString().trim()).equals(checker) ) {
    //Do Secure Work
} else  {
    //Add warning Toast
}

For extra checking that the activity has started because of intent or it came from background, you can have an isBack variable.

In Any Activity, use

onCreate() {
    isBack = false;
}
onStop() {
    isBack = true;
}

Then in onStart, you can use

onStart() {
    if(isBack) {
        // Do the work which you want to do if the activity comes from background
    } else {
        // Do the work which you want to do if activity comes due to any intent
    }
    // After doing all the necessary work, remember to update isBack
    // because now the activity is in focus
    isBack = false;
}


问:
How to find declaration for my typescript/react module?
I am very (very) new in frontend technologies, specially react and typescript.

My issue come when trying to do a simple thing that is to use a react component https://github.com/ckeditor/ckeditor5

So I went to the examples and found this:

https://github.com/ckeditor/ckeditor5-react-example/blob/master/package.json

I am trying to include the ckeditor with the ClassicEditor module

So I added this on my package.json

```<code>"@ckeditor/ckeditor5-editor-classic": "^12.0.0",
"@ckeditor/ckeditor5-essentials": "^11.0.0",
"@ckeditor/ckeditor5-paragraph": "^11.0.0",
"@ckeditor/ckeditor5-react": "^1.1.2",
</code>```

and checking the implementation here https://github.com/ckeditor/ckeditor5-react-example/blob/master/src/App.js

I need to import the module definition for typescript (I guess)

```<code>import CKEditor from '@ckeditor/ckeditor5-react';

// NOTE: We use editor from source (not a build)!
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
</code>```

So, this part has this weird note, but happen that does not work in my project (says is missing and cannot find it)

Any idea what else I could do to add it? I tried removing the /src/classiceditor part but is still missing.

I made a npm install and I am able to see the classiceditor code there with package.json and more... the /src/classiceditor folder actually exists node_modules with /@ckeditor/ckeditor5-editor-classic/src/classiceditor.js

Any idea what I'm missing?

答:
for anyone else having the same issue you also try declaring a file types/@ckeditor/index.d.ts and add the following content

```<code>declare module '@ckeditor/*' {
  const classes: any;
  export default classes;
}
</code>```

the accepted answer did not work for me when dealing with @ckeditor/ckeditor5-build-classic

Body:
I am very (very) new in frontend technologies, specially react and typescript.

My issue come when trying to do a simple thing that is to use a react component https://github.com/ckeditor/ckeditor5

So I went to the examples and found this:

https://github.com/ckeditor/ckeditor5-react-example/blob/master/package.json

I am trying to include the ckeditor with the ClassicEditor module

So I added this on my package.json

"@ckeditor/ckeditor5-editor-classic": "^12.0.0",
"@ckeditor/ckeditor5-essentials": "^11.0.0",
"@ckeditor/ckeditor5-paragraph": "^11.0.0",
"@ckeditor/ckeditor5-react": "^1.1.2",

and checking the implementation here https://github.com/ckeditor/ckeditor5-react-example/blob/master/src/App.js

I need to import the module definition for typescript (I guess)

import CKEditor from '@ckeditor/ckeditor5-react';

// NOTE: We use editor from source (not a build)!
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';

So, this part has this weird note, but happen that does not work in my project (says is missing and cannot find it)

Any idea what else I could do to add it? I tried removing the /src/classiceditor part but is still missing.

I made a npm install and I am able to see the classiceditor code there with package.json and more... the /src/classiceditor folder actually exists node_modules with /@ckeditor/ckeditor5-editor-classic/src/classiceditor.js

Any idea what I'm missing?

Body:
for anyone else having the same issue you also try declaring a file types/@ckeditor/index.d.ts and add the following content

declare module '@ckeditor/*' {
  const classes: any;
  export default classes;
}

the accepted answer did not work for me when dealing with @ckeditor/ckeditor5-build-classic


问:
Compare Two Arrays Of Objects and return a new array if value is true in Javascript
I need to compare 2 arrays

```<code>const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
]
</code>```

An if invited is true I need to return a new array.

Something like this:

```<code>const newArray = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  },
]
</code>```

Any idea how can I achieve this? Help please

答:
const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
];

const newArr = allFriends.map((friend) => {
  const found = inviteFriends.find((invited) => {
    return invited.userId === friend.userId
  });
  return {...friend, ...found};
});

console.log(newArr);```

Body:
I need to compare 2 arrays

const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
]

An if invited is true I need to return a new array.

Something like this:

const newArray = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  },
]

Any idea how can I achieve this? Help please


问:
How to link viewDidLoad when I don't have UIViewController
I'm trying to link a Mapbox example class to my IOS app. The example class implemented viewDidLoad method, so I assume I should instantiate this code inside a UIViewController file right?

But unfortunately I don't have that file. I'm using react native and I assume I should have at least AppDelegate and UIViewController files correct? But I don't have it. I only have the UIViewController instantiated in AppDelegate.m like so:

UIViewController *rootViewController = [UIViewController new];

rootViewController.view = rootView;

self.window.rootViewController = rootViewController;

Is this the place where I should "link" the example class so that the viewDidLoad will be triggered?

答:
In order to implement the viewDidLoad method you must create a subclass of UIViewController. In the AppDelegate.m file you are using a parent class, not a subclass.

Once you've created the UIViewController subclass (you could name it something like MapboxViewController) you would substitute it for the first line of code listed.

Instead of

UIViewController *rootViewController = [UIViewController new];

you'd have

MapboxViewController *rootViewController = [MapboxViewController new];

Here is a Stack Overflow that explains how to add a view controller in a ReactNative project. It's in Swift, but I think is still a good guide.

React-Native iOS - How can I navigate to a non-React-Native view (native iOS view controller) from a React-Native view with a button press?


问:
Adding boost header files gives compile time errors
When i add the header file

```<code>  #include <boost/fusion/adapted/struct/adapt_struct.hpp>
</code>```

It gives couple of errors

```<code>error C2988: unrecognizable template declaration/definition
error C2143: syntax error: missing ';' before '<'
error C2913: explicit specialization; 'boost::type_of::id2type_impl' is not a specialization of a class template
error C2059: syntax error: '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
</code>```

which point towards the line number 125 in typeof_impl.hpp file.

答: After reading  drescherjm , sehe's comments i changed some settings in the visual studio and when i changed platform Toolset from visual studio 2017 v(141) to visual studio 2015 v(140) , the program compiled sucessfully.</p>

Body:
When i add the header file

  #include <boost/fusion/adapted/struct/adapt_struct.hpp>

It gives couple of errors

error C2988: unrecognizable template declaration/definition
error C2143: syntax error: missing ';' before '<'
error C2913: explicit specialization; 'boost::type_of::id2type_impl' is not a specialization of a class template
error C2059: syntax error: '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body

which point towards the line number 125 in typeof_impl.hpp file.


答:
Use filtering to achieve that:</p>

```<code>invitedFriends = allFriends.filter(friend => friend.invited==true);
</code>```

Title: Compare Two Arrays Of Objects and return a new array if value is true in Javascript

Body:
Use filtering to achieve that:

invitedFriends = allFriends.filter(friend => friend.invited==true);


问:
problem in calculating lambda with Pandas
I need to convert the value of the 'Amount' field to dollar, based on the value of another 'Currency' field, but I don't understand why the value of the first record is repeated to me throughout the dataframe.

Here is my code:

```<code>def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: ( df_conversion_dolar_2['Amount'].apply(calculo_dolar_2)) if x=='$$' else df_conversion_dolar_2['Amount'])

df_conversion_dolar_2
</code>```

capture

I am trying in this other way, but without success:

precio_dolar = 800
def calculo_dolar_3(data):
  if data == '$$':
    valor = (df_conversion_dolar_2['Amount']*1000)/float(precio_dolar)
  else:
    valor = df_conversion_dolar_2['Amount']
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: df_conversion_dolar_2['Amount'].apply(calculo_dolar_3))

df_conversion_dolar_2```

What is it due to?

答:
I think what you're trying to do can be accomplished like so</p>

```<code>def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2.apply(lambda x: calculo_dolar_2(x['Amount']) if x['Currency']=='$$' else x['Amount'])
</code>```

Body:
I need to convert the value of the 'Amount' field to dollar, based on the value of another 'Currency' field, but I don't understand why the value of the first record is repeated to me throughout the dataframe.

Here is my code:

def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: ( df_conversion_dolar_2['Amount'].apply(calculo_dolar_2)) if x=='$$' else df_conversion_dolar_2['Amount'])

df_conversion_dolar_2

capture

I am trying in this other way, but without success:

precio_dolar = 800
def calculo_dolar_3(data):
  if data == '$$':
    valor = (df_conversion_dolar_2['Amount']*1000)/float(precio_dolar)
  else:
    valor = df_conversion_dolar_2['Amount']
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2['Currency'].apply(lambda x: df_conversion_dolar_2['Amount'].apply(calculo_dolar_3))

df_conversion_dolar_2

What is it due to?

Body:
I think what you're trying to do can be accomplished like so

def calculo_dolar_2(data):
  valor = (data*1000)/float(precio_dolar)
  return valor

df_conversion_dolar_2['ED'] = df_conversion_dolar_2.apply(lambda x: calculo_dolar_2(x['Amount']) if x['Currency']=='$$' else x['Amount'])


问:
How to update or read TextFiled inside GridLayout which is in TabView
I have below stack of components and I want to read and set value of the TextFiled:

```<code>-Rectangle
-----TabView
---------Tab
-----------Rectangle
--------------GridLayout
------------------Rectangle
--------------------TextField <--- I want to access this TextField
</code>```

I have also a case where I need to access Repeater inside the Tab:

```<code>-Rectangle
-----TabView
---------Tab
-----------Rectangle
--------------GridLayout
------------------Repeater
--------------------TextField <--- I want to access this TextField also
</code>```

I have tried to access it using:

```<code>var tab0 = myTabView.getTab(0);
tab0.children[0].text = "Some Text"; // I get Undefined Error
</code>```

I have tried to access the component using a function inside the Tab:

```<code>import QtQuick 2.0
import QtQuick.Controls 2.14 as QQC2
import QtQuick.Layouts 1.14
import QtQuick.Controls 1.4 as QQC1

QQC2.Item {

QQC1.TabView {

  QQC1.Tab {
    title: "tab1"

    function printValue ()  {
      console.log("myTextFld.txt: "+myTextFld.txt);  // <-- Getting Error myTextFld undefined.
    }

    Rectangle {
      id: tabHolderRext
      color: "blue"

      GridLayout {
        id: myGrid
        model: 7

        Repeater {
          id: herderRepeater
          model: header
          delegate: Rectangle {
            TextField {
              // I want to Access This TextField also
            }
          }
        }

        Rectangle {
          id: row0Rect
          Layout.row: 0
          Layout.column: index

          TextFiled {
            id: myTextFld
            text: modelData
          }
        }

        // Rest of the rows
    }
    }
}
}
}

</code>```

答:
Item id can be used to access the values from TextField if you have all items in same qml file. If you have different qml files then make use of alias types link to access the values.

Repeater case: The Textfield has to update the underlying modelview --> model first then we can make use of the model's data.

Here is a sample code. I have stacked all item's in the same qml file so that access by id works here.

```<code>import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480

    Item {
        anchors.fill: parent
        anchors.margins: 10

        TabView {
            anchors.fill: parent
            Tab {
                title: "TextField"

                Item {
                    anchors.fill: parent
                    Grid {
                        spacing: 20
                        anchors.fill: parent
                        anchors.margins: 10
                        Rectangle {
                            height: 40
                            width: 150
                            TextField {
                                id: inputId
                                anchors.fill: parent
                                placeholderText: "enter text"
                            }
                        }

                        Button {
                            height: 40
                            width: 150
                            text: "show txt"
                            onClicked: labelId.text = inputId.text
                        }

                        Rectangle {
                            height: 40
                            width: 150
                            Label {
                                id: labelId
                                anchors.fill: parent
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                        }
                    }
                }
            }
            Tab {
                title: "Repeater"

                Item {
                    anchors.fill: parent
                    Grid {
                        spacing: 20
                        anchors.fill: parent
                        anchors.margins: 10
                        columns: 3

                        ListModel {
                            id: fruitModel
                            ListElement { name: "Apple" }
                            ListElement { name: "Orange" }
                            ListElement { name: "Banana" }
                        }

                        Repeater {
                            width: parent.width
                            height: parent.height / 2
                            model: fruitModel
                            delegate: Rectangle {
                                height: 40
                                width: 150
                                TextField {
                                    anchors.fill: parent
                                    text: name
                                    onTextChanged: fruitModel.setProperty(index, "name", text) // update model data
                                }
                            }
                        }

                        Repeater {
                            width: parent.width
                            height: parent.height / 2
                            model: fruitModel
                            delegate: Rectangle {
                                height: 40
                                width: 150
                                Label {
                                    text: name
                                    anchors.fill: parent
                                    horizontalAlignment: Text.AlignHCenter
                                    verticalAlignment: Text.AlignVCenter
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

</code>```

Body:
I have below stack of components and I want to read and set value of the TextFiled:

-Rectangle
-----TabView
---------Tab
-----------Rectangle
--------------GridLayout
------------------Rectangle
--------------------TextField <--- I want to access this TextField

I have also a case where I need to access Repeater inside the Tab:

-Rectangle
-----TabView
---------Tab
-----------Rectangle
--------------GridLayout
------------------Repeater
--------------------TextField <--- I want to access this TextField also

I have tried to access it using:

var tab0 = myTabView.getTab(0);
tab0.children[0].text = "Some Text"; // I get Undefined Error

I have tried to access the component using a function inside the Tab:

import QtQuick 2.0
import QtQuick.Controls 2.14 as QQC2
import QtQuick.Layouts 1.14
import QtQuick.Controls 1.4 as QQC1

QQC2.Item {

QQC1.TabView {

  QQC1.Tab {
    title: "tab1"

    function printValue ()  {
      console.log("myTextFld.txt: "+myTextFld.txt);  // <-- Getting Error myTextFld undefined.
    }

    Rectangle {
      id: tabHolderRext
      color: "blue"

      GridLayout {
        id: myGrid
        model: 7

        Repeater {
          id: herderRepeater
          model: header
          delegate: Rectangle {
            TextField {
              // I want to Access This TextField also
            }
          }
        }

        Rectangle {
          id: row0Rect
          Layout.row: 0
          Layout.column: index

          TextFiled {
            id: myTextFld
            text: modelData
          }
        }

        // Rest of the rows
    }
    }
}
}
}

Body:
Item id can be used to access the values from TextField if you have all items in same qml file. If you have different qml files then make use of alias types link to access the values.

Repeater case: The Textfield has to update the underlying modelview --> model first then we can make use of the model's data.

Here is a sample code. I have stacked all item's in the same qml file so that access by id works here.

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480

    Item {
        anchors.fill: parent
        anchors.margins: 10

        TabView {
            anchors.fill: parent
            Tab {
                title: "TextField"

                Item {
                    anchors.fill: parent
                    Grid {
                        spacing: 20
                        anchors.fill: parent
                        anchors.margins: 10
                        Rectangle {
                            height: 40
                            width: 150
                            TextField {
                                id: inputId
                                anchors.fill: parent
                                placeholderText: "enter text"
                            }
                        }

                        Button {
                            height: 40
                            width: 150
                            text: "show txt"
                            onClicked: labelId.text = inputId.text
                        }

                        Rectangle {
                            height: 40
                            width: 150
                            Label {
                                id: labelId
                                anchors.fill: parent
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                        }
                    }
                }
            }
            Tab {
                title: "Repeater"

                Item {
                    anchors.fill: parent
                    Grid {
                        spacing: 20
                        anchors.fill: parent
                        anchors.margins: 10
                        columns: 3

                        ListModel {
                            id: fruitModel
                            ListElement { name: "Apple" }
                            ListElement { name: "Orange" }
                            ListElement { name: "Banana" }
                        }

                        Repeater {
                            width: parent.width
                            height: parent.height / 2
                            model: fruitModel
                            delegate: Rectangle {
                                height: 40
                                width: 150
                                TextField {
                                    anchors.fill: parent
                                    text: name
                                    onTextChanged: fruitModel.setProperty(index, "name", text) // update model data
                                }
                            }
                        }

                        Repeater {
                            width: parent.width
                            height: parent.height / 2
                            model: fruitModel
                            delegate: Rectangle {
                                height: 40
                                width: 150
                                Label {
                                    text: name
                                    anchors.fill: parent
                                    horizontalAlignment: Text.AlignHCenter
                                    verticalAlignment: Text.AlignVCenter
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


问:
Wait until a symbol provider is available
I am writing a Go adapter extension for the Test Explorer extension for Visual Studio Code. My extension uses language services from Microsoft's Go extension:

const symbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', uri)
```

However, I have an issue. When I specify extensionDependencies and activationEvents correctly (in package.json), symbols don't initially load (the command returns undefined). If I set activationEvents to * or if I delay for long enough in my activate handler, symbols load. I thought about retrying until the command returns something, but "this file has no symbols" and "there is no symbol provider for this type of document" both return undefined.

Is there a way to delay until a symbol provider has been defined for a specific file extension/language? Waiting for the Go extension to be activated is not enough. I would use GoDocumentSymbolProvider directly, but the extension doesn't export anything.

答:
It looks like it will be possible to add a delay time before your extension is activated.  See https://github.com/microsoft/vscode/issues/98083 (Add support to eventually activate an extension on startup).  And https://github.com/microsoft/vscode/issues/98990 (Delayed startup activation events).

Will be in v1.46. From v1.46 release notes onStartupFinished activation event:

We now have a new activation event, similar to the already existing *
  activation event. The new onStartupFinished activation event should
  be used when an extension wishes to be activated sometime soon after
  VS Code startup, but not as part of the startup.

However, it is just a hard-coded delay, not based on other events but may still help your situation.

There is a new activation event which looks like e.g. onStartup:1000
  or onStartup:5000. This means that the extension wants to be
  activated 1000ms or 5000ms after startup. This is very similar to *
  activation, but the extension indicates that it can wait a bit.

Body:
I am writing a Go adapter extension for the Test Explorer extension for Visual Studio Code. My extension uses language services from Microsoft's Go extension:

const symbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', uri)

However, I have an issue. When I specify extensionDependencies and activationEvents correctly (in package.json), symbols don't initially load (the command returns undefined). If I set activationEvents to * or if I delay for long enough in my activate handler, symbols load. I thought about retrying until the command returns something, but "this file has no symbols" and "there is no symbol provider for this type of document" both return undefined.

Is there a way to delay until a symbol provider has been defined for a specific file extension/language? Waiting for the Go extension to be activated is not enough. I would use GoDocumentSymbolProvider directly, but the extension doesn't export anything.


问:
Use variable as entity table name
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.</p>

```<code>using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}
</code>```

答:
you could create a function that accepts an "object" and "type" and returns an IQUeryable ?

eg:

```<code>private IQueryable GetQuery(object Table, Type t)
{
    var query = from d in ((t)Table) where d == "Yes" select d;
    return query;
}
</code>```

UNTESTED!!! so may need to do some variation on that, but something along those lines might work for you....

ContentLicense: CC BY-SA 3.0

Title: Use variable as entity table name

Body:
Is there a way to dynmaically define the table name so I do not have to do multiple calls if the table I'm accessing is different for different conditions? I don't want to have an if/else for every table I am accessing if I can use a variable name instead.

using (Entity ctx = new Entity())
{
    dbTableVal = "EntityTables";
    var query = from d in dbTableVal
                where d == "Yes"
                select d;
}

Body:
you could create a function that accepts an "object" and "type" and returns an IQUeryable ?

eg:

private IQueryable GetQuery(object Table, Type t)
{
    var query = from d in ((t)Table) where d == "Yes" select d;
    return query;
}

UNTESTED!!! so may need to do some variation on that, but something along those lines might work for you....


问:
Remove columns from dataframe where ALL values are NA
I have a data frame where some of the columns contain NA values.

How can I remove columns where all rows contain NA values?

答:
You can use Janitor package remove_empty

```<code>library(janitor)

df %>%
  remove_empty(c("rows", "cols")) #select either row or cols or both
</code>```

Also, Another dplyr approach

```<code> library(dplyr)
 df %>% select_if(~all(!is.na(.)))
</code>```

OR

```<code>df %>% select_if(colSums(!is.na(.)) == nrow(df))
</code>```

this is also useful if you want to only exclude / keep column with certain number of missing values e.g.

```<code> df %>% select_if(colSums(!is.na(.))>500)
</code>```

Body:
You can use Janitor package remove_empty

library(janitor)

df %>%
  remove_empty(c("rows", "cols")) #select either row or cols or both

Also, Another dplyr approach

 library(dplyr)
 df %>% select_if(~all(!is.na(.)))

OR

df %>% select_if(colSums(!is.na(.)) == nrow(df))

this is also useful if you want to only exclude / keep column with certain number of missing values e.g.

 df %>% select_if(colSums(!is.na(.))>500)


问:
EF 6 - Consume stored procedure and call ToListAsync()
I am trying to call a stored procedure via EF 6. Using ToList() works as expected and a list of entities is returned.  However, ToListAsync() does NOT seem to return data.  In sql Profiler, I can see the stored procedure being executed against the database.  However, the break point after the line for ToListAsync() does not get hit.  I never see data get returned.

code below

```<code>public async Task<List<MyEntityObject>> GetStoredProcedureData()        {

           List<MyEntityObject> MyEntityObjects;
           using (var dbContext = new DbContext())
           {
               var  MyEntityObjectsQry = dbContext.Database.SqlQuery<MyEntityObject>("dbo.GetStoredProcedureData");
               MyEntityObjects =await MyEntityObjectsQry.ToListAsync();
           }
           return MyEntityObjects;
       }
</code>```

答:
I figured this out.  I was not consuming the method correctly.  I was using a windows service.  Plus, I could not add async to the Main method.</p>
```<code>static void Main(string[] args)
     {
         // async cannot be added to Main
         // await  CallStoredProcedure(); will not work here
         Task<bool> task = Task.Run<bool>(async () => await CallStoredProcedure());
         var test = task.Result;
     }

</code>```
```<code>static async Task<bool> CallStoredProcedure()
    {
        var dataService = new MyDataService();
        // just call my method with await
        var details = await dataService.GetStoredProcedureData();
        Console.WriteLine("found {0} items", details.Count);
        return true;
    }
</code>```

Body:
I am trying to call a stored procedure via EF 6. Using ToList() works as expected and a list of entities is returned.  However, ToListAsync() does NOT seem to return data.  In sql Profiler, I can see the stored procedure being executed against the database.  However, the break point after the line for ToListAsync() does not get hit.  I never see data get returned.

code below

public async Task<List<MyEntityObject>> GetStoredProcedureData()        {

           List<MyEntityObject> MyEntityObjects;
           using (var dbContext = new DbContext())
           {
               var  MyEntityObjectsQry = dbContext.Database.SqlQuery<MyEntityObject>("dbo.GetStoredProcedureData");
               MyEntityObjects =await MyEntityObjectsQry.ToListAsync();
           }
           return MyEntityObjects;
       }

Body:
I figured this out.  I was not consuming the method correctly.  I was using a windows service.  Plus, I could not add async to the Main method.

static void Main(string[] args)
     {
         // async cannot be added to Main
         // await  CallStoredProcedure(); will not work here
         Task<bool> task = Task.Run<bool>(async () => await CallStoredProcedure());
         var test = task.Result;
     }

static async Task<bool> CallStoredProcedure()
    {
        var dataService = new MyDataService();
        // just call my method with await
        var details = await dataService.GetStoredProcedureData();
        Console.WriteLine("found {0} items", details.Count);
        return true;
    }


问:
How to stop aiohttp server running in a thread?
I am working on UI app (kivy) and trying to implement python AIOHTTP Server start and stop buttons.
I have found example in another post how to start aiohttp server in a thread (main thread is used by UI app).
But not sure how to stop the aiohttp server running in a thread, as loop.run_forever is a blocking method.

Thanks in advance.

Python  3.7.0
aiohttp 3.6.2
OS: Windows

Code is:

Serverthread.py

```<code>import asyncio
from aiohttp import web

def aiohttp_server():
    print("aiohttp_server runner created")

    async def say_hello(request):
        return web.Response(text='Hello, world')

    app = web.Application()
    app.add_routes([web.get('/', say_hello)])
    runner = web.AppRunner(app)
    return runner

def run_server(runner):
    print("Entering run_server")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(runner.setup())
    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())
    print("Loop run_forever")
    loop.run_forever()

def stop_server(runner):
    print("Entering stop_server")

</code>```

App, my-ui.py

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty

from serverthread import run_server, aiohttp_server
import threading

class ServerAdmin(Widget):
    active_threads = NumericProperty(0)
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),), daemon=True))

    def start_server(self):
        if self.active_threads == 0:
            print("starting server...")
            self.t.start()
            self.active_threads += 1
            print("Server thread started.")

        else:
            print("Number of active threads: ", str(self.active_threads))

    def stop_server(self):
        print("stopping server...")
        print(f"Check if thread active: {str(self.t.isAlive())}, {self.t.name}")
        pass

class MyUiApp(App):
    def build(self):
        return ServerAdmin()

if __name__ == '__main__':
    MyUiApp().run()

</code>```

答:
Share event</p>

```<code>class ServerAdmin(Widget):
    stop = ObjectProperty(asyncio.Event())
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),stop ), daemon=True))

    def stop_server(self):
        self.stop.set()

def run_server(runner, stop):
    ...
    print("Loop run_forever")
    # loop.run_forever()
    loop.run_until_complete(stop.wait())
    loop.close()
</code>```

Body:
I am working on UI app (kivy) and trying to implement python AIOHTTP Server start and stop buttons.
I have found example in another post how to start aiohttp server in a thread (main thread is used by UI app).
But not sure how to stop the aiohttp server running in a thread, as loop.run_forever is a blocking method.

Thanks in advance.

Python  3.7.0
aiohttp 3.6.2
OS: Windows

Code is:

Serverthread.py

import asyncio
from aiohttp import web

def aiohttp_server():
    print("aiohttp_server runner created")

    async def say_hello(request):
        return web.Response(text='Hello, world')

    app = web.Application()
    app.add_routes([web.get('/', say_hello)])
    runner = web.AppRunner(app)
    return runner

def run_server(runner):
    print("Entering run_server")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(runner.setup())
    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())
    print("Loop run_forever")
    loop.run_forever()

def stop_server(runner):
    print("Entering stop_server")

App, my-ui.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty

from serverthread import run_server, aiohttp_server
import threading

class ServerAdmin(Widget):
    active_threads = NumericProperty(0)
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),), daemon=True))

    def start_server(self):
        if self.active_threads == 0:
            print("starting server...")
            self.t.start()
            self.active_threads += 1
            print("Server thread started.")

        else:
            print("Number of active threads: ", str(self.active_threads))

    def stop_server(self):
        print("stopping server...")
        print(f"Check if thread active: {str(self.t.isAlive())}, {self.t.name}")
        pass

class MyUiApp(App):
    def build(self):
        return ServerAdmin()

if __name__ == '__main__':
    MyUiApp().run()

Body:
Share event

class ServerAdmin(Widget):
    stop = ObjectProperty(asyncio.Event())
    t = ObjectProperty(threading.Thread(target=run_server, args=(aiohttp_server(),stop ), daemon=True))

    def stop_server(self):
        self.stop.set()

def run_server(runner, stop):
    ...
    print("Loop run_forever")
    # loop.run_forever()
    loop.run_until_complete(stop.wait())
    loop.close()


问:
How to add additional styles to a window which is already using a style template
How to add additional styles to window style when it already using a style like in below?

```<code>    <Style x:Key="MyWindowStyle" TargetType="Window">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
    </Style>
</code>```

My main window is:

```<code><Window x:Class="Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Binding"
        mc:Ignorable="d"
        Style="{StaticResource MyWindowStyle}"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Label  Content="Test Window" />
    </StackPanel>
</Window>
</code>```

So I want to use MyWindowStyle but say I also want to add additional styles like adding the following:

```<code>        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>
</code>```

How do I do that? I can't figure out the syntax.

答:
You can define MyWindowStyle2 and use it.

```<code><Style x:Key="MyWindowStyle2" TargetType="Window" BasedOn="{StaticResource MyWindowStyle}">
    <Setter Property="BorderThickness" Value="3"/>
    <Setter Property="BorderBrush" Value="Red"/>
</Style>
</code>```

Or
here

Body:
How to add additional styles to window style when it already using a style like in below?

My main window is:

<Window x:Class="Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Binding"
        mc:Ignorable="d"
        Style="{StaticResource MyWindowStyle}"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>

    </StackPanel>
</Window>

So I want to use MyWindowStyle but say I also want to add additional styles like adding the following:

        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>

How do I do that? I can't figure out the syntax.

Body:
You can define MyWindowStyle2 and use it.

<Style x:Key="MyWindowStyle2" TargetType="Window" BasedOn="{StaticResource MyWindowStyle}">
    <Setter Property="BorderThickness" Value="3"/>
    <Setter Property="BorderBrush" Value="Red"/>
</Style>

Or
here


问:
Why wildfly17 server show 403 where jboss 6.X work perfectly in my System?
I use jboss 6.x to deploy war file (EMC.war) and jboss server work perfectly in eclipse with JRE1.8.0_241.

After changing server form jboss 6.X to wildfly 17, message always show 403 forbidden when using simple example.

I change wildfly version form 8 to 18, but http message still show 4.3 forbidden

There is my code.

My url is http://localhost:8080/EMC/

enviroment：
Eclipse
JRE 1.8.0_241
wildfly 17

Thanks!

答:
I still get error 403.

Here is project structure.

In class RestEasyServices

```<code>package com.demo.tutorials;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class RestEasyServices extends Application {
}
</code>```

In class EMCRESTService

```<code>package com.demo.tutorials;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/abc")
public class EMCRESTService extends Application{

     @GET
     @Path("/simple")
     public String getHelloWorldJSON() {
            return "{\"result\":\"" + "\"}";
       }

}
</code>```

In web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>EMC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

server.log show message doing http://localhost:8080/EMC/

```<code>2020-06-02 10:08:26,761 TRACE [org.jboss.security] (default task-1) PBOX00354: Setting security roles ThreadLocal: null
</code>```

http://localhost:8080/EMC/ get 403

What should I do to solve the bug?

Thsanks!

Body:
I still get error 403.

Here is project structure.

In class RestEasyServices

package com.demo.tutorials;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class RestEasyServices extends Application {
}

In class EMCRESTService

package com.demo.tutorials;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/abc")
public class EMCRESTService extends Application{

     @GET
     @Path("/simple")
     public String getHelloWorldJSON() {
            return "{\"result\":\"" + "\"}";
       }

}

In web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>EMC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

</web-app>

server.log show message doing http://localhost:8080/EMC/

2020-06-02 10:08:26,761 TRACE [org.jboss.security] (default task-1) PBOX00354: Setting security roles ThreadLocal: null

http://localhost:8080/EMC/ get 403

What should I do to solve the bug?

Thsanks!


问:
Extend Resource Controllers
I'm doing what I want in a certain way and I'm looking for alternatives or better ways of doing.
I'm using Resource Controllers in my application. Also I'm using softdelete in several models, so my routes are as follows:

Route::get('users/deleted', array('uses' => 'UserController@trash'));
Route::put('users/{id}/restore', array('uses' => 'UserController@restore'));
Route::resource('users', 'UserController');
```

The first route is to display objects that have been deleted.
The second allows me to restore these deleted elements.
The third maps the traditional methods (create, edit, update, etc.).

I have several controllers that work exactly the same way, I wonder if have any way to tell laravel to work with this two methods (trash and delete) by default without the two extra lines.

Is it possible? Or to give a better way that I'm doing?
(sorry for bad english)

答:
Im using route model bind.

I do this way.

<?php

namespace App\Http\Router;

use Illuminate\Support\Facades\Route;
use Illuminate\Routing\Router;

class CustomRouter extends Router
{
    public function customResource($routeName, $controllerPath, $routeBindName = null, $routeBindModel = null) {
        $routeBindName = $routeBindName ?? $routeName;

        $routeBindNameTrashed = "{$routeBindName}_trashed";

        if($routeBindModel && $routeBindName) {
            Route::model($routeBindName, $routeBindModel);
            Route::bind($routeBindNameTrashed, function($modelId) use ($routeBindModel) {
                return app($routeBindModel)->newQuery()->onlyTrashed()->findOrFail($modelId);
            });
        }

        Route::put("$routeName/{{$routeBindNameTrashed}}/restore", "{$controllerPath}@restore")->name("{$routeName}.restore");
        Route::delete("$routeName/{{$routeBindNameTrashed}}/force", "{$controllerPath}@forceDelete")->name("{$routeName}.force-delete");
        Route::resource($routeName, $controllerPath);
    }
}

```

<p>Alter bootstrap/app.php</p>

<pre class="lang-php prettyprint-override"><code>$app->singleton(
    'router',
    App\Http\Router\CustomRouter::class
);
</code>```

Then usage:

Route::customResource('projects', 'ProjectsController', 'project', \App\Models\Project::class);
```

Route:list

Title: Extend Resource Controllers

Body:
I'm doing what I want in a certain way and I'm looking for alternatives or better ways of doing.
I'm using Resource Controllers in my application. Also I'm using softdelete in several models, so my routes are as follows:

Route::get('users/deleted', array('uses' => 'UserController@trash'));
Route::put('users/{id}/restore', array('uses' => 'UserController@restore'));
Route::resource('users', 'UserController');

The first route is to display objects that have been deleted.
The second allows me to restore these deleted elements.
The third maps the traditional methods (create, edit, update, etc.).

I have several controllers that work exactly the same way, I wonder if have any way to tell laravel to work with this two methods (trash and delete) by default without the two extra lines.

Is it possible? Or to give a better way that I'm doing?
(sorry for bad english)

Body:
Im using route model bind.

I do this way.

<?php

namespace App\Http\Router;

use Illuminate\Support\Facades\Route;
use Illuminate\Routing\Router;

class CustomRouter extends Router
{
    public function customResource($routeName, $controllerPath, $routeBindName = null, $routeBindModel = null) {
        $routeBindName = $routeBindName ?? $routeName;

        $routeBindNameTrashed = "{$routeBindName}_trashed";

        if($routeBindModel && $routeBindName) {
            Route::model($routeBindName, $routeBindModel);
            Route::bind($routeBindNameTrashed, function($modelId) use ($routeBindModel) {
                return app($routeBindModel)->newQuery()->onlyTrashed()->findOrFail($modelId);
            });
        }

        Route::put("$routeName/{{$routeBindNameTrashed}}/restore", "{$controllerPath}@restore")->name("{$routeName}.restore");
        Route::delete("$routeName/{{$routeBindNameTrashed}}/force", "{$controllerPath}@forceDelete")->name("{$routeName}.force-delete");
        Route::resource($routeName, $controllerPath);
    }
}

Alter bootstrap/app.php

$app->singleton(
    'router',
    App\Http\Router\CustomRouter::class
);

Then usage:

Route::customResource('projects', 'ProjectsController', 'project', \App\Models\Project::class);

Route:list


问:
XPATH in selenium Zillow schools
Trying to create a program that web scrapes Zillow for the schools in a certain neighborhood but I am having some trouble scraping the xpath for the school information (rating, school name, and the grade)

I am having no luck grabbing the rating: 4/10 and the school name, see picture:

I have tried for the '4':
driver.find_element_by_xpath('.//div[@class="sc-1ra75gx-0 eYkapv"]/span[@class="Text-aiai24-0 egyxfz"]').text) and it fails (outputs nothing). I tried to get the name of the school, in this case Del Roble Elementary School and it also is not returning the correct output.
(driver.find_element_by_xpath('(.//div[@class="sc-1ra75gx-3 fnKRzv"]/span[@class="ds-school-name ds-standard-label notranslate"])[1]').text) and it doesnt output anything.

When I try to scrape for the grades of the particular school I use:

(driver.find_element_by_xpath("//span[@class='Text-aiai24-0 Qookr']").text)
but it returns "Estimated Monthly Income" and my guess is because it uses the same span class so how can I grab grades and not the other one.

I am trying to get the output as the following:

```<code>School: Del Roble Elementary School
Rating: 4/10
Grade: K-6
</code>```

Using mac os and firefox as my driver.
URL: https://www.zillow.com/san-jose-ca/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-121.87871932983398%2C%22east%22%3A-121.77486419677734%2C%22south%22%3A37.20517535620264%2C%22north%22%3A37.306966010798114%7D%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A33839%2C%22regionType%22%3A6%7D%5D%2C%22isMapVisible%22%3Atrue%2C%22mapZoom%22%3A13%2C%22filterState%22%3A%7B%7D%2C%22isListVisible%22%3Atrue%7D

```<code># IT WORKS
import pandas as pd
from selenium import webdriver
import time

# Open the browser and URL
h_count = 3
driver = webdriver.Firefox()
#url ="https://www.zillow.com/homes/for_sale/33839_rid/2-_beds/84000-1979000_price/X1-SSg18dep4cy1ee1000000000_1y8ew_sse/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-121.96676450598144%2C%22east%22%3A-121.75905423986816%2C%22south%22%3A37.25989406246074%2C%22north%22%3A37.36706818940328%7D%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A33839%2C%22regionType%22%3A6%7D%5D%2C%22isMapVisible%22%3Atrue%2C%22mapZoom%22%3A12%2C%22filterState%22%3A%7B%22price%22%3A%7B%22min%22%3A84000%2C%22max%22%3A1979000%7D%2C%22beds%22%3A%7B%22min%22%3A2%7D%2C%22sort%22%3A%7B%22value%22%3A%22globalrelevanceex%22%7D%7D%2C%22isListVisible%22%3Atrue%7D"
url = "https://www.zillow.com/san-jose-ca/schools/"

driver.get(url)
driver.maximize_window()
time.sleep(2)

name = driver.find_element_by_xpath('//header[@class="school-name"]/@href[1]')
#rate = driver.find_element_by_xpath('//div[@class="zsg-media-img_ext school-card-rating"]/div')
info = driver.find_element_by_xpath('//span[@class="school-fact school-grade"][1]')

print("name: " + str(name))
print("rating: " + str(rate))
print("info: " + str(info))
</code>```

答:
You should probably start here to scrape the schools of interest :

```<code>https://www.zillow.com/san-jose-ca/schools/#/san-jose-ca/schools
</code>```

The Del Roble Elementary School appears on page 8.

To scrape the name of the school, the rating of the school and the grade from the list of results, you can use the following XPath :

```<code>//header[@class="school-name"]/a
//li//div[contains(@class,"gs-rating")]
//li[@class="school-card-info-item"][1]
</code>```

The result of the last expression will need a bit of cleaning (removing the first part of "XXXX • Grades..."). Something like result.partition("• ")[2]

Or, assuming you build a list of schools from the list of results with //header[@class="school-name"]//@href, you can process each page with :

```<code>//h1
//div[@class="zsg-media-img_ext school-card-rating"]/div
//span[@class="school-fact school-grade"]
</code>```

Output for Del Roble : Del Roble, 4, Grades-K6

To be complete, you can also download directly the data in JSON format (200 schools per JSON). To build the correct request URL and assuming you've searched for "San Jose" (https://www.zillow.com/san-jose-ca/schools/) :

Look for the following element :

```<code>//div[@class="zsg-layout-width zsg-layout-top"]/div[1]
</code>```

Get the attributes @data-id (id for the city) and @data-mbr(coordinates position). For data-mbr, you have to remove the ( ).

With San Jose you'll find 33839 and -122.045672,37.147971,-121.704359,37.469538

You can build the url to fetch the JSON as follow :

```<code>https://www.zillow.com/ajax/schools.json?bb=value.of.data.mbr&sort=gs_rating&dir=desc&r=value.of.data.id
</code>```

Add &page=XX if the number of results exceeds 200 (this can be found in the following element //section[@class="school-region-about zsg-content-section"]//p).

JSON urls for San Jose :

https://www.zillow.com/ajax/schools.json?bb=-122.045672,37.147971,-121.704359,37.469538&sort=gs_rating&dir=desc&r=33839

https://www.zillow.com/ajax/schools.json?bb=-122.045672,37.147971,-121.704359,37.469538&sort=gs_rating&dir=desc&r=33839&page=2

Use import json, json.load to filter the data afterwards.

Output :

Title: XPATH in selenium Zillow schools

Body:
Trying to create a program that web scrapes Zillow for the schools in a certain neighborhood but I am having some trouble scraping the xpath for the school information (rating, school name, and the grade)

I am having no luck grabbing the rating: 4/10 and the school name, see picture:

I have tried for the '4':
driver.find_element_by_xpath('.//div[@class="sc-1ra75gx-0 eYkapv"]/span[@class="Text-aiai24-0 egyxfz"]').text) and it fails (outputs nothing). I tried to get the name of the school, in this case Del Roble Elementary School and it also is not returning the correct output.
(driver.find_element_by_xpath('(.//div[@class="sc-1ra75gx-3 fnKRzv"]/span[@class="ds-school-name ds-standard-label notranslate"])[1]').text) and it doesnt output anything.

When I try to scrape for the grades of the particular school I use:

(driver.find_element_by_xpath("//span[@class='Text-aiai24-0 Qookr']").text)
but it returns "Estimated Monthly Income" and my guess is because it uses the same span class so how can I grab grades and not the other one.

I am trying to get the output as the following:

School: Del Roble Elementary School
Rating: 4/10
Grade: K-6

Using mac os and firefox as my driver.
URL: https://www.zillow.com/san-jose-ca/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-121.87871932983398%2C%22east%22%3A-121.77486419677734%2C%22south%22%3A37.20517535620264%2C%22north%22%3A37.306966010798114%7D%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A33839%2C%22regionType%22%3A6%7D%5D%2C%22isMapVisible%22%3Atrue%2C%22mapZoom%22%3A13%2C%22filterState%22%3A%7B%7D%2C%22isListVisible%22%3Atrue%7D

# IT WORKS
import pandas as pd
from selenium import webdriver
import time

# Open the browser and URL
h_count = 3
driver = webdriver.Firefox()
#url ="https://www.zillow.com/homes/for_sale/33839_rid/2-_beds/84000-1979000_price/X1-SSg18dep4cy1ee1000000000_1y8ew_sse/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-121.96676450598144%2C%22east%22%3A-121.75905423986816%2C%22south%22%3A37.25989406246074%2C%22north%22%3A37.36706818940328%7D%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A33839%2C%22regionType%22%3A6%7D%5D%2C%22isMapVisible%22%3Atrue%2C%22mapZoom%22%3A12%2C%22filterState%22%3A%7B%22price%22%3A%7B%22min%22%3A84000%2C%22max%22%3A1979000%7D%2C%22beds%22%3A%7B%22min%22%3A2%7D%2C%22sort%22%3A%7B%22value%22%3A%22globalrelevanceex%22%7D%7D%2C%22isListVisible%22%3Atrue%7D"
url = "https://www.zillow.com/san-jose-ca/schools/"

driver.get(url)
driver.maximize_window()
time.sleep(2)

name = driver.find_element_by_xpath('//header[@class="school-name"]/@href[1]')
#rate = driver.find_element_by_xpath('//div[@class="zsg-media-img_ext school-card-rating"]/div')
info = driver.find_element_by_xpath('//span[@class="school-fact school-grade"][1]')

print("name: " + str(name))
print("rating: " + str(rate))
print("info: " + str(info))

Body:
You should probably start here to scrape the schools of interest :

https://www.zillow.com/san-jose-ca/schools/#/san-jose-ca/schools

The Del Roble Elementary School appears on page 8.

To scrape the name of the school, the rating of the school and the grade from the list of results, you can use the following XPath :

//header[@class="school-name"]/a
//li//div[contains(@class,"gs-rating")]
//li[@class="school-card-info-item"][1]

The result of the last expression will need a bit of cleaning (removing the first part of "XXXX • Grades..."). Something like result.partition("• ")[2]

Or, assuming you build a list of schools from the list of results with //header[@class="school-name"]//@href, you can process each page with :

//h1
//div[@class="zsg-media-img_ext school-card-rating"]/div
//span[@class="school-fact school-grade"]

Output for Del Roble : Del Roble, 4, Grades-K6

To be complete, you can also download directly the data in JSON format (200 schools per JSON). To build the correct request URL and assuming you've searched for "San Jose" (https://www.zillow.com/san-jose-ca/schools/) :

Look for the following element :

//div[@class="zsg-layout-width zsg-layout-top"]/div[1]

Get the attributes @data-id (id for the city) and @data-mbr(coordinates position). For data-mbr, you have to remove the ( ).

With San Jose you'll find 33839 and -122.045672,37.147971,-121.704359,37.469538

You can build the url to fetch the JSON as follow :

https://www.zillow.com/ajax/schools.json?bb=value.of.data.mbr&sort=gs_rating&dir=desc&r=value.of.data.id

Add &page=XX if the number of results exceeds 200 (this can be found in the following element //section[@class="school-region-about zsg-content-section"]//p).

JSON urls for San Jose :

https://www.zillow.com/ajax/schools.json?bb=-122.045672,37.147971,-121.704359,37.469538&sort=gs_rating&dir=desc&r=33839

https://www.zillow.com/ajax/schools.json?bb=-122.045672,37.147971,-121.704359,37.469538&sort=gs_rating&dir=desc&r=33839&page=2

Use import json, json.load to filter the data afterwards.

Output :


问:
What does it mean to check that a parameter is not null or empty nor negative?
I have an assignment where it says

The parameters must be checked to ensure they are not null or empty nor a negative value.

I am having trouble understanding what checking to ensure they are not null or empty nor negative means.

```<code>//field
private String listingNumber;

//My constructor:

public A0_Realtor(String listingNumberParam)
{
        setListingNumber(listingNumberParam);
}
</code>```

Setter that compiles but doesn't work? if a create a default constructor and check the value, I find that the value is null and doesn't print out invalid value

```<code>//Getter not sure if this does anything

public String getListingNumber(){
        return listingNumber;
}

//Setter

public void setListingNumber(String newListingNumber){

        if( newListingNumber != null || newListingNumber.isEmpty()){
            System.out.println("Invalid value");

        } else {
            listingNumber = newListingNumber;

       }
</code>```

//something that prints asking price. I suspect I am just getting null because of the"void" i typted?

```<code>public void printDetails (){
        System.out.println("MLS Number: "+ listingNumber);
    }
</code>```

My output :

MLS Number: null

答:
For a start you seem to have messed up your code by having the method setListingNumber inside itself.  I am guessing this is just a posting error.

But the problem is with this code

```<code>if( newListingNumber != null && newListingNumber.isEmpty())
</code>```

It is not possible for the value to be null and empty.  You need to change to or

```<code>if( newListingNumber != null || newListingNumber.isEmpty())
</code>```

edit

Also, you code does not show, but I am assuming that you do have a field called listingNumber

Body:
I have an assignment where it says

The parameters must be checked to ensure they are not null or empty nor a negative value.

I am having trouble understanding what checking to ensure they are not null or empty nor negative means.

//field
private String listingNumber;

//My constructor:

public A0_Realtor(String listingNumberParam)
{
        setListingNumber(listingNumberParam);
}

Setter that compiles but doesn't work? if a create a default constructor and check the value, I find that the value is null and doesn't print out invalid value

//Getter not sure if this does anything

public String getListingNumber(){
        return listingNumber;
}

//Setter

public void setListingNumber(String newListingNumber){

        if( newListingNumber != null || newListingNumber.isEmpty()){
            System.out.println("Invalid value");

        } else {
            listingNumber = newListingNumber;

       }

//something that prints asking price. I suspect I am just getting null because of the"void" i typted?

public void printDetails (){
        System.out.println("MLS Number: "+ listingNumber);
    }

My output :

MLS Number: null

Body:
For a start you seem to have messed up your code by having the method setListingNumber inside itself.  I am guessing this is just a posting error.

But the problem is with this code

if( newListingNumber != null && newListingNumber.isEmpty())

It is not possible for the value to be null and empty.  You need to change to or

if( newListingNumber != null || newListingNumber.isEmpty())

edit

Also, you code does not show, but I am assuming that you do have a field called listingNumber


问:
Taking data out of JSONP
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

```<code>jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })
</code>```

At clientside, I have the following script:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});
</code>```

How do I write some of the jsonp content to the screen, i.e.

```<code>channel title: title goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />
</code>```

instead of alerting "success"?

答:
You could use the jQuery tmpl plugin, here is an example:

```<code>var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

// Compile the markup as a named template
$.template( "movieTemplate", markup );

$.ajax({
  dataType: "jsonp",
  url: moviesServiceUrl,
  jsonp: "$callback",
  success: showMovies
});

// Within the callback, use .tmpl() to render the data.
function showMovies( data ) {
  // Render the template with the "movies" data and insert
  // the rendered HTML under the 'movieList' element
  $.tmpl( "movieTemplate", data )
    .appendTo( "#movieList" );
}
</code>```

See: http://api.jquery.com/jquery.tmpl/

Title: Taking data out of JSONP

Body:
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })

At clientside, I have the following script:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});

How do I write some of the jsonp content to the screen, i.e.

channel title: title goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

instead of alerting "success"?

Body:
You could use the jQuery tmpl plugin, here is an example:

var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

// Compile the markup as a named template
$.template( "movieTemplate", markup );

$.ajax({
  dataType: "jsonp",
  url: moviesServiceUrl,
  jsonp: "$callback",
  success: showMovies
});

// Within the callback, use .tmpl() to render the data.
function showMovies( data ) {
  // Render the template with the "movies" data and insert
  // the rendered HTML under the 'movieList' element
  $.tmpl( "movieTemplate", data )
    .appendTo( "#movieList" );
}

See: http://api.jquery.com/jquery.tmpl/


问:
how can I get the row number of the last used cell in a given range
Thanks again. I have this code again, I am trying to get the row number of the last used cell. the code doesn't work properly whenever there is a space in between the data in the the specified range. I just stops at the first row.

```<code>Sub MyCode()
ActiveSheet.Range("A9:A27").End(xlDown).Select
MsgBox ActiveCell.Row

End Sub
</code>```

The issue i have with this code is that  in the range A9:A27 if there is an empty row somewhere at A18 it stops there and gives the Row as 18 without even going down to A27

答:
Here is the corrected code.

```<code>Sub MyCode()

    Dim Rng As Range

    With ActiveSheet
        Set Rng =  .Cells(.Rows.Count, "A").End(xlUp)
        MsgBox Rng.Row
    End With
End Sub
</code>```

To understand this code you need to know the syntax for defining a cell.

Set MyCell = Cells([Row number], [Column number or ID])

In the above code .Rows.Count is a large number (1048576 to be exact). .Cells(.Rows.Count, "A") defines the cell A1048576. Now, from there you look for the "End" going "xlUp" and arrive at the last used cell in the column.

You would use exactly the same method to find the last used cell horizontally, like Cells(2, Columns.Count).End(xlToLeft). Here the sheet isn't specified and therefore the ActiveSheet by default.

Observe the double reference to ActiveSheet in .Cells(.Rows.Count, "A") as indicated by the leading periods. Both the Rows.Count and the cell itself must be in the same sheet.

Since the code explained here defines a cell, and since a range is defined by its first and last cells, you can define a range in column A as shown below.

```<code>Sub MyCode2()

    Dim Rng As Range

    With ActiveSheet
        Set Rng =  .Range(.Cells(30, 1),  .Cells(.Rows.Count, "A").End(xlUp))
    End With
    MsgBox Rng.Address(0, 0)
End Sub
</code>```

Body:
Thanks again. I have this code again, I am trying to get the row number of the last used cell. the code doesn't work properly whenever there is a space in between the data in the the specified range. I just stops at the first row.

Sub MyCode()
ActiveSheet.Range("A9:A27").End(xlDown).Select
MsgBox ActiveCell.Row

End Sub

The issue i have with this code is that  in the range A9:A27 if there is an empty row somewhere at A18 it stops there and gives the Row as 18 without even going down to A27

Body:
Here is the corrected code.

Sub MyCode()

    Dim Rng As Range

    With ActiveSheet
        Set Rng =  .Cells(.Rows.Count, "A").End(xlUp)
        MsgBox Rng.Row
    End With
End Sub

To understand this code you need to know the syntax for defining a cell.

Set MyCell = Cells([Row number], [Column number or ID])

In the above code .Rows.Count is a large number (1048576 to be exact). .Cells(.Rows.Count, "A") defines the cell A1048576. Now, from there you look for the "End" going "xlUp" and arrive at the last used cell in the column.

You would use exactly the same method to find the last used cell horizontally, like Cells(2, Columns.Count).End(xlToLeft). Here the sheet isn't specified and therefore the ActiveSheet by default.

Observe the double reference to ActiveSheet in .Cells(.Rows.Count, "A") as indicated by the leading periods. Both the Rows.Count and the cell itself must be in the same sheet.

Since the code explained here defines a cell, and since a range is defined by its first and last cells, you can define a range in column A as shown below.

Sub MyCode2()

    Dim Rng As Range

    With ActiveSheet
        Set Rng =  .Range(.Cells(30, 1),  .Cells(.Rows.Count, "A").End(xlUp))
    End With
    MsgBox Rng.Address(0, 0)
End Sub


问:
How can I group the number of values into columns based on month in sql
I have a data set like

```<code>Code Date
123  21-Jan-2000
234  23-Feb-1999
123  19-Jan-2001
</code>```

and I would like to query the table to display the data like this:

```<code>Code Total (All months) Jan Feb ... Dec
123    2                 1   1
234    1                 0   1
</code>```

I really have no idea how to start this. Any hints or help is greatly appreciated.

答:
We can try a pivot query:

```<code>SELECT
    Code,
    COUNT(Date) AS "Total (All months)",
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 1  THEN 1 END) AS Jan,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 2  THEN 1 END) AS Feb,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 3  THEN 1 END) AS Mar,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 4  THEN 1 END) AS Apr,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 5  THEN 1 END) AS May,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 6  THEN 1 END) AS Jun,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 7  THEN 1 END) AS Jul,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 8  THEN 1 END) AS Aug,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 9  THEN 1 END) AS Sep,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 10 THEN 1 END) AS Oct,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 11 THEN 1 END) AS Nov,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 12 THEN 1 END) AS Dec
FROM yourTable
GROUP BY
    Code
ORDER BY
    Code;
</code>```

Note that the above explicit pivot syntax can often outperform the counterpart which uses the PIVOT operator.

Body:
I have a data set like

Code Date
123  21-Jan-2000
234  23-Feb-1999
123  19-Jan-2001

and I would like to query the table to display the data like this:

Code Total (All months) Jan Feb ... Dec
123    2                 1   1
234    1                 0   1

I really have no idea how to start this. Any hints or help is greatly appreciated.

Body:
We can try a pivot query:

SELECT
    Code,
    COUNT(Date) AS "Total (All months)",
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 1  THEN 1 END) AS Jan,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 2  THEN 1 END) AS Feb,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 3  THEN 1 END) AS Mar,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 4  THEN 1 END) AS Apr,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 5  THEN 1 END) AS May,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 6  THEN 1 END) AS Jun,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 7  THEN 1 END) AS Jul,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 8  THEN 1 END) AS Aug,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 9  THEN 1 END) AS Sep,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 10 THEN 1 END) AS Oct,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 11 THEN 1 END) AS Nov,
    COUNT(CASE WHEN EXTRACT(MONTH FROM Date) = 12 THEN 1 END) AS Dec
FROM yourTable
GROUP BY
    Code
ORDER BY
    Code;

Note that the above explicit pivot syntax can often outperform the counterpart which uses the PIVOT operator.


问:
Twilio Receive Fax, Body is Empty
I'm trying to get started with Twilio's Programmable Fax API and I have completed their getting started guide. However, when I receive the fax, I log the request body to the console. However, the body is just an empty object.
I'm not sure what is going wrong.

```<code>const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Parse any incoming POST parameters
app.use(bodyParser.json({ extended: false }));

// Define a handler for when the fax is initially sent
app.post('/fax/sent', (req, res) => {
  // Let's manually build some TwiML. We can choose to receive the
  // fax with <Receive>, or reject with <Reject>.
  console.log(req.body);

  const twiml = `
  <Response>
    <Receive action="/fax/received" mediaType="application/pdf" storeMedia="true"/>
  </Response>
  `;

  // Send Fax twiml response
  res.type('text/xml');
  res.send(twiml);
});

// Define a handler for when the fax is finished sending to us - if successful,
// We will have a URL to the contents of the fax at this point
app.post('/fax/received', (req, res) => {
  // log the URL of the PDF received in the fax
  console.log(req.body);
  // Respond with empty 200/OK to Twilio
  res.status(200);
  res.send(req.body);
});

// Start the web server
http.createServer(app).listen(3000, () => {
  console.log('Express server listening on port 3000');
});
</code>```

And here is what I get back in the console. You can see the empty object that is logged...

```<code>Express server listening on port 3000
{}
</code>```

UPDATE:
I changed the body parser middleware to use urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
And I get the object but I don't see a media url...

答:
With later versions of Express, 4.16.0 - Release date: 2017-09-28, you don't need to require body-parser.</p>

```<code>// Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
</code>```

Title: Twilio Receive Fax, Body is Empty

Body:
I'm trying to get started with Twilio's Programmable Fax API and I have completed their getting started guide. However, when I receive the fax, I log the request body to the console. However, the body is just an empty object.
I'm not sure what is going wrong.

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Parse any incoming POST parameters
app.use(bodyParser.json({ extended: false }));

// Define a handler for when the fax is initially sent
app.post('/fax/sent', (req, res) => {
  // Let's manually build some TwiML. We can choose to receive the
  // fax with <Receive>, or reject with <Reject>.
  console.log(req.body);

  const twiml = `
  <Response>
    <Receive action="/fax/received" mediaType="application/pdf" storeMedia="true"/>
  </Response>
  `;

  // Send Fax twiml response
  res.type('text/xml');
  res.send(twiml);
});

// Define a handler for when the fax is finished sending to us - if successful,
// We will have a URL to the contents of the fax at this point
app.post('/fax/received', (req, res) => {
  // log the URL of the PDF received in the fax
  console.log(req.body);
  // Respond with empty 200/OK to Twilio
  res.status(200);
  res.send(req.body);
});

// Start the web server
http.createServer(app).listen(3000, () => {
  console.log('Express server listening on port 3000');
});

And here is what I get back in the console. You can see the empty object that is logged...

Express server listening on port 3000
{}

UPDATE:
I changed the body parser middleware to use urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
And I get the object but I don't see a media url...

Body:
With later versions of Express, 4.16.0 - Release date: 2017-09-28, you don't need to require body-parser.

// Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


问:
How does tflite fuses Relu into conv layers?
When converting TF model to tflite model (or in other words - quantize a model using "post-training quantization"), the Relu layers disappears from the graph. This is explained in the documentation: "operations that can be simply removed from the graph (tf.identity), replaced by tensors (tf.placeholder), or fused into more complex operations (tf.nn.bias_add)."

My question is - how can a Relu layer be fused into a prior layer? (What is the math beyond this "fusion"? Is this a specific procedure to quantized models, or this can be done also in the original floating-point model?)

答:
For the Relu (or activation functions) in TFLite, the fusion doesn't really have some math behind it, but more because the Conv kernel support doing the activation while computing the Convolution.
So, instead of building a tensor of X elements as output from Conv and then pass it as input to the following Relu layer which just iterates over to compute it, you can just clamp the values directly during convolution.
So, because the TFLite kernel supports this we can simplify the graph during conversion and fuse the Activation layer with the conv and set the FusedActivationFunction type in the ConvParams to which activation should happen during convolution.
This is not specific to quantized model, TFLite float Conv kernels also does this.
Here is an example where the clamping values set before the GEMM
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/kernels/internal/optimized/optimized_ops.h#L1338

Or in the reference kernel
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/kernels/internal/reference/conv.h#L91

For bias_add disappearing, the converter fuse the bias_add and conv and set the bias param in the Op (that's in case the value to add is constant), so the Kernel can add the bias value during convolution computation
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/kernels/internal/reference/conv.h#L89

For cases like Mul, the converter fuses the mul with Conv if the multiplier is some constant

Mul (Const_A, Conv(Input, Filter), bias)

Conv(Input, (Filter * Const_A), (bias * Const_A))

Assuming that Const_A and Filter are broadcastable types

This happens during conversion
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/mlir/lite/transforms/optimize_patterns.td#L118

Hope that helps.


问:
IntelliJ + Maven Shade: A JNI error has occurred, please check your installation and try again
In IntelliJ I'm using Maven to build a shaded jar of my project. I'm brand new to Maven and am probably doing something wrong despite my best efforts.

When I attempt to run the jar, I get the following error:

A JNI error has occurred, please check your installation and try again

I've checked my java version and it should be running off JDK14

```<code>>java -version
openjdk version "14.0.1" 2020-04-14
OpenJDK Runtime Environment (build 14.0.1+7)
OpenJDK 64-Bit Server VM (build 14.0.1+7, mixed mode, sharing)

>javac -version
javac 14.0.1
</code>```

I am not sure where I'm going wrong. Any help would be greatly appreciated. If you need any information that I haven't provided, please ask. As I'm new to Maven, I don't know what I should be sharing and what's pointless to share.

Additionally, would there be anyway to distribute this without each user having to upgrade to Java 11?

Here's my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.thenorsepantheon</groupId>
    <artifactId>wowslineupbuilder</artifactId>
    <name>WoWs Lineup Builder</name>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.2-jre</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.thenorsepantheon.wowslineupbuilder.WoWsLineupBuilder</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

答:
This error possibly occurs if you have 2 versions of Java available in your system. When you try to run your application, it picks the different version and fail. I want you to first of all check your global system variables and JDK configured with intellij is same.

Then you have do ...

Right-click on the main method class, Click on "Run As", Click on "Java Application". The keyboard shortcut is: Shift+Alt+X J (while holding Shift and Alt, press X; then release Shift and Alt and press J).

Body:
In IntelliJ I'm using Maven to build a shaded jar of my project. I'm brand new to Maven and am probably doing something wrong despite my best efforts.

When I attempt to run the jar, I get the following error:

A JNI error has occurred, please check your installation and try again

I've checked my java version and it should be running off JDK14

>java -version
openjdk version "14.0.1" 2020-04-14
OpenJDK Runtime Environment (build 14.0.1+7)
OpenJDK 64-Bit Server VM (build 14.0.1+7, mixed mode, sharing)

>javac -version
javac 14.0.1

I am not sure where I'm going wrong. Any help would be greatly appreciated. If you need any information that I haven't provided, please ask. As I'm new to Maven, I don't know what I should be sharing and what's pointless to share.

Additionally, would there be anyway to distribute this without each user having to upgrade to Java 11?

Here's my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.thenorsepantheon</groupId>
    <artifactId>wowslineupbuilder</artifactId>
    <name>WoWs Lineup Builder</name>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.2-jre</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.thenorsepantheon.wowslineupbuilder.WoWsLineupBuilder</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


问:
zip a list with space delimited into tuple
I have a dataframe df with a column called columnList as str.

```<code>"1 2,7 8,10 7"
</code>```

Then I converted them to a list as shown :

```<code>[1 2,7 8,10 7]
</code>```

I want to convert the value inside list to tuple :

```<code>[(1,2),(7,8),(10,7)]
</code>```

Current code :

```<code>temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)
</code>```

I'm getting empty list.

df looks like this :

```<code>column1    columnList
  YY      1 2,7 8,10 7
</code>```

Name: df, dtype: object

答:
You could map the characters to ints after splitting them, then convert the map object to a tuple:</p>

```<code>temp = df['columnList'].str.split(',')
result = [tuple(map(int, num.split())) for num in temp]
print(result)
# [(1, 2), (7, 8), (10, 7)]
</code>```

Body:
I have a dataframe df with a column called columnList as str.

"1 2,7 8,10 7"

Then I converted them to a list as shown :

[1 2,7 8,10 7]

I want to convert the value inside list to tuple :

[(1,2),(7,8),(10,7)]

Current code :

temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)

I'm getting empty list.

df looks like this :

column1    columnList
  YY      1 2,7 8,10 7

Name: df, dtype: object

Body:
You could map the characters to ints after splitting them, then convert the map object to a tuple:

temp = df['columnList'].str.split(',')
result = [tuple(map(int, num.split())) for num in temp]
print(result)
# [(1, 2), (7, 8), (10, 7)]


问:
Python import error: "encondings" on debian 10
So I'm running debian 10, and using python 3.7 (which I built from source). For some reason I can no longer use the CLI interpreter, and whenever I try to execute anything that relies on Python, it returns the following error:

```<code>Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f41b0784740 (most recent call first):
Aborted
</code>```

However, when I run the exact same command (either for the interpreter or when running a different python application) using sudo, it works perfectly fine. It feels like the supporting python 3.7 modules are not accessible  by the current user. But I'm not sure how to proceed in order to fix it.

答: Okay, so I found a way around this. I updated my python alias to point to python3.7 instead of python3. I am still, however, not sure if this is a solution, or a workaround. But it works now.

Body:
So I'm running debian 10, and using python 3.7 (which I built from source). For some reason I can no longer use the CLI interpreter, and whenever I try to execute anything that relies on Python, it returns the following error:

Fatal Python error: initfsencoding: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f41b0784740 (most recent call first):
Aborted

However, when I run the exact same command (either for the interpreter or when running a different python application) using sudo, it works perfectly fine. It feels like the supporting python 3.7 modules are not accessible  by the current user. But I'm not sure how to proceed in order to fix it.