问:
Not able to style the suggested actions container with limited height and overflow hidden and scrollable
I'm using these style for suggested actions. When the number of suggested actions are more, i want the suggested actions to be in a container with fixed height and overflow hidden with scrollable.
It looks like there are no style options to do the currently. Could you please check if this can done?

```<code>const styleOptions = {
  suggestedActionBackground: 'White',
  suggestedActionBorder: 0,
  suggestedActionBorderRadius: 4,
  suggestedActionBorderStyle: 'solid',
  suggestedActionBorderWidth: 1,
  suggestedActionHeight: 32,
  suggestedActionLayout: 'stacked', // either "carousel" or "stacked"
};
</code>```

enter image description here

答:
This is achievable thru use of CSS, Web Chat's store, and an event listener. A couple things to note, however.

One, this requires manipulating the DOM directly. Generally, this is frowned upon in a React environment. Whether you are using the React version of Web Chat or not, Web Chat is built upon React. Because of this, components may change in the future which could break this setup. Please bare this in mind.

Two, the example below is a simple setup. You will need to adjust it to meet your needs. For instance, you may need to further isolate certain buttons or specific suggested actions as they arrive.

First, we setup our CSS. I have two classes. hideSuggestedActionsContainer is used to, initially, hide any suggested actions. If we don't set this immediately, then the CSS changes made to suggested actions will be momentarily visible to the user as they are rendered. suggestedActionContainer sets the container styling, including enabling (but hiding) scrolling in the container.

.hideSuggestedActionContainer {
  display: none;
}

.suggestedActionContainer {
  background: white;
  width: 300px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  overflow-y: scroll;
  -ms-overflow-style: none;
}

.suggestedActionContainer::-webkit-scrollbar {
  display: none;
}
```

<p>In Web Chat, we utilize the <code>store</code> to manage what actions we take and when. The <code>store</code> is passed in as a parameter into Web Chat.</p>

<p>When Web Chat first connects (<code>DIRECT_LINE/CONNECT_FULFILLED</code>), we assign the <code>hideSuggestedActionContainer</code> class to the suggested actions DIV wrapper.</p>

<p>As the suggested action arrives (<code>WEB_CHAT/SET_SUGGESTED_ACTIONS</code>), we remove the <code>hideSuggestedActionContainer</code> class and assign the <code>suggestedActionContainer</code> class allowing the suggested action to be viewed.</p>

<p>At the same time, we monitor the incoming activities (<code>DIRECT_LINE/INCOMING_ACTIVITY</code>) looking for the associated HTML element that houses the suggested action. As Web Chat only allows for one suggested action to be displayed at a time, this <em>should</em> be the first object in the <code>[role=status]</code> array (again, things could change in the future). From that array, we collect the various suggested action buttons and, when one is clicked, we dispatch an event.</p>

<pre class="lang-js prettyprint-override"><code>const store = window.WebChat.createStore( {}, ({dispatch}) => next => action => {
  if ( action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    setTimeout( () => {
      let actions = document.querySelectorAll( '[role=status]' );
      let suggestedAction = actions[ 0 ];
      suggestedAction.classList.add( 'hideSuggestedActionContainer' );
    }, 20 )
  }

  if ( action.type === 'WEB_CHAT/SET_SUGGESTED_ACTIONS' ) {
    const { suggestedActions } = action.payload;
    if ( suggestedActions.length > 0 ) {
      setTimeout( () => {
        let actions = document.querySelectorAll( '[role=status]' );
        let suggestedAction = actions[ 0 ];
        suggestedAction.classList.remove('hideSuggestedActionContainer');
        suggestedAction.classList.add( 'suggestedActionContainer' );
      }, 20 )
    }
  }

  if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
    const { activity } = action.payload;
    if (activity.type === 'message') {
      const actions = document.querySelectorAll( '[role=status]' );
      const buttons = actions[0].querySelectorAll('button');
      buttons.forEach( button => {
        button.onclick = function() {
          const buttonClick = new Event('buttonClick');
          window.dispatchEvent( buttonClick )
        };
      } )
    }
  }

  next(action);
} );

[ ... ]

window.WebChat.renderWebChat(
  {
    directLine: window.WebChat.createDirectLine( {
      token: token
    } ),
    store: store,
    styleOptions: styleOptions
  },
  document.getElementById( 'webchat' )
);
</code>```

Below the Web Chat renderer, we place our event listener. As a suggested action button is clicked, we remove the suggestedActionContainer class and re-assign the hideSuggestedActionContainer class.

const buttonClickEvent = ( function () {
  window.addEventListener( 'buttonClick', () => {
    let actions = document.querySelectorAll( '[role=status]' );
    let suggestedAction = actions[ 0 ];
    suggestedAction.classList.remove( 'suggestedActionContainer' );
    suggestedAction.classList.add( 'hideSuggestedActionContainer' );
  } );
} )()
```

A note about the setTimeout() functions used in the store. The store processes every activity as it arrives before displaying it. Because of this, a slight delay needs to be applied to the changes we are pushing to the DOM. Without setTimeout(), the page tries to render our changes before the store is able to display the activity's associated HTML. I set the time outs to 20 milliseconds, but you may find you will need to adjust this. I have found that if I set the time out to too low a number then the changes occur before the activity is rendered. If it's too long (300+ ms or thereabouts), then the changes become visible to the user.

Hope of help!

Body:
I'm using these style for suggested actions. When the number of suggested actions are more, i want the suggested actions to be in a container with fixed height and overflow hidden with scrollable.
It looks like there are no style options to do the currently. Could you please check if this can done?

const styleOptions = {
  suggestedActionBackground: 'White',
  suggestedActionBorder: 0,
  suggestedActionBorderRadius: 4,
  suggestedActionBorderStyle: 'solid',
  suggestedActionBorderWidth: 1,
  suggestedActionHeight: 32,
  suggestedActionLayout: 'stacked', // either "carousel" or "stacked"
};

enter image description here

Body:
This is achievable thru use of CSS, Web Chat's store, and an event listener. A couple things to note, however.

One, this requires manipulating the DOM directly. Generally, this is frowned upon in a React environment. Whether you are using the React version of Web Chat or not, Web Chat is built upon React. Because of this, components may change in the future which could break this setup. Please bare this in mind.

Two, the example below is a simple setup. You will need to adjust it to meet your needs. For instance, you may need to further isolate certain buttons or specific suggested actions as they arrive.

First, we setup our CSS. I have two classes. hideSuggestedActionsContainer is used to, initially, hide any suggested actions. If we don't set this immediately, then the CSS changes made to suggested actions will be momentarily visible to the user as they are rendered. suggestedActionContainer sets the container styling, including enabling (but hiding) scrolling in the container.

.hideSuggestedActionContainer {
  display: none;
}

.suggestedActionContainer {
  background: white;
  width: 300px;
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  overflow-y: scroll;
  -ms-overflow-style: none;
}

.suggestedActionContainer::-webkit-scrollbar {
  display: none;
}

In Web Chat, we utilize the store to manage what actions we take and when. The store is passed in as a parameter into Web Chat.

When Web Chat first connects (DIRECT_LINE/CONNECT_FULFILLED), we assign the hideSuggestedActionContainer class to the suggested actions DIV wrapper.

As the suggested action arrives (WEB_CHAT/SET_SUGGESTED_ACTIONS), we remove the hideSuggestedActionContainer class and assign the suggestedActionContainer class allowing the suggested action to be viewed.

At the same time, we monitor the incoming activities (DIRECT_LINE/INCOMING_ACTIVITY) looking for the associated HTML element that houses the suggested action. As Web Chat only allows for one suggested action to be displayed at a time, this should be the first object in the [role=status] array (again, things could change in the future). From that array, we collect the various suggested action buttons and, when one is clicked, we dispatch an event.

const store = window.WebChat.createStore( {}, ({dispatch}) => next => action => {
  if ( action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
    setTimeout( () => {
      let actions = document.querySelectorAll( '[role=status]' );
      let suggestedAction = actions[ 0 ];
      suggestedAction.classList.add( 'hideSuggestedActionContainer' );
    }, 20 )
  }

  if ( action.type === 'WEB_CHAT/SET_SUGGESTED_ACTIONS' ) {
    const { suggestedActions } = action.payload;
    if ( suggestedActions.length > 0 ) {
      setTimeout( () => {
        let actions = document.querySelectorAll( '[role=status]' );
        let suggestedAction = actions[ 0 ];
        suggestedAction.classList.remove('hideSuggestedActionContainer');
        suggestedAction.classList.add( 'suggestedActionContainer' );
      }, 20 )
    }
  }

  if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
    const { activity } = action.payload;
    if (activity.type === 'message') {
      const actions = document.querySelectorAll( '[role=status]' );
      const buttons = actions[0].querySelectorAll('button');
      buttons.forEach( button => {
        button.onclick = function() {
          const buttonClick = new Event('buttonClick');
          window.dispatchEvent( buttonClick )
        };
      } )
    }
  }

  next(action);
} );

[ ... ]

window.WebChat.renderWebChat(
  {
    directLine: window.WebChat.createDirectLine( {
      token: token
    } ),
    store: store,
    styleOptions: styleOptions
  },
  document.getElementById( 'webchat' )
);

Below the Web Chat renderer, we place our event listener. As a suggested action button is clicked, we remove the suggestedActionContainer class and re-assign the hideSuggestedActionContainer class.

const buttonClickEvent = ( function () {
  window.addEventListener( 'buttonClick', () => {
    let actions = document.querySelectorAll( '[role=status]' );
    let suggestedAction = actions[ 0 ];
    suggestedAction.classList.remove( 'suggestedActionContainer' );
    suggestedAction.classList.add( 'hideSuggestedActionContainer' );
  } );
} )()

A note about the setTimeout() functions used in the store. The store processes every activity as it arrives before displaying it. Because of this, a slight delay needs to be applied to the changes we are pushing to the DOM. Without setTimeout(), the page tries to render our changes before the store is able to display the activity's associated HTML. I set the time outs to 20 milliseconds, but you may find you will need to adjust this. I have found that if I set the time out to too low a number then the changes occur before the activity is rendered. If it's too long (300+ ms or thereabouts), then the changes become visible to the user.

Hope of help!


来源: stackexchange

问:
Android architecture components and coroutines
There is a lot of information out there on architecture components, kotlin and coroutines but nowhere I can find an example using all those things together.
I'm struggling on how to use android's architecture components as described here together with coroutines. I have an idea but feel uncertain if it's the correct way of implementating this architectural style.
I'm trying to use the view model + repository pattern together with retro fit and coroutines.

I have the following repository:

```<code>class FooRepostiroy(private val fooHttpService: FooHttpService) {
   suspend fun someMethod() : SomeResult {
       val response = fooHttpService.someRemotCall() // which is also a suspending method using retrofit-2
       // process response, store it using room and return SomeResult data object
</code>```

Then I use the FooRepository from my ViewModel but because someMethod is a suspending method I need to wrap it in a coroutine scope:

```<code>class FooViewModel(private val fooRepositoru : FooRepository) : ViewModel() {
    private var someMethodJob : Job? = null
    val result : MutableLiveData<SomeResult> = MutableLiveData()

    fun someMethod() {
        someMethodJob = viewModelScope.launch {
            result.value = fooRepositoru.someMethod()
        }
    }

    override fun onCleared() {
        super.onCleared()
        someMethodJob?.cancel()
    }
</code>```

Then in the fragment or activity I can observe the view model result

```<code>    fooViewModel.result.observe(viewLifecycleOwner, Observer {
</code>```

Starting from my repository layer and below everything can be a suspending function. Then from the view model I can call any suspending function but never have a publicly exposed suspending function in my view model.
Is this the correct or proper way to incorporate coroutines with the view model architecture ?

答:
Is this the correct or proper way to incorporate coroutines with the view model architecture?

Yes!

Every instance of ViewModel has its own ViewModelScope.

The purpose of ViewModelScope is to run the jobs during the life cycle of that ViewModel and take care of automatic cancelation of running coroutine jobs in case the parent Activity/Fragment of ViewModel is destroyed.

Any running jobs under ViewModelScope will be canceled when the ViewModel will be destroyed.

Read more here

ContentLicense: CC BY-SA 4.0

Body:
There is a lot of information out there on architecture components, kotlin and coroutines but nowhere I can find an example using all those things together.
I'm struggling on how to use android's architecture components as described here together with coroutines. I have an idea but feel uncertain if it's the correct way of implementating this architectural style.
I'm trying to use the view model + repository pattern together with retro fit and coroutines.

I have the following repository:

class FooRepostiroy(private val fooHttpService: FooHttpService) {
   suspend fun someMethod() : SomeResult {
       val response = fooHttpService.someRemotCall() // which is also a suspending method using retrofit-2
       // process response, store it using room and return SomeResult data object

Then I use the FooRepository from my ViewModel but because someMethod is a suspending method I need to wrap it in a coroutine scope:

class FooViewModel(private val fooRepositoru : FooRepository) : ViewModel() {
    private var someMethodJob : Job? = null
    val result : MutableLiveData<SomeResult> = MutableLiveData()

    fun someMethod() {
        someMethodJob = viewModelScope.launch {
            result.value = fooRepositoru.someMethod()
        }
    }

    override fun onCleared() {
        super.onCleared()
        someMethodJob?.cancel()
    }

Then in the fragment or activity I can observe the view model result

    fooViewModel.result.observe(viewLifecycleOwner, Observer {

Starting from my repository layer and below everything can be a suspending function. Then from the view model I can call any suspending function but never have a publicly exposed suspending function in my view model.
Is this the correct or proper way to incorporate coroutines with the view model architecture ?


问:
How to clone/copy a list of objects that may be views?
This is a Snowflake question about creating views.

We need to recreate a list of objects in a target database from a source. Some of them are tables, some of them are views. Many may already exist in the target, and must be dropped first.

For all-tables, cloning is working without issues:

```<code>CREATE OR REPLACE TABLE TO_DB.X CLONE FROM_DB.X;
</code>```

However some of the objects are views, and this causes an error and potentially(?) another problem:

1) Error:  Object 'X' already exists as VIEW

 2) If it doesn't exist: View will get created as Table

So we need to make sure that Views get created as VIEWS not as a table.
How to do this?

Thank you.

答:
I'm not 100% following your question.  If you are trying to clone views, you can't specifically clone a view.  A view is only cloned if the schema or database is cloned (views would then be cloned as child objects in those clones).

If you are trying recreate a view from the from_db to the to_db, I'd recommend using the get_ddl() function against the "from" schema/database, and then executing the result of that in the "to" schema/database.

Is that the issue you are asking about?

Views will not be created as tables unless you explicitly do a CTAS from a view to a table.  It won't happen during a CLONE operation.

Body:
This is a Snowflake question about creating views.

We need to recreate a list of objects in a target database from a source. Some of them are tables, some of them are views. Many may already exist in the target, and must be dropped first.

For all-tables, cloning is working without issues:

CREATE OR REPLACE TABLE TO_DB.X CLONE FROM_DB.X;

However some of the objects are views, and this causes an error and potentially(?) another problem:

1) Error:  Object 'X' already exists as VIEW

 2) If it doesn't exist: View will get created as Table

So we need to make sure that Views get created as VIEWS not as a table.
How to do this?

Thank you.


问:
Bash making a new file with same name but lowercases
I have a problem, for an assignment I have to open a file and use the sed command to change some stuff and then put the output into a new file. The changing part was not the hardest but writing/copying the output into the new file is the problem. Lets say my beginning file is called ABC1d.gb and the output file has to be called abc1d.gb, when i try this with > or >> it will or overwrite the beginning file and empty it or it will append the output to the ABC1d.gb file. So i want to know if i can even make a file abc1d.gb and if so can i also aply it to my assignment?

Thanks in advance!

My code line that I use now is:

```<code>cat ABC1d.gb | sed 's/ABC/abc/g' > abc1d.gb
</code>```

EDIT/UPDATE:
The problem is my system, I have made the folder i was workin in casesensitive via windowscommands and now it does like it should. The problem wasn't the code, it was the system/folder...

答:
Your command will only have a problem if ABC1d.gb and abc1d.gb are the same file, which will happen if you're using a case-insensitive filesystem.

The solution is to write to a temporary file and then rename it.

```<code>sed 's/ABC/abc/g' ABC1d.gb > abc1d.temp
mv abc1d.temp abc1d.gb
</code>```

Body:
I have a problem, for an assignment I have to open a file and use the sed command to change some stuff and then put the output into a new file. The changing part was not the hardest but writing/copying the output into the new file is the problem. Lets say my beginning file is called ABC1d.gb and the output file has to be called abc1d.gb, when i try this with > or >> it will or overwrite the beginning file and empty it or it will append the output to the ABC1d.gb file. So i want to know if i can even make a file abc1d.gb and if so can i also aply it to my assignment?

Thanks in advance!

My code line that I use now is:

cat ABC1d.gb | sed 's/ABC/abc/g' > abc1d.gb

EDIT/UPDATE:
The problem is my system, I have made the folder i was workin in casesensitive via windowscommands and now it does like it should. The problem wasn't the code, it was the system/folder...

Body:
Your command will only have a problem if ABC1d.gb and abc1d.gb are the same file, which will happen if you're using a case-insensitive filesystem.

The solution is to write to a temporary file and then rename it.

sed 's/ABC/abc/g' ABC1d.gb > abc1d.temp
mv abc1d.temp abc1d.gb


问:
Docker image Prune Filtering
Currently I am running

```<code>while true; do
    docker system prune --all -f;
    sleep 6400;
    done
</code>```

In a daemonset to remove older images in my containers.

There is some unused images that I still want to keep around. Is there a possibility to filter out some images to not be pruned by this command?

for example after running docker system prune command,the following should not change if I want to prune everything else except repository a

```<code>Repository         TAG          IMAGE_ID         CREATED     SIZE
a                  12dac         3eadf            now          1
a                  44rfd         233df            4 month ago  1
</code>```

Thanks.

答:
You can add regular expression filters to prevent certain containers from pruning.

```<code>filtered=$(docker image prune –filter name=foo* -aq)
docker rm $filtered
</code>```

This will delete all except containers that begin with the letters foo.

If necessary, you can read about the additional keys you can use for filtering in the docs

(2022) Update: This is no longer supported. Please see the other answers.

Title: Docker image Prune Filtering

Body:
Currently I am running

while true; do
    docker system prune --all -f;
    sleep 6400;
    done

In a daemonset to remove older images in my containers.

There is some unused images that I still want to keep around. Is there a possibility to filter out some images to not be pruned by this command?

for example after running docker system prune command,the following should not change if I want to prune everything else except repository a

Repository         TAG          IMAGE_ID         CREATED     SIZE
a                  12dac         3eadf            now          1
a                  44rfd         233df            4 month ago  1

Thanks.

Body:
You can add regular expression filters to prevent certain containers from pruning.

filtered=$(docker image prune –filter name=foo* -aq)
docker rm $filtered

This will delete all except containers that begin with the letters foo.

If necessary, you can read about the additional keys you can use for filtering in the docs

(2022) Update: This is no longer supported. Please see the other answers.


问:
Error to create matrix with zeros in kotlin using Mat.zeros
I'm working on developing an application using opencv. I'm uploading an image and assigning a new matrix with the same size as the original image, but in this matrix I need to fill all the rows and columns with 0. However, the function Mat.zeros is not assigning 0 in my matrix and I have the output filled with values: [D @ 13a5b9d, [D @ f3978b1, [D @ 30c17d0 ...
Oh, and I need it to be a matrix of type Mat () because I will work with opencv. Can someone help me solve this error
Code:

```<code>val srcOriginal = Imgcodecs.imread(currentPhotoPath)

val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

for(x in 0..markers.rows()) {
   for(y in 0..markers.cols()) {
      Log.i("teste", markers[x,y])
  }
}
</code>```

Output expected:

```<code>[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
</code>```

output:

答:
Your code actually creates a matrix filled with the correct values. The thing is, markers[x,y] returns a value of type DoubleArray, not Double and hence you cannot see the actual content. If you print the values with the following line you will see that there are zeros in the matrix:

Log.i("teste", markers[x,y].contentToString())

// Alternative using the Java Arrays class
Log.i("teste", Arrays.toString(markers[x,y]))
```

Body:
I'm working on developing an application using opencv. I'm uploading an image and assigning a new matrix with the same size as the original image, but in this matrix I need to fill all the rows and columns with 0. However, the function Mat.zeros is not assigning 0 in my matrix and I have the output filled with values: [D @ 13a5b9d, [D @ f3978b1, [D @ 30c17d0 ...
Oh, and I need it to be a matrix of type Mat () because I will work with opencv. Can someone help me solve this error
Code:

val srcOriginal = Imgcodecs.imread(currentPhotoPath)

val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

for(x in 0..markers.rows()) {
   for(y in 0..markers.cols()) {
      Log.i("teste", markers[x,y])
  }
}

Output expected:

[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]

output:


问:
Odd Syntax (Walrus operator in inheritance)
I was looking in python's grammar and was that you could use the walrus operator in inheritance! Not believing it, I tried it out:

```<code>class foo: pass
class bar(foobar := foo):
    def x(self):
        print("it works!")

b = bar()
b.x()
</code>```

This does not raise any syntax error (python 3.8.2)! What is the use of it, and how does it work?

答:
After a little experimenting (and luck), I found out it is for things like renaming classes while inheriting for them:

```<code>class foo:
    def __init__(self, x):
        pass

class bar(foobar := foo):
    def __init__(self):
        foobar.__init__(self, 2)

    def x(self):
        print("it works!")

b = bar()
b.x()
</code>```

If you remove the walrus operator it does not work (obviously). I'm not sure what use it would really be.

Body:
I was looking in python's grammar and was that you could use the walrus operator in inheritance! Not believing it, I tried it out:

class foo: pass
class bar(foobar := foo):
    def x(self):
        print("it works!")

b = bar()
b.x()

This does not raise any syntax error (python 3.8.2)! What is the use of it, and how does it work?

Body:
After a little experimenting (and luck), I found out it is for things like renaming classes while inheriting for them:

class foo:
    def __init__(self, x):
        pass

class bar(foobar := foo):
    def __init__(self):
        foobar.__init__(self, 2)

    def x(self):
        print("it works!")

b = bar()
b.x()

If you remove the walrus operator it does not work (obviously). I'm not sure what use it would really be.


问:
Plot Magnitude[dB] vs. Frequency[deg] with matplotlib.pyplot python where Mag and Freq are two lists
```<code># plotting Magnitud vs. Freq
figure1 = plt.Figure(figsize=(5,4), dpi=100)
ax1 = figure1.add_subplot(111)
ax1.plot(freq, mag_S11, color = 'r')
# ax1.set_ylim([-75, 50])
# ax1.set_xlim([0.0, 30.0])
scatter = FigureCanvasTkAgg(figure1, root)
scatter.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax1.legend(['S11'])
ax1.set_xlabel('Frequency [GHz]')
ax1.set_title('Magnitude[dB] Vs. Frequency')
</code>```

My freq and mag_S11 are 2 lists of more than 200 elements, the problem is I'm not getting the graph behavior I want. Am I plotting it correctly or the values are wrong?

This is what I'm getting:

This is what I want:

Any help would be really appreciated.

答:
That is because plot connects the dots. You want to either use ax1.scatter(...) with the current data or ax1.plot(...) with the data sorted so that x increases. Using

```<code> freq, mag_S11 = sorted([freq, mag_S11], key=lambda x: x[0])
</code>```

should sort both datasets by increasing frequency and let the plot work nicely.

Body:
# plotting Magnitud vs. Freq
figure1 = plt.Figure(figsize=(5,4), dpi=100)
ax1 = figure1.add_subplot(111)
ax1.plot(freq, mag_S11, color = 'r')
# ax1.set_ylim([-75, 50])
# ax1.set_xlim([0.0, 30.0])
scatter = FigureCanvasTkAgg(figure1, root)
scatter.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH)
ax1.legend(['S11'])
ax1.set_xlabel('Frequency [GHz]')
ax1.set_title('Magnitude[dB] Vs. Frequency')

My freq and mag_S11 are 2 lists of more than 200 elements, the problem is I'm not getting the graph behavior I want. Am I plotting it correctly or the values are wrong?

This is what I'm getting:

This is what I want:

Any help would be really appreciated.

Body:
That is because plot connects the dots. You want to either use ax1.scatter(...) with the current data or ax1.plot(...) with the data sorted so that x increases. Using

 freq, mag_S11 = sorted([freq, mag_S11], key=lambda x: x[0])

should sort both datasets by increasing frequency and let the plot work nicely.


问:
React: is not defined no-undef
When I refresh the error message in clearAll() is:

./src/App.js

Line 22:  'notes' is not defined  no-undef

Line 23:  'notes' is not defined  no-undef

How do I define the the properties to use>

```<code>import React, { Component } from 'react';
import Route from 'react-router-dom';
import './App.css';
import Header from './components/Header';
import Router from './components/Router';
import Home from '.Home';
import AddNote from '/AddNote';
import EditNote from '/EditNote';

class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        note: "",
        notes: []
    };
}

clearAll() {
    notes.length = 0;
    notes = [];
}
</code>```

答: const { note, notes } = this.state;</p>

Title: React: is not defined no-undef

Body:
When I refresh the error message in clearAll() is:

./src/App.js

Line 22:  'notes' is not defined  no-undef

Line 23:  'notes' is not defined  no-undef

How do I define the the properties to use>

import React, { Component } from 'react';
import Route from 'react-router-dom';
import './App.css';
import Header from './components/Header';
import Router from './components/Router';
import Home from '.Home';
import AddNote from '/AddNote';
import EditNote from '/EditNote';

class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        note: "",
        notes: []
    };
}

clearAll() {
    notes.length = 0;
    notes = [];
}

Body: const { note, notes } = this.state;


问:
Using PowerShell to replace string that contains $ in the string
I am trying to use PowerShell do a simple find and replace. I use template text files and use $ in front of values that need to be changed.

Example:

```<code>(Get-Content "D:\test") | Foreach-Object {$_ -replace "`$TBQUAL", "DBO"} | Set-Content "D:\test"
</code>```

It should find the line OWNER=$TBQUAL and make it look like OWNER=DBO.

I am using the escape in front of $TBQUAL with no luck. To test that it is working if I removed the $ from the front, it would replace TBQUAL and made it look like OWNER=$DBO.

答:
If you aren't using regular expressions in your replacement, you can do a simple (and fast) replace like this:</p>

```<code>Foreach-Object {$_.Replace('$TBQUAL', 'DBO')}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use PowerShell do a simple find and replace. I use template text files and use $ in front of values that need to be changed.

Example:

(Get-Content "D:\test") | Foreach-Object {$_ -replace "`$TBQUAL", "DBO"} | Set-Content "D:\test"

It should find the line OWNER=$TBQUAL and make it look like OWNER=DBO.

I am using the escape in front of $TBQUAL with no luck. To test that it is working if I removed the $ from the front, it would replace TBQUAL and made it look like OWNER=$DBO.

Body:
If you aren't using regular expressions in your replacement, you can do a simple (and fast) replace like this:

Foreach-Object {$_.Replace('$TBQUAL', 'DBO')}


问:
Preventing duplicates from being added to shopping list DOM Selectors (JS)
I've been attempting to prevent duplicate items from being added to a shopping list I created. I thought the code directly below might do it, but it hasn't been helping. I expected the JS code to access the ul tag and iterate through it's list items so it can compare what's already in the list to what's trying to be added. I'm assuming my issue is with accessing the input. Also, which function should this be done in? The createListElement function or the addListAfterClick function. Please see the code snippet for how the code runs. Thank you in advance!!

```<code>var ul = document.getElementById("shoppingcart");
      var items = ul.getElementsByTagName("li");
      for (var i = 0; i < items.length; i++) {
        if (input.value === items[i]); {
          alert("already in list");
          console.log("already in list");

        }

</code>```

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelectorAll("li");

function inputLength() {
  return input.value.length; // gets the length of the input value

}

function createListElement() {
  var li = document.createElement("li"); // creating a new li tag
  li.appendChild(document.createTextNode(input.value)); // adding input value to newly created li tag
  li.classList.add("item"); // adds a class called "item" to the newly created li tag
  li.addEventListener("click", toggleDone);
  /*  adds click abilities to new item by referencing the toggleDone function, this allows for a line-through
                                               an item in the list if it's clicked,and will remove the line if the item is clicked again */

  ul.appendChild(li); // adds the li tag in the ul tag
  input.value = ""; //clears the input box to allow for new inputs

  var button = document.createElement("button"); // creates anew button tag
  button.appendChild(document.createTextNode("delete")); // creates a new button with the word "delete"
  li.append(button); //adds delete button next to each new input in the shopping list
  button.onclick = removeParent; // if the delete button is clicked, it references the removeParent function which deletes the an input from the shopping list
}

function removeParent(event) {
  event.target.parentNode.remove(); // simply deletes an input from the parent node, which is the ul tag, remember li tags are children of ul tags
}

function toggleDone() {
  this.classList.toggle('done'); // references the css ".done" class, which allows for line-through text, the toggle function turns on and off the line through
}

function addListAfterClick() {
  if (inputLength() > 0) //if the length of the input is greater than 0..(meaning you have to input a something in order to add to the list)
  {
    createListElement(); // references createListElement function, which adds a new li tag with the input value and a delete button next to it

  }

}

function addListAfterKeyPress(event) {
  if (inputLength() > 0 && event.keyCode === 13) // if length of the input is greater than 0 and your press the enter key (13 is the value that represents the enter key)
  {
    {
      createListElement(); // references createListElement function, which adds a new li tag with the input value and a delete button next to it
    }

  }

}

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeyPress);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title> JavaScript + DOM </title>

</head>

<body>
  <h1> Shopping List</h1>
  <p id="first"> Get it done today</p>
  <input id="userinput" type="text" placeholder="enter items">
  <button id="enter">Click Me!</button>

  <ul class="list" id="shoppingcart">
    <li class="bold red" random="23"> Notebook</li>

  </ul>

</body>

</html></code>```

答:
A quick solution is to use a "Set", you can check the duplicity in simple steps. For example:

var mySet = new Set();
mySet.add("foo");
mySet.add("fuu");
mySet.has("foo"); // true
mySet.has("fuu"); // true
mySet.has("faa"); // false
```

<p>So, you can add a set in your first lines and set the conditional <code>has</code> in <code>addListAfterClick</code>:</p>

<pre class="lang-js prettyprint-override"><code>function addListAfterClick() {
  if (inputLength() > 0 && !mySet.has(input.value))
  {
    createListElement();
  }

}
</code>```

And add the value when input is done in createListElement:

function createListElement()
{
  // code...
  ul.appendChild(li);
  mySet.add(input.value);
  input.value = "";
  // code...
}
```

Body:
I've been attempting to prevent duplicate items from being added to a shopping list I created. I thought the code directly below might do it, but it hasn't been helping. I expected the JS code to access the ul tag and iterate through it's list items so it can compare what's already in the list to what's trying to be added. I'm assuming my issue is with accessing the input. Also, which function should this be done in? The createListElement function or the addListAfterClick function. Please see the code snippet for how the code runs. Thank you in advance!!

var ul = document.getElementById("shoppingcart");
      var items = ul.getElementsByTagName("li");
      for (var i = 0; i < items.length; i++) {
        if (input.value === items[i]); {
          alert("already in list");
          console.log("already in list");

        }

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelectorAll("li");

function inputLength() {
  return input.value.length; // gets the length of the input value

}

function createListElement() {
  var li = document.createElement("li"); // creating a new li tag
  li.appendChild(document.createTextNode(input.value)); // adding input value to newly created li tag
  li.classList.add("item"); // adds a class called "item" to the newly created li tag
  li.addEventListener("click", toggleDone);
  /*  adds click abilities to new item by referencing the toggleDone function, this allows for a line-through
                                               an item in the list if it's clicked,and will remove the line if the item is clicked again */

  ul.appendChild(li); // adds the li tag in the ul tag
  input.value = ""; //clears the input box to allow for new inputs

  var button = document.createElement("button"); // creates anew button tag
  button.appendChild(document.createTextNode("delete")); // creates a new button with the word "delete"
  li.append(button); //adds delete button next to each new input in the shopping list
  button.onclick = removeParent; // if the delete button is clicked, it references the removeParent function which deletes the an input from the shopping list
}

function removeParent(event) {
  event.target.parentNode.remove(); // simply deletes an input from the parent node, which is the ul tag, remember li tags are children of ul tags
}

function toggleDone() {
  this.classList.toggle('done'); // references the css ".done" class, which allows for line-through text, the toggle function turns on and off the line through
}

function addListAfterClick() {
  if (inputLength() > 0) //if the length of the input is greater than 0..(meaning you have to input a something in order to add to the list)
  {
    createListElement(); // references createListElement function, which adds a new li tag with the input value and a delete button next to it

  }

}

function addListAfterKeyPress(event) {
  if (inputLength() > 0 && event.keyCode === 13) // if length of the input is greater than 0 and your press the enter key (13 is the value that represents the enter key)
  {
    {
      createListElement(); // references createListElement function, which adds a new li tag with the input value and a delete button next to it
    }

  }

}

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeyPress);

<!DOCTYPE html>

  <title> JavaScript + DOM </title>

 Shopping List

 Get it done today

  <input id="userinput" type="text" placeholder="enter items">
  <button id="enter">Click Me!</button>

 Notebook

Body:
A quick solution is to use a "Set", you can check the duplicity in simple steps. For example:

var mySet = new Set();
mySet.add("foo");
mySet.add("fuu");
mySet.has("foo"); // true
mySet.has("fuu"); // true
mySet.has("faa"); // false

So, you can add a set in your first lines and set the conditional has in addListAfterClick:

function addListAfterClick() {
  if (inputLength() > 0 && !mySet.has(input.value))
  {
    createListElement();
  }

}

And add the value when input is done in createListElement:

function createListElement()
{
  // code...
  ul.appendChild(li);
  mySet.add(input.value);
  input.value = "";
  // code...
}


问:
Integrating React-Router into a React-Redux hooks app
I'm having some confusion about how to set up React Router in a redux project. This is a simplification of my top-level component:

```<code>const App = () => {

  const [data, setData] = useState();

  useEffect(() => {
    const data = fetchData(); //initial async data fetch
    setData(data);
  }, [])

  useEffect(() => {
    if (data) {
      const initialUsState = getRandomState(data.state);
      const intitialUsCounty = getRandomCounty(data.county);

      //these are action creators that dispatch to the store after the intial data fetch
      dispatchUsState(initialUsState);
      dispatchUsCounty(intitialUsCounty);
    }
  }, data)

  const UsState = useSelector(state => state.UsState); //react-redux state selector hooks
  const UsCounty = useSelector(state => state.UsCounty);

  const getPlotData = () => {
     const plotData = createPlotData(UsState, UsCounty);
     return plotData;
  }

  return UsState && UsCounty ? (
    <Router>
      <Route path={`/:${UsState}/:${UsCounty}`} >
        <ComponentOne UsState={UsState} UsCounty={UsCounty} />
        <ComponentTwo UsState={UsState} UsCounty={UsCounty} />
        <Scatterplot plotData={getPlotData()}
      </Route>
    </Router>
  )
  :
  null;
</code>```

There are a few issues I am having:

When I'm running this locally, at localhost:8080/, I am not seeing anything being rendered to the screen. I'm assuming this is because I'm at the root level path? How do I get to the /:${UsState}/:${UsCounty} path automatically, as soon as UsState and UsCounty are available?

UsState and UsCounty are both values that live in the store. If I change my url to a specific /:${UsState}/:${UsCounty} path that I know is valid, how will the redux be able to dispatch the appropriate UsState and UsCounty to the store, as well as complete that initial data fetch?

Also, if /:${UsState}/:${UsCounty} is provided in the URL, I will not want to dispatch a random state & county to the store, as it will already exist in the URL.

答:
Figured out the answer to my own question. In top-level index.js, set up the routes in a <Switch> component like so:

```<code>const jsx = (
  <Provider store={store}>
    <Router>
      <Switch>
        <Route exact path="/">
          <CovidApp />
        </Route>
        <Route path="/:state/:county">
          <CovidApp />
        </Route>
      </Switch>
    </Router>
  </Provider>
);
</code>```

When visiting the site for the first time with the exact root directory /, in the child component CovidApp, I set up a useEffect() hook along with the useHistory() react-router hook to update the path when either of my redux store values, UsState and UsCounty, changed:

```<code>const history = useHistory(); //react-router hook

useEffect(() => {
  if (UsState && county) {
    history.push(`/${UsState}/${county}`);
  }
}, [UsState, county]);
</code>```

Then, the switch statement above would automatically switch to the "/:state/:county" route.

Also in CovidApp, I would check if params already existed when I first navigate to the site. If they do exist, I dispatch them to the store:

```<code> const params = useParams(); //react-router hook

 useEffect(() => {
    const urlHasParams = !!Object.keys(params).length;
      //if there are params when first visiting site and data is available: get each param, lookup in dict, and dispatch to store
      if (covidData && urlHasParams) {
        dispatch(dispatchUsState(params.state));
        dispatch(dispatchCounty(params.county));
    }
  }, [data]);
</code>```

Body:
I'm having some confusion about how to set up React Router in a redux project. This is a simplification of my top-level component:

const App = () => {

  const [data, setData] = useState();

  useEffect(() => {
    const data = fetchData(); //initial async data fetch
    setData(data);
  }, [])

  useEffect(() => {
    if (data) {
      const initialUsState = getRandomState(data.state);
      const intitialUsCounty = getRandomCounty(data.county);

      //these are action creators that dispatch to the store after the intial data fetch
      dispatchUsState(initialUsState);
      dispatchUsCounty(intitialUsCounty);
    }
  }, data)

  const UsState = useSelector(state => state.UsState); //react-redux state selector hooks
  const UsCounty = useSelector(state => state.UsCounty);

  const getPlotData = () => {
     const plotData = createPlotData(UsState, UsCounty);
     return plotData;
  }

  return UsState && UsCounty ? (
    <Router>
      <Route path={`/:${UsState}/:${UsCounty}`} >
        <ComponentOne UsState={UsState} UsCounty={UsCounty} />
        <ComponentTwo UsState={UsState} UsCounty={UsCounty} />
        <Scatterplot plotData={getPlotData()}
      </Route>
    </Router>
  )
  :
  null;

There are a few issues I am having:

When I'm running this locally, at localhost:8080/, I am not seeing anything being rendered to the screen. I'm assuming this is because I'm at the root level path? How do I get to the /:${UsState}/:${UsCounty} path automatically, as soon as UsState and UsCounty are available?

UsState and UsCounty are both values that live in the store. If I change my url to a specific /:${UsState}/:${UsCounty} path that I know is valid, how will the redux be able to dispatch the appropriate UsState and UsCounty to the store, as well as complete that initial data fetch?

Also, if /:${UsState}/:${UsCounty} is provided in the URL, I will not want to dispatch a random state & county to the store, as it will already exist in the URL.

Body:
Figured out the answer to my own question. In top-level index.js, set up the routes in a <Switch> component like so:

const jsx = (
  <Provider store={store}>
    <Router>
      <Switch>
        <Route exact path="/">
          <CovidApp />
        </Route>
        <Route path="/:state/:county">
          <CovidApp />
        </Route>
      </Switch>
    </Router>
  </Provider>
);

When visiting the site for the first time with the exact root directory /, in the child component CovidApp, I set up a useEffect() hook along with the useHistory() react-router hook to update the path when either of my redux store values, UsState and UsCounty, changed:

const history = useHistory(); //react-router hook

useEffect(() => {
  if (UsState && county) {
    history.push(`/${UsState}/${county}`);
  }
}, [UsState, county]);

Then, the switch statement above would automatically switch to the "/:state/:county" route.

Also in CovidApp, I would check if params already existed when I first navigate to the site. If they do exist, I dispatch them to the store:

 const params = useParams(); //react-router hook

 useEffect(() => {
    const urlHasParams = !!Object.keys(params).length;
      //if there are params when first visiting site and data is available: get each param, lookup in dict, and dispatch to store
      if (covidData && urlHasParams) {
        dispatch(dispatchUsState(params.state));
        dispatch(dispatchCounty(params.county));
    }
  }, [data]);


问:
cannot import name 'ft2font' from 'matplotlib' on windows10
I am using a windows10 machine and using PyCharm as my IDE, so when I tried to run the below code, it shows the following error

I tried uninstalling and re-installing matplotlib and also as someone from SO suggested used --force reinstall too, but didn't work

It was working well until yesterday

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

 rng = np.random.RandomState(42)
 X = 10 * rng.rand(50)
 y = 2 * X - 1 + rng.randn(50)

plt.scatter(X, y)
plt.show()
</code>```

Error showing on both Pycharm and Vs Code

```<code>Traceback (most recent call last):
File "D:/PyCharm/exercise/numpy_exercise/pandas_py.py", line 1, in
<module>
import matplotlib.pyplot as plt
File "C:\Users\smile\AppData\Roaming\Python\Python37\site-
packages\matplotlib\__init__.py", line 143, in <module>
from matplotlib import ft2font
ImportError: cannot import name 'ft2font' from 'matplotlib'
 (C:\Users\smile\AppData\Roaming\Python\Python37\site-
 packages\matplotlib\__init__.py)

 Error showing on Jupyter Notebook

<ipython-input-1-1842680e3d86> in <module>
  1 import pandas as pd
  2 import numpy as np
    ----> 3 import matplotlib.pyplot as plt
  4 get_ipython().run_line_magic('matplotlib', 'inline')
  5

 ~\AppData\Roaming\Python\Python37\site-packages\matplotlib\pyplot.py in
 <module>
 30 from cycler import cycler
 31 import matplotlib
   ---> 32 import matplotlib.colorbar
 33 import matplotlib.image
 34 from matplotlib import rcsetup, style

 ~\AppData\Roaming\Python\Python37\site-packages\matplotlib\colorbar.py
 in <module>
 25
 26 import matplotlib as mpl
 ---> 27 import matplotlib.artist as martist
 28 import matplotlib.cbook as cbook
 29 import matplotlib.collections as collections

 ModuleNotFoundError: No module named 'matplotlib.artist'
</code>```

答:
I had a similar problem which was solved simply by forcing the reinstall of matplotlib:

```<code>python -m pip install -I matplotlib
</code>```

The python -m pip instead of pip install to make sure the correct python executable is used

The -I forces reinstall

Body:
I am using a windows10 machine and using PyCharm as my IDE, so when I tried to run the below code, it shows the following error

I tried uninstalling and re-installing matplotlib and also as someone from SO suggested used --force reinstall too, but didn't work

It was working well until yesterday

import matplotlib.pyplot as plt
import numpy as np

 rng = np.random.RandomState(42)
 X = 10 * rng.rand(50)
 y = 2 * X - 1 + rng.randn(50)

plt.scatter(X, y)
plt.show()

Error showing on both Pycharm and Vs Code

Traceback (most recent call last):
File "D:/PyCharm/exercise/numpy_exercise/pandas_py.py", line 1, in
<module>
import matplotlib.pyplot as plt
File "C:\Users\smile\AppData\Roaming\Python\Python37\site-
packages\matplotlib\__init__.py", line 143, in <module>
from matplotlib import ft2font
ImportError: cannot import name 'ft2font' from 'matplotlib'
 (C:\Users\smile\AppData\Roaming\Python\Python37\site-
 packages\matplotlib\__init__.py)

 Error showing on Jupyter Notebook

<ipython-input-1-1842680e3d86> in <module>
  1 import pandas as pd
  2 import numpy as np
    ----> 3 import matplotlib.pyplot as plt
  4 get_ipython().run_line_magic('matplotlib', 'inline')
  5

 ~\AppData\Roaming\Python\Python37\site-packages\matplotlib\pyplot.py in
 <module>
 30 from cycler import cycler
 31 import matplotlib
   ---> 32 import matplotlib.colorbar
 33 import matplotlib.image
 34 from matplotlib import rcsetup, style

 ~\AppData\Roaming\Python\Python37\site-packages\matplotlib\colorbar.py
 in <module>
 25
 26 import matplotlib as mpl
 ---> 27 import matplotlib.artist as martist
 28 import matplotlib.cbook as cbook
 29 import matplotlib.collections as collections

 ModuleNotFoundError: No module named 'matplotlib.artist'

Body:
I had a similar problem which was solved simply by forcing the reinstall of matplotlib:

python -m pip install -I matplotlib

The python -m pip instead of pip install to make sure the correct python executable is used

The -I forces reinstall


问:
Laravel Dusk and memory usage - how to close the browser and custom process
I'm using Laravel Dusk in the controller for users to get screenshots of the any website using mine website.

My code:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Dusk\ElementResolver;
use Exception;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;
use Facebook\WebDriver\WebDriverBy;

use Mail;

class ScreenController extends Controller {
    public function take_screenshoot() {

        $process = (new ChromeProcess)->toProcess();
        if ($process->isStarted()) {
          $process->stop();
        }
        $process->start();

        $options      = (new ChromeOptions)->addArguments([
                '--disable-gpu',
                '--headless',
                '--window-size=1920,1080',
                '--no-sandbox'
            ]);
        $capabilities = DesiredCapabilities::chrome()->setCapability(ChromeOptions::CAPABILITY, $options);

              $driver = retry(5, function () use ($capabilities) {
          return RemoteWebDriver::create('http://localhost:9515', $capabilities, 50000, 60000);
        }, 50);

        $browser = new Browser($driver, new ElementResolver($driver, ''));
        $browser->resize(1920, 1080);
        $browser->visit('http://www.example.com')->mouseover('iframe');

        $screenshoot_name = md5(time());
        $browser->driver->takeScreenshot(base_path('tests/Browser/screenshots/'.$screenshoot_name.'.png'));
        echo "<img src='/tests/Browser/screenshots/".$screenshoot_name.".png></img>";

        $process->stop();

      }
</code>```

Everything works well here as expected just memory usage is by each user request (user visit) higher and higher... How to solve that problem? Why $process->stop(); do not close the browser?

UPDATE
I tried:

```<code>$browser->quit();
</code>```

and

```<code>$browser->driver->quit();
</code>```

but I got error:

Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error
  thrown for http DELETE to /session/8a4f02f2d13648ccfbdead97b338e4f4
  Failed to connect to localhost port 9515: Connection refused

UPDATE 2.0
This is what I got when I run

```<code># ps -aux | less
</code>```

答:
I got the exact same issue and ended up solving it adding:

```<code>$browser->quit();
$process->stop();
</code>```

Note that the order matters. If I swap the lines I get the same error that you mentioned:

```<code>Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error thrown for http DELETE to /session/8a4f02f2d13648ccfbdead97b338e4f4 Failed to connect to localhost port 9515: Connection refused
</code>```

Body:
I'm using Laravel Dusk in the controller for users to get screenshots of the any website using mine website.

My code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Dusk\ElementResolver;
use Exception;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;
use Facebook\WebDriver\WebDriverBy;

use Mail;

class ScreenController extends Controller {
    public function take_screenshoot() {

        $process = (new ChromeProcess)->toProcess();
        if ($process->isStarted()) {
          $process->stop();
        }
        $process->start();

        $options      = (new ChromeOptions)->addArguments([
                '--disable-gpu',
                '--headless',
                '--window-size=1920,1080',
                '--no-sandbox'
            ]);
        $capabilities = DesiredCapabilities::chrome()->setCapability(ChromeOptions::CAPABILITY, $options);

              $driver = retry(5, function () use ($capabilities) {
          return RemoteWebDriver::create('http://localhost:9515', $capabilities, 50000, 60000);
        }, 50);

        $browser = new Browser($driver, new ElementResolver($driver, ''));
        $browser->resize(1920, 1080);
        $browser->visit('http://www.example.com')->mouseover('iframe');

        $screenshoot_name = md5(time());
        $browser->driver->takeScreenshot(base_path('tests/Browser/screenshots/'.$screenshoot_name.'.png'));
        echo "";

        $process->stop();

      }

Everything works well here as expected just memory usage is by each user request (user visit) higher and higher... How to solve that problem? Why $process->stop(); do not close the browser?

UPDATE
I tried:

$browser->quit();

and

$browser->driver->quit();

but I got error:

Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error
  thrown for http DELETE to /session/8a4f02f2d13648ccfbdead97b338e4f4
  Failed to connect to localhost port 9515: Connection refused

UPDATE 2.0
This is what I got when I run

# ps -aux | less

Body:
I got the exact same issue and ended up solving it adding:

$browser->quit();
$process->stop();

Note that the order matters. If I swap the lines I get the same error that you mentioned:

Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error thrown for http DELETE to /session/8a4f02f2d13648ccfbdead97b338e4f4 Failed to connect to localhost port 9515: Connection refused


问:
Writing javascript to detect speed
I am a new member. For school, they want us to write code to figure out the speed of the device (when driving). Is this possible in javascript? Im assuming it will be challenging but any ideas help! Thank you in advance!</p>

答:
You can use Geolocation API to get current position.

Since speed is distance over time, you can use a setInterval() to periodically get the position (every 3 seconds for example) and calculate the distance between the last and current coordinates.

Since that's a homework/school work, I think I shouldn't give you any code.

Title: Writing javascript to detect speed


问:
How to select by two fields using IN operator
I tried query like

```<code>SELECT id FROM events WHERE iid = 2 AND target_id = 3 OR iid = 3 AND target_id = 5 OR...
</code>```

How to short this? Also tried to use IN operator but it get wrong logic

```<code>SELECT id FROM events where iid IN (2, 3) AND target_id IN (3, 5)
</code>```

答:
Postgres support tuples equality:</p>

```<code>select id
from events
where (iid, target_id) in ( (2, 3), (3, 5) )
</code>```

Body:
I tried query like

SELECT id FROM events WHERE iid = 2 AND target_id = 3 OR iid = 3 AND target_id = 5 OR...

How to short this? Also tried to use IN operator but it get wrong logic

SELECT id FROM events where iid IN (2, 3) AND target_id IN (3, 5)

Body:
Postgres support tuples equality:

select id
from events
where (iid, target_id) in ( (2, 3), (3, 5) )


答:
It's of no use - so don't use it ;-)  Arbitrary expressions are allowed there.  For example, this is even more useless:

```<code>from random import choice

class C(choice([int, list])):
    pass
</code>```

Have fun ;-)

Title: Odd Syntax (Walrus operator in inheritance)

Body:
I was looking in python's grammar and was that you could use the walrus operator in inheritance! Not believing it, I tried it out:

class foo: pass
class bar(foobar := foo):
    def x(self):
        print("it works!")

b = bar()
b.x()

This does not raise any syntax error (python 3.8.2)! What is the use of it, and how does it work?

Body:
It's of no use - so don't use it ;-)  Arbitrary expressions are allowed there.  For example, this is even more useless:

from random import choice

class C(choice([int, list])):
    pass

Have fun ;-)


问:
How to detect that my application is running in vs2008 with debugger attached?
Previously I was doing a lot of WinFroms components and we had something InDesigner I'm wondering if there is something similar IsWithDebuggerAttached

Thanks

答: From the the System.Diagnostics namespace, use the Debugger.IsAttached property.


问:
x3dom -> inline URL format in a Blazor Server App issues
I am able to load an external .x3d file using a html file but I can't seem to get this working in a Blazor Server App in the _Host.cshtml file.
I have the x3d file in a models folder under wwroot and my html looks like:</p>
```<code><inline url='/models/Deer.x3d'>  </inline>
</code>```

答: I was missing the step of adding a mime type for the x3d file extension.</p>

Body:
I am able to load an external .x3d file using a html file but I can't seem to get this working in a Blazor Server App in the _Host.cshtml file.
I have the x3d file in a models folder under wwroot and my html looks like:

<inline url='/models/Deer.x3d'>  </inline>


问:
How to fill missing values based on grouped average?
My data has missing values for 'Age' and I want to replace them by average based on groupby column 'Title'. After the command:

```<code>df.groupby('Title').mean()['Age']
</code>```

I get a list for example

Mr 32

Miss 21.7

Ms 28

etc.

I tried:

```<code>df['Age'].replace(np.nan, 0, inplace=True)
df[(df.Age==0.0)&(df.Title=='Mr')]
</code>```

to just see the cells where age is missing and title is of one type but it doesn't work.

Question 1. Why the code above doesn't show any cells, despite multiple cells satisfying both conditions at the same time (age = 0.0 and title is mr)

Question2. How can I replace all missing values based on the group average as described above?

答:
Question 1:
Please provide a snippet in order to be able to reproduce the error

Question 2:

Try df['Age'].fillna(f.groupby('Title')['Age'].transform('mean')). This is similar to Pandas: filling missing values by mean in each group

Body:
My data has missing values for 'Age' and I want to replace them by average based on groupby column 'Title'. After the command:

df.groupby('Title').mean()['Age']

I get a list for example

Mr 32

Miss 21.7

Ms 28

etc.

I tried:

df['Age'].replace(np.nan, 0, inplace=True)
df[(df.Age==0.0)&(df.Title=='Mr')]

to just see the cells where age is missing and title is of one type but it doesn't work.

Question 1. Why the code above doesn't show any cells, despite multiple cells satisfying both conditions at the same time (age = 0.0 and title is mr)

Question2. How can I replace all missing values based on the group average as described above?


问:
Google API returns a response 200 empty JSON
I'm trying to make an HTTP GET request to the Google Street View Publish API, inside a Google Apps Script script, to fetch the photos list and save metadata about them to a Google spreadsheet.

The code I'm using on the script to contact the API:

```<code>var url = 'https://streetviewpublish.googleapis.com/v1/photos?fields=nextPageToken%2Cphotos&key=' + API_KEY;

var response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    headers: {
        //the accessToken is borrowed from the Apps Script Infrastructure `ScriptApp.getOAuthToken()`
        //source: https://www.youtube.com/watch?v=aP6pxK3jexc
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
    }
});
console.log('API response:\n' + response);
</code>```

And including the Street View Auth at the script's manifest oauthscopes.json file:

```<code>...
"oauthScopes": [
  "https://www.googleapis.com/auth/streetviewpublish",
  "https://www.googleapis.com/auth/script.external_request",
  "https://www.googleapis.com/auth/spreadsheets"
]
...
</code>```

Been using a time-based trigger to run the script every 15 min, and it has been working just fine for couple of hours and returning a JSON object with the photos on the account, until the API stopped to return a response, and it's now just returning an empty JSON object {}.

I don't think I consumed the quote for the API usage, my numbers from the GCP dashboard as follows:

Tried to create another API KEY and use it at the script, but still no luck.

Also, when tried to test the API from the Google APIs Explorer, authorize and execute, it gives me the response code 200 with an empty JSON object as well.
This has been working before, but, now it doesn't!

What might be the problem here?

Edit:

As suggested at the comments, I tried to:

Call the API endpoint with or without the API key and the other parameters, as follows:

https://streetviewpublish.googleapis.com/v1/photos?fields=nextPageToken%2Cphotos&key=' + API_KEY

https://streetviewpublish.googleapis.com/v1/photos?key=' + API_KEY

https://streetviewpublish.googleapis.com/v1/photos

Also, tried to revoke the access for both the Google APIs Explorer and the script on Google Apps Script, from the account security checkup. Which because of it when tried to run it again, it opened a popup window to ask for the authorization/permission again, which I granted as well.

Tried to log out of the Google account & clearing the browser's cache.

Yet, still, the same empty JSON object response!

Edit 2:

Also stopped the script's time-based triggers 2 days ago, still no luck!

答: The documentation says that pageSize defaults to 100. This is not the case. If you specify the pageSize parameter, it returns a response with photos.

Body:
I'm trying to make an HTTP GET request to the Google Street View Publish API, inside a Google Apps Script script, to fetch the photos list and save metadata about them to a Google spreadsheet.

The code I'm using on the script to contact the API:

var url = 'https://streetviewpublish.googleapis.com/v1/photos?fields=nextPageToken%2Cphotos&key=' + API_KEY;

var response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    headers: {
        //the accessToken is borrowed from the Apps Script Infrastructure `ScriptApp.getOAuthToken()`
        //source: https://www.youtube.com/watch?v=aP6pxK3jexc
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
    }
});
console.log('API response:\n' + response);

And including the Street View Auth at the script's manifest oauthscopes.json file:

...
"oauthScopes": [
  "https://www.googleapis.com/auth/streetviewpublish",
  "https://www.googleapis.com/auth/script.external_request",
  "https://www.googleapis.com/auth/spreadsheets"
]
...

Been using a time-based trigger to run the script every 15 min, and it has been working just fine for couple of hours and returning a JSON object with the photos on the account, until the API stopped to return a response, and it's now just returning an empty JSON object {}.

I don't think I consumed the quote for the API usage, my numbers from the GCP dashboard as follows:

Tried to create another API KEY and use it at the script, but still no luck.

Also, when tried to test the API from the Google APIs Explorer, authorize and execute, it gives me the response code 200 with an empty JSON object as well.
This has been working before, but, now it doesn't!

What might be the problem here?

Edit:

As suggested at the comments, I tried to:

Call the API endpoint with or without the API key and the other parameters, as follows:

https://streetviewpublish.googleapis.com/v1/photos?fields=nextPageToken%2Cphotos&key=' + API_KEY

https://streetviewpublish.googleapis.com/v1/photos?key=' + API_KEY

https://streetviewpublish.googleapis.com/v1/photos

Also, tried to revoke the access for both the Google APIs Explorer and the script on Google Apps Script, from the account security checkup. Which because of it when tried to run it again, it opened a popup window to ask for the authorization/permission again, which I granted as well.

Tried to log out of the Google account & clearing the browser's cache.

Yet, still, the same empty JSON object response!

Edit 2:

Also stopped the script's time-based triggers 2 days ago, still no luck!


问:
Safari fires StorageEvent in same tab
I am experiencing a strange issue in Safari (Version 13.1).

Use case: I am synchronizing data between various open tabs. This is implemented by writing to local storage and listening to the "storage" event.

According my understanding (and MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event), the storage event should be fired when something is written to local storage and two conditions are fulfilled:

the value for the item has changed

this change is originating from the same domain, but a different document (i.e. other tab/window)

In other words:

Let's say I have two open tabs (A and B)

Both listen for changes to "storage"

One of the tabs (A)  writes something to local storage

Only the other tab (B) should receive the "storage" event

This works perfectly fine in Chrome, Firefox & Opera. But in Safari it is fired within the same tab as well.

This code will replicate this (works on any site in the console):

window.addEventListener('storage', event => console.log(event));
window.localStorage.setItem('foo', 'bar');
```

In Chrome/Firefox/Opera nothing will be logged (expected behavior)

In Safari, a storage event will be logged in the same window

In addition, the event itself does not seem to have sufficient information to identify which tab has triggered it. I am pondering to write another helper with a unique key per open tab and write that to local storage and listen for changes to it. But before I do that I wanted to see if I am missing something. I know there are some libraries to message other tabs, but I am reluctant to introduce a dedicated library for something as basic as this.

Question: Am I missing something? Is there a way to let the storage event in Safari only fire when something is written from other tabs?

答:
This also happens on IE11, as described here and here. The solution is to check, whether your current tab is in focus, as described here.

So, in your code:

```<code>function handler (event) {
  if (!document.hasFocus()) {
    // continue with your logic
  }
}
window.addEventListener('storage', handler);
</code>```

I'd also suggest to handle the IE issue, in case your app needs it, as described in the above answers. You can do that by detecting the browser and enhancing the above logic.

Title: Safari fires StorageEvent in same tab

Body:
I am experiencing a strange issue in Safari (Version 13.1).

Use case: I am synchronizing data between various open tabs. This is implemented by writing to local storage and listening to the "storage" event.

According my understanding (and MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event), the storage event should be fired when something is written to local storage and two conditions are fulfilled:

the value for the item has changed

this change is originating from the same domain, but a different document (i.e. other tab/window)

In other words:

Let's say I have two open tabs (A and B)

Both listen for changes to "storage"

One of the tabs (A)  writes something to local storage

Only the other tab (B) should receive the "storage" event

This works perfectly fine in Chrome, Firefox & Opera. But in Safari it is fired within the same tab as well.

This code will replicate this (works on any site in the console):

window.addEventListener('storage', event => console.log(event));
window.localStorage.setItem('foo', 'bar');

In Chrome/Firefox/Opera nothing will be logged (expected behavior)

In Safari, a storage event will be logged in the same window

In addition, the event itself does not seem to have sufficient information to identify which tab has triggered it. I am pondering to write another helper with a unique key per open tab and write that to local storage and listen for changes to it. But before I do that I wanted to see if I am missing something. I know there are some libraries to message other tabs, but I am reluctant to introduce a dedicated library for something as basic as this.

Question: Am I missing something? Is there a way to let the storage event in Safari only fire when something is written from other tabs?

Body:
This also happens on IE11, as described here and here. The solution is to check, whether your current tab is in focus, as described here.

So, in your code:

function handler (event) {
  if (!document.hasFocus()) {
    // continue with your logic
  }
}
window.addEventListener('storage', handler);

I'd also suggest to handle the IE issue, in case your app needs it, as described in the above answers. You can do that by detecting the browser and enhancing the above logic.


问:
Cannot read File from fs with FileReader
Hi i am trying to read a file and i am having trouble with the fileReader readAsArrayBuffer function in nodejs.

```<code>var FileReader = require("filereader");

let p12_path = __dirname + "/file.p12";

var p12xxx = fs.readFileSync(p12_path, "utf-8");

var reader = new FileReader();

reader.readAsArrayBuffer(p12xxx);//The problem is here
reader.onloadend = function() {
  arrayBuffer = reader.result;
  var arrayUint8 = new Uint8Array(arrayBuffer);
  var p12B64 = forge.util.binary.base64.encode(arrayUint8);
  var p12Der = forge.util.decode64(p12B64);
  var p12Asn1 = forge.asn1.fromDer(p12Der);

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

-------The error

```<code>Error: cannot read as File: "0�6�\.............
</code>```

答:
According to the npm filereader Doc, the reader created with fs.readFileSync(p12_path, "utf-8"); needs to  get a path of a file in the utf-8 encoding, otherwise it cannot read it.

The printed out "0�6�\............. shows the file is obviously not in utf8 and therefor not readable.

Body:
Hi i am trying to read a file and i am having trouble with the fileReader readAsArrayBuffer function in nodejs.

var FileReader = require("filereader");

let p12_path = __dirname + "/file.p12";

var p12xxx = fs.readFileSync(p12_path, "utf-8");

var reader = new FileReader();

reader.readAsArrayBuffer(p12xxx);//The problem is here
reader.onloadend = function() {
  arrayBuffer = reader.result;
  var arrayUint8 = new Uint8Array(arrayBuffer);
  var p12B64 = forge.util.binary.base64.encode(arrayUint8);
  var p12Der = forge.util.decode64(p12B64);
  var p12Asn1 = forge.asn1.fromDer(p12Der);

  ............
}

-------The error

Error: cannot read as File: "0�6�\.............


问:
SQL injection login bypass
I am preparing SQL injection vulnerable page to test skills, here is my code:

```<code><?php
    echo "<center><h1>Login Bypass</h1></center>";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "<center>".$query_string."</center><br/>";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "<center>SUCCESS</center><br/>";
    else echo "<center>ACCESS DENIED</center><br/>";
    echo "<center>".$row['email']."</center><br/>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <center>
    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>
    </center>
</body>

</html>
</code>```

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

```<code>$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
</code>```

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

```<code>SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '
</code>```

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

答:
you don't close your comment.  Try </p>

<p>"agajan' ; --"</p>

```<code>SELECT *
  FROM users
 WHERE username = 'agajan'; --  ' AND password = ' '
</code>```

Title: SQL injection login bypass

Body:
I am preparing SQL injection vulnerable page to test skills, here is my code:

<?php
    echo "
Login Bypass
";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "".$query_string."
";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "SUCCESS
";
    else echo "ACCESS DENIED
";
    echo "".$row['email']."
";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

Body:
you don't close your comment.  Try

"agajan' ; --"

SELECT *
  FROM users
 WHERE username = 'agajan'; --  ' AND password = ' '


问:
Appstoreconnect API: Testflight's What To Test
I'm trying to update the so called "What To Test" field for an app already uploaded to Testflight, by the Appstoreconnect API introduced during WWDC 2018.

First of all I've got my jwt token using the jwt.rb script shown during the video "Session 303 - Automating Appstoreconnect", presented during WWDC 2018.

That's my BASH shell:

```<code>TOKEN=$(ruby jwt.rb)
</code>```

Then I'm not even able to get the "What To Test" attribute by the API. I'm only able to see some beta details like those:

```<code>curl "https://api.appstoreconnect.apple.com/v1/builds/<id>/buildBetaDetail" --Header "Authorization Bearer:$TOKEN"

{
  "data" : {
    "type" : "buildBetaDetails",
    "id" : "<id>",
    "attributes" : {
      "autoNotifyEnabled" : true,
      "internalBuildState" : "IN_BETA_TESTING",
      "externalBuildState" : "IN_BETA_TESTING"
    },
    "relationships" : {
      "build" : {
        "links" : {
          "self" : "https://api.appstoreconnect.apple.com/v1/buildBetaDetails/<id>/relationships/build",
          "related" : "https://api.appstoreconnect.apple.com/v1/buildBetaDetails/<id>/build"
        }
      }
    },
    "links" : {
      "self" : "https://api.appstoreconnect.apple.com/v1/<id>"
    }
  },
  "links" : {
    "self" : "https://api.appstoreconnect.apple.com/v1/builds/<id>/buildBetaDetail"
  }
}
</code>```

Which is the HTTP GET I should perform in order to collect What To Test Testflight data for a given ?

Afterwhards, which would be the HTTP PATCH I should perform in order to update it ?

答:
The "what to test" text is localized so it has multiple values. You can find this data in the "whatsNew" attribute of the "betaBuildLocalizations". Use this URL to all build localizations:

GET/v1/builds/:id/betaBuildLocalizations

And use this to edit:

PATCH /v1/betaBuildLocalizations/:id

Body:
I'm trying to update the so called "What To Test" field for an app already uploaded to Testflight, by the Appstoreconnect API introduced during WWDC 2018.

First of all I've got my jwt token using the jwt.rb script shown during the video "Session 303 - Automating Appstoreconnect", presented during WWDC 2018.

That's my BASH shell:

TOKEN=$(ruby jwt.rb)

Then I'm not even able to get the "What To Test" attribute by the API. I'm only able to see some beta details like those:

curl "https://api.appstoreconnect.apple.com/v1/builds/<id>/buildBetaDetail" --Header "Authorization Bearer:$TOKEN"

{
  "data" : {
    "type" : "buildBetaDetails",
    "id" : "<id>",
    "attributes" : {
      "autoNotifyEnabled" : true,
      "internalBuildState" : "IN_BETA_TESTING",
      "externalBuildState" : "IN_BETA_TESTING"
    },
    "relationships" : {
      "build" : {
        "links" : {
          "self" : "https://api.appstoreconnect.apple.com/v1/buildBetaDetails/<id>/relationships/build",
          "related" : "https://api.appstoreconnect.apple.com/v1/buildBetaDetails/<id>/build"
        }
      }
    },
    "links" : {
      "self" : "https://api.appstoreconnect.apple.com/v1/<id>"
    }
  },
  "links" : {
    "self" : "https://api.appstoreconnect.apple.com/v1/builds/<id>/buildBetaDetail"
  }
}

Which is the HTTP GET I should perform in order to collect What To Test Testflight data for a given ?

Afterwhards, which would be the HTTP PATCH I should perform in order to update it ?


问:
SQL query data that appears for consecutive years
I have tried several times to figure this out but no luck.

I have one table that I am trying to query.

InvNo (primary key),
CustID,
InvAmt,
DatePD

I want to pull all of the customers that have paid at least one invoice for 3 consecutive fiscal years. Fiscal year for this example is Aug 1 to Jul 31 of the following year. Thie InvNo is unique but the custID can appear multiple times depending on how many invoices they have paid. Can anyone help me with this?

For output I need one record per custID and how many consecutive years that CustID has paid an invoice.

CustID 333   ConsecutiveYears 7

答:
You can get the year by either subtracting 8 months or adding four months and extracting the year.  Then, lag() can solve the problem:

```<code>select distinct custid
from (select t.*, lag(yyyy, 2) over (partition by custid order by yyyy) as prev_yyyy_2
      from (select distinct custid, year(dateadd(month, -8, datepd)) as yyyy
            from t
           ) t
     ) t
where prev_yyyy_2 = yyyy - 2;
</code>```

The innermost subquery just gets pairs of customers and year.  The lag() looks two rows behind.  Three years are present if "2 rows behind" is exactly 2 years ago.

Body:
You can get the year by either subtracting 8 months or adding four months and extracting the year.  Then, lag() can solve the problem:

select distinct custid
from (select t.*, lag(yyyy, 2) over (partition by custid order by yyyy) as prev_yyyy_2
      from (select distinct custid, year(dateadd(month, -8, datepd)) as yyyy
            from t
           ) t
     ) t
where prev_yyyy_2 = yyyy - 2;

The innermost subquery just gets pairs of customers and year.  The lag() looks two rows behind.  Three years are present if "2 rows behind" is exactly 2 years ago.


问:
Javascript: How to make sense of all the frameworks and design philosophies?
I have been a user of jQuery (and some of its minor plugins) for a while. The Javascript code I've developed over the years could be described best as... messy. It used a ton of global variables and functions here and there, didn't use standard ways of organizing the code, nor any design patterns whatsoever.

I am currently building the new version of a website, and I have completed doing the backend with PEAR::MDB2 and Smarty templates. The rest is just homebrew PHP with some classes.

Now I am at the point where I'll add the Javascript layer on top of the website to improve the user-friendliness of some features. (while making sure everything degrades gracefully) I want to write better, cleaner, more organized Javascript than I used to, so I did a little research. I read Stefanov's Object-Oriented Javascript to have a better grasp on some concepts I knew only loosely about (prototypes, constructors, etc.) as well. Now I'm stuck at a point where I wonder which Javascript frameworks I should use, and how to organize it all.

After conducting my research, I understood Cappuccino & Objective-J, and Sproutcore were not what I was looking for. To quote Cappucino's about page:

Cappuccino is not designed for building web sites, or making existing sites more "dynamic". We think these goals are too far removed from those of application development to be served well by a single framework. Projects like Prototype and jQuery are excellent at those tasks

So there's that. Then I found out about Coffee Script, which is more of a one-to-one "compiler" and wouldn't help me with the actual organization of my code.

I also stumbled on some articles that give guidelines:

Using Inheritance Patterns to Organize Large jQuery Applications

A JavaScript Module Pattern

I also found out about Backbone.js, Shoestring, JavaScriptMVC, Google Loader, jQuery Tools, jQuery UI. I don't really know what to do of all this... The things I know:

I don't want to invest too much time in learning something too complex, I want to keep things simple and flexible as much as possible (that is why I don't use Symfony on the backend, for example), yet clean and organized.

I want to use jQuery, the question is, what should I use with it? (that is compatible too)

Right now, I'd use jQuery and jQuery Tools and "organize" all that in a simple namespace/object literal with simple properties and methods and also, since the site is localized, I just plan on using the simple vsprintf (as I do on the backend) with key:value pairs loaded from an object literal provided by the backend. JavaScriptMVC seems interesting, but I fear it would bring way too much complexity for a project that is fairly small sized. That is where I need your advice! Thank you very much in advance.

答: You should watch the video and read the links in this article and then you should ask yourself again if jquery is the right tool. Maybe you will use dojo, that is much better for larger projects or you take a look at backbone and where you can stay with jquery. After all both of them are more "javascriptish" then something like sproutcore, cappuciono or even GWT. And also much easier to understand when you come from jquery.</p>