问:
Can I use closest() function in JavaScript?
I am trying to use the closest() function to delete a row from a table, but I am encountering an error.

Call function:<button onclick="validarIntervencao(1)">test</button>

function validarIntervencao(id) {
  var element = this;

  $.confirm({
    title: 'Confirmação!',
    content: "Quer mesmo validar a intervenção nº" + id + "? Esta ação envia o relatório ao cliente.",
    buttons: {
      Confirmar: {
        text: 'Confirmar',
        btnClass: 'btn btn-success',
        action: function() {
          $.ajax({
            url: base_url + "intervencoes/validarIntervencao/" + id,
            success: function(data) {

              if (data == false) {
                $.confirm({
                  title: 'Atenção!',
                  content: "Verifique a descrição e o relatório.",
                  buttons: {
                    Ok: {
                      text: 'Ok',
                      btnClass: 'btn btn-success'
                    }
                  }
                });
              } else {
                element.closest('tr').remove();
              }
            },
            error: function() {
              alert('Erro!');
            }
          });
        }
      },
      Cancelar: {
        text: 'Cancelar',
        btnClass: 'btn btn-danger'
      }
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="intervencoesTable" width="100%">
<thead>
<tr>
    <th>Teste</th>
    <th>Ações</th>
</tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>
            <button onclick="validarIntervencao(1)" id="validaBTN1">test</button>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>
            <button onclick="validarIntervencao(2)" id="validaBTN2">test</button>
        </td>
    </tr>
</tbody>
</table></code>```

I'm getting this error in console:

TypeError: element.closest is not a function

Can I use the closest() function inside a JavaScript function? Is there any alternative?

答:
You state in the comment that you're calling this function from an inline onclick attribute. This is the problem.

When invoked in this manner this within the function will refer to the window, which has no closest() method, as it's the top level object in the DOM.

To fix this issue, and improve the quality of your code, remove the onclick attribute and  invoke your logic from an unobtrusive event handler. The handler function will run under the scope of the element which raised the event, so this will work as you expect it to. Try this:

document.querySelector('table').addEventListener('click', function(e) {
  if (e.target.classList.contains('delete')) {
    // $.confirm( ...
    var button = e.target;
    button.closest('tr').remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>Row 1</td>
    <td><button class="delete">Delete</button></td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td><button class="delete">Delete</button></td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td><button class="delete">Delete</button></td>
  </tr>
</table></code>```

Body:
I am trying to use the closest() function to delete a row from a table, but I am encountering an error.

Call function:<button onclick="validarIntervencao(1)">test</button>

function validarIntervencao(id) {
  var element = this;

  $.confirm({
    title: 'Confirmação!',
    content: "Quer mesmo validar a intervenção nº" + id + "? Esta ação envia o relatório ao cliente.",
    buttons: {
      Confirmar: {
        text: 'Confirmar',
        btnClass: 'btn btn-success',
        action: function() {
          $.ajax({
            url: base_url + "intervencoes/validarIntervencao/" + id,
            success: function(data) {

              if (data == false) {
                $.confirm({
                  title: 'Atenção!',
                  content: "Verifique a descrição e o relatório.",
                  buttons: {
                    Ok: {
                      text: 'Ok',
                      btnClass: 'btn btn-success'
                    }
                  }
                });
              } else {
                element.closest('tr').remove();
              }
            },
            error: function() {
              alert('Erro!');
            }
          });
        }
      },
      Cancelar: {
        text: 'Cancelar',
        btnClass: 'btn btn-danger'
      }
    }
  });
}

    Teste
    Ações

        1

            <button onclick="validarIntervencao(1)" id="validaBTN1">test</button>

        2

            <button onclick="validarIntervencao(2)" id="validaBTN2">test</button>

I'm getting this error in console:

TypeError: element.closest is not a function

Can I use the closest() function inside a JavaScript function? Is there any alternative?

Body:
You state in the comment that you're calling this function from an inline onclick attribute. This is the problem.

When invoked in this manner this within the function will refer to the window, which has no closest() method, as it's the top level object in the DOM.

To fix this issue, and improve the quality of your code, remove the onclick attribute and  invoke your logic from an unobtrusive event handler. The handler function will run under the scope of the element which raised the event, so this will work as you expect it to. Try this:

document.querySelector('table').addEventListener('click', function(e) {
  if (e.target.classList.contains('delete')) {
    // $.confirm( ...
    var button = e.target;
    button.closest('tr').remove();
  }
});

<table>
  <tr>
    <td>Row 1</td>
    <td><button class="delete">Delete</button></td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td><button class="delete">Delete</button></td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td><button class="delete">Delete</button></td>
  </tr>
</table>


来源: stackexchange

问:
Simple way to play a sound file (.aif)
I'm making an app for Mac OS X using Xcode, and I want it to play a alert sound when something happens.

What is the simplest code for playing a sound in Objective-C/Cocoa? Note that my sound file is an .aif.

Also, where do I put the sound file inside my project?

Thank you.

答:
You can copy and add your .aif files to your project in Xcode as follows:

Command-click on the Classes folder (from within xCode)

Select Add > Existing Files

Navigate to the directory containing your .aif and select it(them). Click Add.
(optional: Check the “Copy items” checkbox & Click Add.)

See Apple's examples & great info: here & here.

ContentLicense: CC BY-SA 3.0

Title: Simple way to play a sound file (.aif)


问:
How to control interval in rxjs? - inactivate timer in angular
I try to implement a kind of "session timer" in angular app. It will logout user when (s)he don't click any key in a specified period. Everything goes ok, until first logout. After 2nd login, reset method of timer don't work. The user is logged out after the specified time, regardless of the action performed.

I made a demo on StackBlitz

Here is code of service:

```<code>@Injectable({
  providedIn: "root"
})
export class SessionTimerService {
  private readonly sessionTimer: Observable<number> = interval(10000); // 10 sec
  private sessionTimerController: Subject<void>;

  public constructor(private readonly router: Router) {}

  public initTimer(): void {
    this.sessionTimerController = new Subject<void>();
    this.sessionTimer
      .pipe(
        take(1),
        takeUntil(this.sessionTimerController)
      )
      .subscribe(() => {
        console.log("logout");
        this.sessionTimerController.next();
        this.sessionTimerController.complete();
        this.router.navigate(["/login"]);
      });
  }

  public resetTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("reset");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();

      this.initTimer();
    }
  }

  public stopTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("stop");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();
    }
  }
}
</code>```

window.relaod() is not good answer on this problem.

答:
The problem is that you're creating two independent timers when you logging the second time because on first login is this.sessionTimerController === null and you check this condition:

inside onMouseMove.

inside MainComponent's constructor.

Second problem is that method initTimer() doesn't check if there's already a timer going:

So before creating a new timer you can complete the previous one so you know there will be always just one:

```<code>private sessionTimerController: Subject<void> = new Subject<void>();

...

public initTimer(): void {
  console.log('initTimer');

  this.sessionTimerController.next();
  this.sessionTimerController.complete();
  this.sessionTimerController = new Subject<void>();
  ...
</code>```

Live demo: https://stackblitz.com/edit/angular-session-timer-yqdxco?file=src/app/session-timer.service.ts

In my opinion in your use-case it would be easier to get rid of the Subject completely because it's just making things complicated and use a single Subscription object to cancel any previous timers.

ContentLicense: CC BY-SA 4.0

Body:
I try to implement a kind of "session timer" in angular app. It will logout user when (s)he don't click any key in a specified period. Everything goes ok, until first logout. After 2nd login, reset method of timer don't work. The user is logged out after the specified time, regardless of the action performed.

I made a demo on StackBlitz

Here is code of service:

@Injectable({
  providedIn: "root"
})
export class SessionTimerService {
  private readonly sessionTimer: Observable<number> = interval(10000); // 10 sec
  private sessionTimerController: Subject<void>;

  public constructor(private readonly router: Router) {}

  public initTimer(): void {
    this.sessionTimerController = new Subject<void>();
    this.sessionTimer
      .pipe(
        take(1),
        takeUntil(this.sessionTimerController)
      )
      .subscribe(() => {
        console.log("logout");
        this.sessionTimerController.next();
        this.sessionTimerController.complete();
        this.router.navigate(["/login"]);
      });
  }

  public resetTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("reset");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();

      this.initTimer();
    }
  }

  public stopTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("stop");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();
    }
  }
}

window.relaod() is not good answer on this problem.

Body:
The problem is that you're creating two independent timers when you logging the second time because on first login is this.sessionTimerController === null and you check this condition:

inside onMouseMove.

inside MainComponent's constructor.

Second problem is that method initTimer() doesn't check if there's already a timer going:

So before creating a new timer you can complete the previous one so you know there will be always just one:

private sessionTimerController: Subject<void> = new Subject<void>();

...

public initTimer(): void {
  console.log('initTimer');

  this.sessionTimerController.next();
  this.sessionTimerController.complete();
  this.sessionTimerController = new Subject<void>();
  ...

Live demo: https://stackblitz.com/edit/angular-session-timer-yqdxco?file=src/app/session-timer.service.ts

In my opinion in your use-case it would be easier to get rid of the Subject completely because it's just making things complicated and use a single Subscription object to cancel any previous timers.


问:
Why promis only works in the last variable?
Why "then" in var test1 not show 1111111? But if just use resolve(); work fine. What wrong? How to do multiple promise requests at the same time?

window.testFunc = function() {

  let _self = this;

  this.test = function() {
    _self.resolve();
  };

  return new Promise(function(resolve, reject) {

    _self.resolve = resolve;
    _self.reject = reject;

    //this work fine
    //resolve();

    //this not work
    setTimeout(function() {
      _self.test();
    }, 300);
  });

};

let test1 = window.testFunc();
let test2 = window.testFunc();

test1.then(function(value) {
  console.log(111111);
});
test2.then(function(value) {
  console.log(222222);
});```

答:
this has the same value each time you call window.testFunc, so _self.test is the same property (which gets overwritten each time).

Use a local variable with a new object (let _self = {};) instead of a shared object.

window.testFunc = function() {

    let _self = {};

    _self.test = function () {
        _self.resolve();
    };

    return new Promise(function (resolve, reject) {

        _self.resolve = resolve;
        _self.reject = reject;

        //this work fine
        //resolve();

        //this not work
        setTimeout(function(){
            _self.test();
        }, 300);
    });

};

let test1 = window.testFunc();
let test2 = window.testFunc();

test1.then(function(value){
    console.log(111111);
});
test2.then(function(value){
    console.log(222222);
});```


问:
Search a string in complete MS Access database
I want to search a string in whole MS Access database. How can I do this?</p>

答: If you're talking about searching for the names of reports, queries, tables, modules, etc in your Access file, then try SpeedFerret</p>


问:
How to disable ipython prompt blinking?
When I run ipython (7.12.0, this is from the Anaconda distro) in an xterm, the In prompts blink. It's super irritating. How do I turn it off?

The only thing that blinks is the text of the input prompt "In [#]:' at the beginning of every ipython input line. Nothing else in the terminal window blinks. To be specific, I am not asking about the cursor. The cursor is not blinking.

Note, there is a previous question, How to disable ipython prompt blinking?, that purports to answer this exact question. However, it is out-of-date. The answer given there doesn't work. Also, I suspect the answer was meant for the jupyter notebook. I'm asking about the terminal version of ipython.

答:
The blinking cursor is a feature of the terminal itself.
If you are using XTerm, you can disable the cursor:

```<code>setterm -cursor off
</code>```

You can re-enable it with:

```<code>setterm -cursor on
</code>```

Title: How to disable ipython prompt blinking?

Body:
The blinking cursor is a feature of the terminal itself.
If you are using XTerm, you can disable the cursor:

setterm -cursor off

You can re-enable it with:

setterm -cursor on


问:
How to split string vector by first desired symbol in R?
Here is an example.

```<code>library(tidyverse)
df<-data.frame(x=c("a-b-c", "b-d","c-d_e-f"))
df
#        x
#1   a-b-c
#2     b-d
#3 c-d_e-f
</code>```

What I wanted is to separate the column x by the first -, thus a desired output would be:

```<code>  x     y
1 a   b-c
2 b     d
3 c d_e-f
</code>```

答:
We can use extract

```<code>library(tidyr)
library(dplyr)
df %>%
    extract(x, into = c('x', 'y'), '^([^-])+-(.*)')
</code>```

Or with separate with making use of extra

```<code>df %>%
    separate(x, into = c('x', 'y'), '-', extra = 'merge')
#   x     y
#1 a   b-c
#2 b     d
#3 c d_e-f
</code>```

Body:
Here is an example.

library(tidyverse)
df<-data.frame(x=c("a-b-c", "b-d","c-d_e-f"))
df
#        x
#1   a-b-c
#2     b-d
#3 c-d_e-f

What I wanted is to separate the column x by the first -, thus a desired output would be:

  x     y
1 a   b-c
2 b     d
3 c d_e-f

Body:
We can use extract

library(tidyr)
library(dplyr)
df %>%
    extract(x, into = c('x', 'y'), '^([^-])+-(.*)')

Or with separate with making use of extra

df %>%
    separate(x, into = c('x', 'y'), '-', extra = 'merge')
#   x     y
#1 a   b-c
#2 b     d
#3 c d_e-f


问:
Typescript: what is the best way to copy *some* (not all) properties from one class instance to another object?
Suppose I have a Typescript class like the following:

```<code>class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}
</code>```

I create an instance of the class:

```<code>const myInstance = new MyClass(true, 'hi', 45);
</code>```

If I want to copy the values of only the properties x and z to another object, I could do the following:

```<code>const myInstance = new MyClass(true, 'hi', 45);
const { x, z } = myInstance;
const myObject = { x, z };
</code>```

Is there any better (and simple) way of achieving this?

Or is this the simplest way?

Note, the above example class is small. Imagine if the class has, say, 20 properties, and I want to get only 5 of them.

It would be good to see a generic solution to the problem.

答:
Just pass the values you need:

const myInstance = new MyClass(true, 'hi', 45);
const myObject = { x: myInstance.x, z: myInstance.z };
```

Body:
Suppose I have a Typescript class like the following:

class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

I create an instance of the class:

const myInstance = new MyClass(true, 'hi', 45);

If I want to copy the values of only the properties x and z to another object, I could do the following:

const myInstance = new MyClass(true, 'hi', 45);
const { x, z } = myInstance;
const myObject = { x, z };

Is there any better (and simple) way of achieving this?

Or is this the simplest way?

Note, the above example class is small. Imagine if the class has, say, 20 properties, and I want to get only 5 of them.

It would be good to see a generic solution to the problem.


问:
How to override getitem method with indexing based on numpy ndarray?
I am trying to build a class based on numpy.ndarray which __getitem__ and __setitem__ methods provide data based on indexing like this Point class:

```<code>import numpy as np

class Point:
    def __init__(self, number=20):
        dt = np.dtype([("x",np.float64), ("y",np.float64), ("alive",np.bool)])
        self.points = np.zeros((int(number),1), dtype=dt)
        self.points["alive"] = True

#    def __getitem__(self, i):
#        mask = self.points["alive"] == True
#        print("get")
#        return self.points[mask].__getitem__(i)

    def __getitem__(self, i):
        mask = self.points["alive"] == True
        print("get")
        return self.points[mask][i]

    def __setitem__(self, i, item):
        mask = self.points["alive"] == True
        print("set")
        self.points[mask][i] = item
</code>```

And if I try:

```<code>p = Point()
print(p[0])
>>>>get
>>>>(0., 0., True)
print(p[0]["alive"])
>>>>get
>>>>True
p[0]["alive"] = False
>>>>get
print(p.points[0]["alive"])
>>>>[ True]
</code>```

So the modification is not taken into account, but I got no error, like I was modifying a copy. Also I am confused because I am not calling the __setitem__ method but the __getitem__ method. I tried another implementation using the __getitem__ of the ndarray but there is the same problem.

What am I doing wrong and how to do this properly ?

答:
I found how to do it using pandas which allows to do this without chained indexing and get a view of the array instead of a copy:

```<code>import numpy as np
import pandas as pd

class Point:
    def __init__(self, number=20):
        d = {"x":np.zeros((int(number),)), "y":np.zeros((int(number),))}
        self.points = pd.DataFrame(d)
        self.alive = pd.Series(np.ones((int(number),),dtype=bool))

    def __getitem__(self, i):
        return self.points.loc[self.alive,i]

    def __setitem__(self, i, item):
        self.points.loc[self.alive,i] = item
</code>```

Which gives the correct behaviour:

```<code>p = Point(3)
print(p[:])

>>>>     x    y
>>>> 0  0.0  0.0
>>>> 1  0.0  0.0
>>>> 2  0.0  0.0

p.alive[0] = False
print(p[:])

>>>>     x    y
>>>> 1  0.0  0.0
>>>> 2  0.0  0.0

p["x"] = p["x"] + 5
print(p[:])

>>>>     x    y
>>>> 1  5.0  0.0
>>>> 2  5.0  0.0

</code>```

Body:
I am trying to build a class based on numpy.ndarray which __getitem__ and __setitem__ methods provide data based on indexing like this Point class:

import numpy as np

class Point:
    def __init__(self, number=20):
        dt = np.dtype([("x",np.float64), ("y",np.float64), ("alive",np.bool)])
        self.points = np.zeros((int(number),1), dtype=dt)
        self.points["alive"] = True

#    def __getitem__(self, i):
#        mask = self.points["alive"] == True
#        print("get")
#        return self.points[mask].__getitem__(i)

    def __getitem__(self, i):
        mask = self.points["alive"] == True
        print("get")
        return self.points[mask][i]

    def __setitem__(self, i, item):
        mask = self.points["alive"] == True
        print("set")
        self.points[mask][i] = item

And if I try:

p = Point()
print(p[0])
>>>>get
>>>>(0., 0., True)
print(p[0]["alive"])
>>>>get
>>>>True
p[0]["alive"] = False
>>>>get
print(p.points[0]["alive"])
>>>>[ True]

So the modification is not taken into account, but I got no error, like I was modifying a copy. Also I am confused because I am not calling the __setitem__ method but the __getitem__ method. I tried another implementation using the __getitem__ of the ndarray but there is the same problem.

What am I doing wrong and how to do this properly ?

Body:
I found how to do it using pandas which allows to do this without chained indexing and get a view of the array instead of a copy:

import numpy as np
import pandas as pd

class Point:
    def __init__(self, number=20):
        d = {"x":np.zeros((int(number),)), "y":np.zeros((int(number),))}
        self.points = pd.DataFrame(d)
        self.alive = pd.Series(np.ones((int(number),),dtype=bool))

    def __getitem__(self, i):
        return self.points.loc[self.alive,i]

    def __setitem__(self, i, item):
        self.points.loc[self.alive,i] = item

Which gives the correct behaviour:

p = Point(3)
print(p[:])

>>>>     x    y
>>>> 0  0.0  0.0
>>>> 1  0.0  0.0
>>>> 2  0.0  0.0

p.alive[0] = False
print(p[:])

>>>>     x    y
>>>> 1  0.0  0.0
>>>> 2  0.0  0.0

p["x"] = p["x"] + 5
print(p[:])

>>>>     x    y
>>>> 1  5.0  0.0
>>>> 2  5.0  0.0


问:
Why can't I get a simple Combobox to work in EXTjs 4 using a JSONStore?
This is driving me insane.  I have a JS file that is:

```<code>  Ext.onReady(function(){
     Ext.QuickTips.init();

     var SitesStore = new Ext.data.JsonStore({
        autoLoad: true,
        fields: [{
           name: 'id',
           mapping: 'id'
        }, {
           name: 'name',
           mapping: 'name'
        }],
        proxy: {
           type: 'ajax',
           url : '/sites/getsites.do'
        },
        storeId: 'SitesStore',
        root: 'sites',
        url: '/sites/getsites.do',
        xtype: 'jsonstore'
     });

     SitesStore.load(function(data){
        Ext.create('Ext.form.ComboBox', {
           fieldLabel: 'Choose Site...',
           store: SitesStore,
           data: data[0].raw["sites"],
           queryMode: 'remote',
           displayField: 'name',
           valueField: 'id',
           renderTo: "timesheetSearch"
        });

        console.log(data[0].raw["sites"]);
     });

  }); //end onReady
</code>```

My /sites/getsites.do returns JSON data in the following format:

```<code>{
    -sites: [
        -{
            id: "12345678"
            name: "Blah Warehouse"
        },
        -{
            id: "5999B91DF6C0"
            name: "WalMart Warehouse"
        },
        ...
}
</code>```

I realize the data[0].raw["sites"] probably isn't the preferred way to access the data but I do confirm that the data is being populated and I'm getting back 136 sites.

The combobox DOES render.  However, the live search doesn't work and there are no entries.

I'm new to ExtJS.

Any tips would be appreciated.

Thanks

UPDATE

This code WORKS

```<code>var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    data: [{'id':'aaaa', 'name':'Honeywell'}],
    storeId: 'SitesStore',
    root: 'sites'
});

Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose Site...',
    store: SitesStore,
    queryMode: 'remote',
    displayField: 'name',
    triggerAction: 'all',
    valueField: 'id',
    renderTo: "timesheetSearch"
});
</code>```

This does NOT

```<code>var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    proxy: {
        type: 'ajax',
        url: '/sites/getsites.do'
    },
    storeId: 'SitesStore',
    root: 'sites'
});

Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose Site...',
    store: SitesStore,
    queryMode: 'remote',
    displayField: 'name',
    triggerAction: 'all',
    valueField: 'id',
    renderTo: "timesheetSearch"
});
</code>```

When I run it without a proxy (and specify a url) I get an error saying I didn't specify a proxy.

Thanks

UPDATE

UGH!!!!!!

I got it.  Here is the correct JSONStore

```<code>var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    proxy: {
        type: 'ajax',
        url: '/sites/getsites.do',
        reader: {
            type:'json',
            root: 'sites'
        }
    },
    storeId: 'SitesStore',
    root: 'sites'
});
</code>```

Thanks everyone.  Couldn't believe how hard this was.  Mainly because I couldn't find a good tutorial.  lol

答:
UPDATE

I was able to figure this out.  Here is the working code:

```<code>var SitesStore = Ext.create('Ext.data.Store', {
     autoLoad: true,
     fields: ['id','name'],
     proxy: {
        type: 'ajax',
        url: '/sites/getsites.do',
        reader: {
           type:'json',
           root: 'sites'
        }
     },
     storeId: 'SitesStore',
     root: 'sites'
  });

  Ext.create('Ext.form.ComboBox', {
     fieldLabel: 'Choose Site...',
     store: SitesStore,
     queryMode: 'remote',
     displayField: 'name',
     triggerAction: 'all',
     valueField: 'id',
     renderTo: "timesheetSearch"
  });
</code>```

I never could get JSONStore to work so I created a standard Store and had to match the reader attribute with my JSON data.

Hope this helps someone.

Body:
This is driving me insane.  I have a JS file that is:

  Ext.onReady(function(){
     Ext.QuickTips.init();

     var SitesStore = new Ext.data.JsonStore({
        autoLoad: true,
        fields: [{
           name: 'id',
           mapping: 'id'
        }, {
           name: 'name',
           mapping: 'name'
        }],
        proxy: {
           type: 'ajax',
           url : '/sites/getsites.do'
        },
        storeId: 'SitesStore',
        root: 'sites',
        url: '/sites/getsites.do',
        xtype: 'jsonstore'
     });

     SitesStore.load(function(data){
        Ext.create('Ext.form.ComboBox', {
           fieldLabel: 'Choose Site...',
           store: SitesStore,
           data: data[0].raw["sites"],
           queryMode: 'remote',
           displayField: 'name',
           valueField: 'id',
           renderTo: "timesheetSearch"
        });

        console.log(data[0].raw["sites"]);
     });

  }); //end onReady

My /sites/getsites.do returns JSON data in the following format:

{
    -sites: [
        -{
            id: "12345678"
            name: "Blah Warehouse"
        },
        -{
            id: "5999B91DF6C0"
            name: "WalMart Warehouse"
        },
        ...
}

I realize the data[0].raw["sites"] probably isn't the preferred way to access the data but I do confirm that the data is being populated and I'm getting back 136 sites.

The combobox DOES render.  However, the live search doesn't work and there are no entries.

I'm new to ExtJS.

Any tips would be appreciated.

Thanks

UPDATE

This code WORKS

var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    data: [{'id':'aaaa', 'name':'Honeywell'}],
    storeId: 'SitesStore',
    root: 'sites'
});

Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose Site...',
    store: SitesStore,
    queryMode: 'remote',
    displayField: 'name',
    triggerAction: 'all',
    valueField: 'id',
    renderTo: "timesheetSearch"
});

This does NOT

var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    proxy: {
        type: 'ajax',
        url: '/sites/getsites.do'
    },
    storeId: 'SitesStore',
    root: 'sites'
});

Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose Site...',
    store: SitesStore,
    queryMode: 'remote',
    displayField: 'name',
    triggerAction: 'all',
    valueField: 'id',
    renderTo: "timesheetSearch"
});

When I run it without a proxy (and specify a url) I get an error saying I didn't specify a proxy.

Thanks

UPDATE

UGH!!!!!!

I got it.  Here is the correct JSONStore

var SitesStore = Ext.create('Ext.data.Store', {
    autoLoad: true,
    fields: ['id','name'],
    proxy: {
        type: 'ajax',
        url: '/sites/getsites.do',
        reader: {
            type:'json',
            root: 'sites'
        }
    },
    storeId: 'SitesStore',
    root: 'sites'
});

Thanks everyone.  Couldn't believe how hard this was.  Mainly because I couldn't find a good tutorial.  lol

Body:
UPDATE

I was able to figure this out.  Here is the working code:

var SitesStore = Ext.create('Ext.data.Store', {
     autoLoad: true,
     fields: ['id','name'],
     proxy: {
        type: 'ajax',
        url: '/sites/getsites.do',
        reader: {
           type:'json',
           root: 'sites'
        }
     },
     storeId: 'SitesStore',
     root: 'sites'
  });

  Ext.create('Ext.form.ComboBox', {
     fieldLabel: 'Choose Site...',
     store: SitesStore,
     queryMode: 'remote',
     displayField: 'name',
     triggerAction: 'all',
     valueField: 'id',
     renderTo: "timesheetSearch"
  });

I never could get JSONStore to work so I created a standard Store and had to match the reader attribute with my JSON data.

Hope this helps someone.


问:
Center values under others
I have tried to center the value (number + %) under the "Battery L" and "Battery R".
For example:

```<code>Battery L    Battery R
  100%         100%
</code>```

Do you know how can I do?

```<code><View style={{ alignItems: "center" }}>
  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end", marginRight: 20 }}>
      <Text style={{}}>{"Battery R"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text style={{}}>{"Battery L"}</Text>
    </View>
  </View>

  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end" }}>
      <Text>{"100" + " %"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text>{"100" + " %"}</Text>
    </View>
  </View>
</View>
</code>```

Link

答:
You can achieve this using simple style guide as below

```<code><View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
  <View style={{ alignItems: 'center', justifyContent: 'center' }}>
    <Text>{"Battery L"}</Text>
    <Text>{"100" + " %"}</Text>
  </View>
  <View style={{ alignItems: 'center', justifyContent: 'center' }}>
    <Text>{"Battery R"}</Text>
    <Text>{"100" + " %"}</Text>
  </View>
</View>
</code>```

This may not be the optimal solution.

Hope this helps you. Feel free for doubts.

Title: Center values under others

Body:
I have tried to center the value (number + %) under the "Battery L" and "Battery R".
For example:

Battery L    Battery R
  100%         100%

Do you know how can I do?

<View style={{ alignItems: "center" }}>
  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end", marginRight: 20 }}>
      <Text style={{}}>{"Battery R"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text style={{}}>{"Battery L"}</Text>
    </View>
  </View>

  <View style={{ flex: 1, flexDirection: "row" }}>
    <View style={{ justifyContent: "flex-end", alignItems: "flex-end" }}>
      <Text>{"100" + " %"}</Text>
    </View>
    <View style={{ justifyContent: "flex-start", alignItems: "flex-start" }}>
      <Text>{"100" + " %"}</Text>
    </View>
  </View>
</View>

Link

Body:
You can achieve this using simple style guide as below

<View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
  <View style={{ alignItems: 'center', justifyContent: 'center' }}>
    <Text>{"Battery L"}</Text>
    <Text>{"100" + " %"}</Text>
  </View>
  <View style={{ alignItems: 'center', justifyContent: 'center' }}>
    <Text>{"Battery R"}</Text>
    <Text>{"100" + " %"}</Text>
  </View>
</View>

This may not be the optimal solution.

Hope this helps you. Feel free for doubts.


问:
Able to choose future date when setting max date in datepicker
I'm targeting for and building with API level 21, using AppCompat v21.

It gives me a nicely looking new date picker, which has the unexpected property of allowing me to choose a future date when max date has been set using

```<code>datePicker.setMaxDate(Calendar.getInstance().getTimeInMillis())
</code>```

The future dates are greyed out, but I can still choose any one of them. Is that a bug? Am I doing it wrong? Is there a way to prevent the user from being able to pick a future date in the date picker?

The old Holo date picker did not allow picking a future date when setting a maximum date.

UPDATE:

While it is not working properly on my Nexus 4 running stock 5.0, it is working properly on my Nexus 6 running stock Android 5.1.1. Perhaps it was a bug in Android 5.0 and it was fixed in 5.1? Can anyone confirm?

答:
you can work around it on your CSS by finding the right element (with a "disabled" class) and setting a pointer events to none.`</p>

```<code>.bs-datepicker-body table td.disabled {
      pointer-events: none;
}
</code>```

Body:
I'm targeting for and building with API level 21, using AppCompat v21.

It gives me a nicely looking new date picker, which has the unexpected property of allowing me to choose a future date when max date has been set using

datePicker.setMaxDate(Calendar.getInstance().getTimeInMillis())

The future dates are greyed out, but I can still choose any one of them. Is that a bug? Am I doing it wrong? Is there a way to prevent the user from being able to pick a future date in the date picker?

The old Holo date picker did not allow picking a future date when setting a maximum date.

UPDATE:

While it is not working properly on my Nexus 4 running stock 5.0, it is working properly on my Nexus 6 running stock Android 5.1.1. Perhaps it was a bug in Android 5.0 and it was fixed in 5.1? Can anyone confirm?

Body:
you can work around it on your CSS by finding the right element (with a "disabled" class) and setting a pointer events to none.`

.bs-datepicker-body table td.disabled {
      pointer-events: none;
}


问:
Are unit-test names important?
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

```<code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code>```

verse

```<code>[Test]
public void UserNameTestValidation1() {}
</code>```

答:
In Clean Code, page 124, Robert C. Martin writes:

The moral of the story is simple: Test code is just as important as production code. It is not a second-class citizen. It requires thought, design, and care. It must be kept as clean as production code.

OwnerDisplayName: Xian

ContentLicense: CC BY-SA 2.5

Title: Are unit-test names important?

Body:
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

OwnerDisplayName: flipdoubt


问:
How can I change the speed of audio being played? (Using Clip as well as AudioPlayer.player.start()?)
How can I change the speed of audio being played in a Java program (Using Clip as well as AudioPlayer.player.start()?)</p>

答: Increase playback speed of sound file in java</p>


问:
Regex to extract parentheses content
I want a regex to grab the arguments of RegExp without parsing the code.

```<code>RegExp(/a+b/)       Output: /a+b/
RegExp(/a+b/, 'g')  Output: /a+b/, 'g'
</code>```

I have came up with the following regex:

```<code>(?:RegExp)\((.*)\)
</code>```

It works fine for most examples, but fails for some cases (e.g. minified, 1 line JavaScripts, regexs including parentheses):

```<code>RegExp("myregex")                               - capturing group 1: "myregex"
Regexp("something"); myfunction("something")    - capturing group 1: "something"); myfunction("something"
RegExp("my(regex)")                             - capturing group 1: "my(regex
</code>```

This is clearly due to finding a matching closing parenthesis. Is there a workaround for this?

答:
Try this RegEx:

```<code>/.*RegExp\((\"(?:.+?)\"|\/(?:.+?)\/.*)\).*/gmi
</code>```

Review and test it out here: https://regex101.com/r/cReoV7/6

Title: Regex to extract parentheses content

Body:
I want a regex to grab the arguments of RegExp without parsing the code.

RegExp(/a+b/)       Output: /a+b/
RegExp(/a+b/, 'g')  Output: /a+b/, 'g'

I have came up with the following regex:

(?:RegExp)\((.*)\)

It works fine for most examples, but fails for some cases (e.g. minified, 1 line JavaScripts, regexs including parentheses):

RegExp("myregex")                               - capturing group 1: "myregex"
Regexp("something"); myfunction("something")    - capturing group 1: "something"); myfunction("something"
RegExp("my(regex)")                             - capturing group 1: "my(regex

This is clearly due to finding a matching closing parenthesis. Is there a workaround for this?

Body:
Try this RegEx:

/.*RegExp\((\"(?:.+?)\"|\/(?:.+?)\/.*)\).*/gmi

Review and test it out here: https://regex101.com/r/cReoV7/6


问:
Tkinter Entry validation for IP Address
I am taking IPv4 address as an input from the user, using Tkinter Entry and I would prefer using the validatecommand attribute of the widget which will only allow entries with the format XXX.XXX.XXX.XXX, being X digits.

The problem can be solved with re module matching the entry with the expression ^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$ but I would like to do it beforehand.

I have tried using the ipaddress module as follows:

```<code>import tkinter as tk
import ipaddress as ip
import re

def validate(value):
    if ip.ip_address(value):
        return True
    return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()
</code>```

The thing is that only the first character introduced is checked to be an IPv4 address and all characters are permitted, not only digits and dots.

How could it be done?

答:
You'll have to alter it if you don't want it to accept addresses like 999.999.999.999, but the regex that worked for me in a similar application is below. I wrote it to validate octet by octet. I'm still fairly new to this, so you'll have to excuse the PEP8 formatting issues.</p>

```<code>import tkinter as tk
import re

def validate(P):
    test = re.compile('(^\d{0,3}$|^\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{0,3}$)')
    if test.match(P):
        return True
    else:
        return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()
</code>```

Title: Tkinter Entry validation for IP Address

Body:
I am taking IPv4 address as an input from the user, using Tkinter Entry and I would prefer using the validatecommand attribute of the widget which will only allow entries with the format XXX.XXX.XXX.XXX, being X digits.

The problem can be solved with re module matching the entry with the expression ^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$ but I would like to do it beforehand.

I have tried using the ipaddress module as follows:

import tkinter as tk
import ipaddress as ip
import re

def validate(value):
    if ip.ip_address(value):
        return True
    return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()

The thing is that only the first character introduced is checked to be an IPv4 address and all characters are permitted, not only digits and dots.

How could it be done?

Body:
You'll have to alter it if you don't want it to accept addresses like 999.999.999.999, but the regex that worked for me in a similar application is below. I wrote it to validate octet by octet. I'm still fairly new to this, so you'll have to excuse the PEP8 formatting issues.

import tkinter as tk
import re

def validate(P):
    test = re.compile('(^\d{0,3}$|^\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{0,3}$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{0,3}$)')
    if test.match(P):
        return True
    else:
        return False

window = tk.Tk()

tk.Label(window, text = "IP", font = 'Arial 10 bold').grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'ew')
varip = tk.StringVar()
vcmd = window.register(validate)
ipadd = tk.Entry(window, textvariable = varip, width = 23, validate = 'key', validatecommand = (vcmd, '%P'))
ipadd.grid(row = 0, column = 1, padx = 5, pady = 5)
window.mainloop()


问:
Recursive data in JSON object
```<code>{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
</code>```

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

```<code>getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}
</code>```

答:
use this:

```<code>function getTopics(obj){
   if(typeof obj !== 'object') return [];
   if(obj.topic) return [obj.topic];
   var res = [];
   for(var i in obj){
     res.push(...getTopics(obj[i]));
   }
   return res;
}
</code>```

Working example:

const topics = {
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
}

function getTopics(obj){
  if(typeof obj !== 'object') return [];
  if(obj.topic) return [obj.topic];
  var res = [];
  for(var i in obj){
    res.push(...getTopics(obj[i]));
  }
  return res;
}

console.log(getTopics(topics));```

Title: Recursive data in JSON object

Body:
{
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]

}

OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:

["SERVICE_STATUS_PRESETS", "AIRCRAFT_ACTIVATION", "OUT_OF_SERVICE", "PROMO_CODES_REQUESTS", "BANNERS", "DOCUMENTS", "USER"]

I try recursive calls like this, though I only get last three records:

getRecursive() {
if (Array.isArray(data)) {
       for (let i = 0; i < data.length; i++) {
         if (data[i].subscriptions) {
           return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
         } else if (data[i].groups) {
           return this.getAllTopics(data[i].groups);
         }
       }
     }
     if (data && data.groups) {
      return this.getAllTopics(data.groups);
     }
     return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
}

Body:
use this:

function getTopics(obj){
   if(typeof obj !== 'object') return [];
   if(obj.topic) return [obj.topic];
   var res = [];
   for(var i in obj){
     res.push(...getTopics(obj[i]));
   }
   return res;
}

Working example:

const topics = {
"groups": [
    {
        "name": "Event",
        "groups": [
            {
                "name": "Service",
                "subscriptions": [
                    {
                        "topic": "SERVICE_STATUS_PRESETS"
                    },
                    {
                        "topic": "AIRCRAFT_ACTIVATION",

                    },
                    {
                        "topic": "OUT_OF_SERVICE",

                    }
                ]
            }
        ]
    },
    {
        "name": "Enquiries",
        "groups": [
            {
                "name": "Service-related",
                "subscriptions": [
                    {

                        "topic": "PROMO_CODES_REQUESTS",

                    }
                ]
            }
        ]
    }
],
"subscriptions": [
    {
        "topic": "BANNERS",
    },
    {
        "topic": "DOCUMENTS",
    },
    {
        "topic": "USER",
    }
]
}

function getTopics(obj){
  if(typeof obj !== 'object') return [];
  if(obj.topic) return [obj.topic];
  var res = [];
  for(var i in obj){
    res.push(...getTopics(obj[i]));
  }
  return res;
}

console.log(getTopics(topics));


问:
innerHTML is null? JS Form Validation
Why i get this error?
I'm using window.onload, i don't understand ... Can you help me?

HTML:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Pràctica DOM3</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
        <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
        <script type="text/javascript" src="script.js"></script>
        <style>
            h2 {
                text-align: center;
                border-bottom: 1px solid black;
                padding-bottom: 20px;
                /*text-decoration: underline;*/
            }
            #ultimsEstudisCursatsLabel {
                margin-top: 10px;
            }
            #submitFormButton {
                margin: auto;
                display: block;
            }
            #resetFormButton {
                margin: auto;
                display: block;
            }
            meter {
                margin: 0 auto 1em;
                width: 100%;
                height: .5em;
            }

            meter[value="1"]::-webkit-meter-optimum-value { background: red; }
            meter[value="2"]::-webkit-meter-optimum-value { background: yellow; }
            meter[value="3"]::-webkit-meter-optimum-value { background: orange; }
            meter[value="4"]::-webkit-meter-optimum-value { background: green; }

        </style>
    </head>
    <body>

        <div class="container">
            <h2>Inscripció CF Informàtica Marianao</h2>
            <br>
            <form method="post" action="#" id="formulari">
                <div class="form-group">
                    <label class="control-label col-sm-2" for="input1">Nom</label>
                        <div class="col-sm-10">
                            <input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Primer cognom</label>
                        <div class="col-sm-10">
                            <input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                <label class="control-label col-sm-2">Segon cognom</label>
                    <div class="col-sm-10">
                        <input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Data naixament </label>
                        <div class="col-sm-10">
                            <input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Email </label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Telèfon</label>
                        <div class="col-sm-10">
                            <input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>
                            <br />
                        </div>
                </div>

                <div class="form-group">

                    <label class="control-label col-sm-2">DNI</label>
                        <div class="col-sm-10">
                            <input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="form-label col-sm-2">Cicle formatiu</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="cicleFormatiu">
                                <option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
                                <option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
                                <option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
                                <option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
                            </select>
                            <br />
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2" id="ultimsEstudisCursatsLabel">Últims estudis cursats</label>
                        <div class="col-sm-10">
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior</label><br><br>
                            </div>
                            <div class="radio">
                                <label><input type="radio" name="ultimEstudis" value="altres">Altres</label><br><br>
                            </div>
                        </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Usuari</label>
                    <div class="col-sm-10">
                        <input class="form-control" type="text" id="inputUsuari" name="usuari" />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Contrasenya</label>
                    <div class="col-sm-10">
                        <input type="password" id="password" name="contrasenya" class="form-control" />
                        <meter max="4" id="password-strength-meter"></meter>
                        <p id="password-strength-text"></p>
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Torna a escriure la contrasenya</label>
                    <div class="col-sm-10">
                        <input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
                        <meter max="4" id="password-strength-meter"></meter>
                        <p id="password-strength-text"></p>
                        <br />
                    </div>
                    <br />
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Observacions</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-2">Termes i condicions</label>
                    <div class="col-sm-10">
                        <label class="checkbox-inline"><input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta <span><a href="condicions.html" target="_blank">aquí</a></span> els termes i condicions.<br></label>
                        <br />
                        <br />
                        <br />
                    </div>
                </div>

                <div class="form-group">
                    <input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">
                </div>
                <div class="form-group">
                    <input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">
                </div>
            </form>

        </div>
    </body>
</html>

</code>```

JS:

```<code>function main (){

    var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
    var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
    var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
    var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
    var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
    var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
    var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
    var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
    var password = document.getElementById("password").addEventListener("blur", validaContrassenya);

    // Recuento de carácteres en el text area.

        var textAreaID = document.getElementById("textarea");
        var length = textAreaID.getAttribute("maxlength");
        var textAreaCount = document.getElementById("count");
        textAreaCount.innerHTML = length + " caràcters restants.";
        textAreaID.addEventListener ("keypress", function () {
            document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
        });

    // Barra de seguridad METER.

    document.addEventListener("keydown", function () {
        var strength = {
            0: "Molt feble.",
            1: "Feble.",
            2: "Acceptable.",
            3: "Forta.",
            4: "Molt forta."
        }

        var password = document.getElementById('password');
        var meter = document.getElementById('password-strength-meter');
        var text = document.getElementById('password-strength-text');

        password.addEventListener('input', function() {
            var val = password.value;
            var result = zxcvbn(val);

            meter.value = result.score;

            if(val !== "") {
                text.innerHTML = "<strong>" + strength[result.score] + "</strong>";
            }
            else {
                text.innerHTML = "";
            }

            if (meter.value >= 2) {
                document.getElementById("contrasenyaCheck").disabled = false;
            }
            else {
                document.getElementById("contrasenyaCheck").disabled = true;
                document.getElementById('contrasenyaCheck').value = "";
            }
        });
    });

    // VALIDACIONES.

        // Primera validación.

            function validarNomCognoms () {
              var pattern = /^[a-zA-Z]*$/;
              if (this.value.length > 0) {
                if(!this.value.match(pattern)) {
                  this.setCustomValidity("No pot contindre números!");
                  this.reportValidity();
                }
                else {
                  this.setCustomValidity("");
                }
              }
              else {
                this.setCustomValidity("No pot citear buit ");
                this.reportValidity();
              }
            }

          // Segunda validación.

          function validarData () {
            if (this.value != "") {
              var dataRecibida = this.value;
              dataRecibida = dataRecibida.split("-").reverse().join("-");

              // Obtener la fecha actual.
              var today = new Date();
              var dd = today.getDate();
              var mm = today.getMonth() + 1;

              var yyyy = today.getFullYear();
              if (dd < 10) {
                dd = '0' + dd;
              }
              if (mm < 10) {
                mm = '0' + mm;
              }
              var today = dd + '/' + mm + '/' + yyyy;

              if (dataRecibida > today) {
                alert ("Data incorrecta.");
              }
              //this.value.setCustomValidity("");
            }
            else {
              alert ("citeá vacío.");
            }
          }

        // Tercera validación.

        function validarEmail () {
          if (this.value != "") {
              var emailPattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Mail incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Cuarta validación.

        function validarTelefon () {
          if (this.value != "") {
              var emailPattern = /^\d{9}$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Telèfon incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Quinta validación.

        function validarDni () {
          if (this.value != "") {
              var emailPattern = /^\d{8}[A-Z]$/;
              if (emailPattern.test(this.value)) {
                  var lletres = ['T', 'R', 'W', 'A',
                                 'G', 'M', 'Y', 'F',
                                 'P', 'D', 'X', 'B',
                                 'N', 'J', 'Z', 'S',
                                 'Q', 'V', 'H', 'L',
                                 'C', 'K', 'E', 'T'];

                  var index = this.value % 23;

                  var my_array = this.value;
                  var last_element = my_array[my_array.length - 1];
                  var boolean = false;

                  for (var i = 0; i < lletres.length; i++) {
                    if (last_element == lletres[i]) {
                      boolean = true;
                    }
                  }
                  if (boolean) {
                    return;
                  }
                  else {
                    alert ("Lletra DNI incorrecte.");
                  }
              }
              else {
                alert ("DNI incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Sexta validación.

        function validarUsuari () {
          if (this.value != "") {
            if (this.value.length < 5) {
              alert ("Longitud mínima de 5 caràcters.");
            }
            else if (this.value.length > 12) {
              alert ("Longitud màxima de 12 caràcters.");
            }
            else {
              return;
            }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Seéptima validación.

        function validaContrassenya () {
          var meter = document.getElementById('password-strength-meter');
          if (meter.value < 2) {
            document.getElementById("cite9").style.display = "block";
          }
          else {
            document.getElementById("cite9").style.display = "none";
          }
        }
}
window.onload = main;

</code>```

Thanks guys!!

ERROR:

答:
You never defined an element with id="count". Just check.

Also, when you define it, make sure it is a direct child of the body. You may try not to do this, but sometimes errors are caused.

Hope you understand now!

Title: innerHTML is null? JS Form Validation

Body:
Why i get this error?
I'm using window.onload, i don't understand ... Can you help me?

HTML:

<!DOCTYPE html>

        <title>Pràctica DOM3</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

        <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

Inscripció CF Informàtica Marianao

            <form method="post" action="#" id="formulari">

                    Nom

                            <input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />

                    Primer cognom

                            <input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />

                Segon cognom

                        <input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />

                    Data naixament

                            <input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>

                    Email

                            <input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>

                    Telèfon

                            <input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>

                    DNI

                            <input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />

                    Cicle formatiu

                            <select class="form-control" name="cicleFormatiu">
                                <option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
                                <option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
                                <option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
                                <option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
                            </select>

                    Últims estudis cursats

                                <input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO

                                <input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat

                                <input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà

                                <input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior

                                <input type="radio" name="ultimEstudis" value="altres">Altres

                    Usuari

                        <input class="form-control" type="text" id="inputUsuari" name="usuari" />

                    Contrasenya

                        <input type="password" id="password" name="contrasenya" class="form-control" />
                        <meter max="4" id="password-strength-meter"></meter>

                    Torna a escriure la contrasenya

                        <input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
                        <meter max="4" id="password-strength-meter"></meter>

                    Observacions

                        <textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>

                    Termes i condicions

                        <input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta aquí els termes i condicions.

                    <input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">

                    <input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">

            </form>

JS:

function main (){

    var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
    var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
    var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
    var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
    var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
    var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
    var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
    var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
    var password = document.getElementById("password").addEventListener("blur", validaContrassenya);

    // Recuento de carácteres en el text area.

        var textAreaID = document.getElementById("textarea");
        var length = textAreaID.getAttribute("maxlength");
        var textAreaCount = document.getElementById("count");
        textAreaCount.innerHTML = length + " caràcters restants.";
        textAreaID.addEventListener ("keypress", function () {
            document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
        });

    // Barra de seguridad METER.

    document.addEventListener("keydown", function () {
        var strength = {
            0: "Molt feble.",
            1: "Feble.",
            2: "Acceptable.",
            3: "Forta.",
            4: "Molt forta."
        }

        var password = document.getElementById('password');
        var meter = document.getElementById('password-strength-meter');
        var text = document.getElementById('password-strength-text');

        password.addEventListener('input', function() {
            var val = password.value;
            var result = zxcvbn(val);

            meter.value = result.score;

            if(val !== "") {
                text.innerHTML = "" + strength[result.score] + "";
            }
            else {
                text.innerHTML = "";
            }

            if (meter.value >= 2) {
                document.getElementById("contrasenyaCheck").disabled = false;
            }
            else {
                document.getElementById("contrasenyaCheck").disabled = true;
                document.getElementById('contrasenyaCheck').value = "";
            }
        });
    });

    // VALIDACIONES.

        // Primera validación.

            function validarNomCognoms () {
              var pattern = /^[a-zA-Z]*$/;
              if (this.value.length > 0) {
                if(!this.value.match(pattern)) {
                  this.setCustomValidity("No pot contindre números!");
                  this.reportValidity();
                }
                else {
                  this.setCustomValidity("");
                }
              }
              else {
                this.setCustomValidity("No pot citear buit ");
                this.reportValidity();
              }
            }

          // Segunda validación.

          function validarData () {
            if (this.value != "") {
              var dataRecibida = this.value;
              dataRecibida = dataRecibida.split("-").reverse().join("-");

              // Obtener la fecha actual.
              var today = new Date();
              var dd = today.getDate();
              var mm = today.getMonth() + 1;

              var yyyy = today.getFullYear();
              if (dd < 10) {
                dd = '0' + dd;
              }
              if (mm < 10) {
                mm = '0' + mm;
              }
              var today = dd + '/' + mm + '/' + yyyy;

              if (dataRecibida > today) {
                alert ("Data incorrecta.");
              }
              //this.value.setCustomValidity("");
            }
            else {
              alert ("citeá vacío.");
            }
          }

        // Tercera validación.

        function validarEmail () {
          if (this.value != "") {
              var emailPattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Mail incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Cuarta validación.

        function validarTelefon () {
          if (this.value != "") {
              var emailPattern = /^\d{9}$/;
              if (emailPattern.test(this.value)) {
                return;
              }
              else {
                alert ("Telèfon incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Quinta validación.

        function validarDni () {
          if (this.value != "") {
              var emailPattern = /^\d{8}[A-Z]$/;
              if (emailPattern.test(this.value)) {
                  var lletres = ['T', 'R', 'W', 'A',
                                 'G', 'M', 'Y', 'F',
                                 'P', 'D', 'X', 'B',
                                 'N', 'J', 'Z', 'S',
                                 'Q', 'V', 'H', 'L',
                                 'C', 'K', 'E', 'T'];

                  var index = this.value % 23;

                  var my_array = this.value;
                  var last_element = my_array[my_array.length - 1];
                  var boolean = false;

                  for (var i = 0; i < lletres.length; i++) {
                    if (last_element == lletres[i]) {
                      boolean = true;
                    }
                  }
                  if (boolean) {
                    return;
                  }
                  else {
                    alert ("Lletra DNI incorrecte.");
                  }
              }
              else {
                alert ("DNI incorrecte.");
              }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Sexta validación.

        function validarUsuari () {
          if (this.value != "") {
            if (this.value.length < 5) {
              alert ("Longitud mínima de 5 caràcters.");
            }
            else if (this.value.length > 12) {
              alert ("Longitud màxima de 12 caràcters.");
            }
            else {
              return;
            }
          }
          else {
            alert ("Está vacío.");
          }
        }

        // Seéptima validación.

        function validaContrassenya () {
          var meter = document.getElementById('password-strength-meter');
          if (meter.value < 2) {
            document.getElementById("cite9").style.display = "block";
          }
          else {
            document.getElementById("cite9").style.display = "none";
          }
        }
}
window.onload = main;

Thanks guys!!

ERROR:


问:
In Vim, what is the opposite of ctrl+w ctrl+w?
ctrl+w ctrl+w cycles through the viewports, but how do I go in the reverse direction?

Suppose I have 3 buffers open in a vsplit, repeatedly doing ctrl+w ctrl+w would go 1, 2, 3, 1, 2, 3, ... What about if I want to go 3, 2, 1, 3, 2, 1, ...

```<code>_____________________________________________________________
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|         1         |         2         |         3         |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
</code>```

答:
Move up: CTRL+w, SHIFT+w

Move down: CTRL+w, CTRL+w

Body:
ctrl+w ctrl+w cycles through the viewports, but how do I go in the reverse direction?

Suppose I have 3 buffers open in a vsplit, repeatedly doing ctrl+w ctrl+w would go 1, 2, 3, 1, 2, 3, ... What about if I want to go 3, 2, 1, 3, 2, 1, ...

_____________________________________________________________
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|         1         |         2         |         3         |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |


问:
Call PowerShell script with argument from another Powershell script with bypass
I need to call a ps1 Script during going through another ps1 file. The new call shouldn't interrupt the script which I'm going through. Also I always call the Powershell scripts like this: powershell -ExecutionPolicy Bypass -File file.ps1 -param log_14.txt due to execution policies.

I tried following code in my .ps1 script, sadly it doesn't work:

```<code>    Start-Job PowerShell -Argument "sort.ps1 -file $fileName"
</code>```

Any ideas how to make it work?

答:
Try this:</p>

```<code>$job = Start-Job -ScriptBlock {
  powershell -ExecutionPolicy Bypass -File "filepath.ps1 Param"
}
$job | wait-job | receive-job
</code>```

Body:
I need to call a ps1 Script during going through another ps1 file. The new call shouldn't interrupt the script which I'm going through. Also I always call the Powershell scripts like this: powershell -ExecutionPolicy Bypass -File file.ps1 -param log_14.txt due to execution policies.

I tried following code in my .ps1 script, sadly it doesn't work:

    Start-Job PowerShell -Argument "sort.ps1 -file $fileName"

Any ideas how to make it work?

Body:
Try this:

$job = Start-Job -ScriptBlock {
  powershell -ExecutionPolicy Bypass -File "filepath.ps1 Param"
}
$job | wait-job | receive-job


问:
How to apply regex for multiple phrases on a dataframe column?
Hello I have a dataframe where I want to remove a specific set of characters 'fwd', 're', 'RE' from every row that starts with these phrases or contains these phrases. The issue I am facing is that I do not know how to apply regex for each case.

my dataframe looks like this:

```<code>      summary
0 Fwd: Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Fwd:RE:Re: Please take action on the action needed items
4 Fix all the mistakes please
5 Fwd:Re: Take action on the attachments in this email
6 Fwd:RE: Action is required
</code>```

I want a result dataframe like this:

```<code>          summary
0 Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Please take action on the action needed items
4 Fix all the mistakes please
5 Take action on the attachments in this email
6 Action is required
</code>```

To get rid of 'Fwd' I used df['msg'].str.replace(r'^Fwd: ','')

答:
The key concept in this case I believe is using the | operator which works as Either or Or for the pattern. It's very useful for these cases.

This is how I would solve the problem:

```<code>import pandas as pd
df = pd.DataFrame({'index':[0,1,2,3,4,5,6,7],
                   'summary':['Fwd: Please look at the attached documents and take action ',
                              'NSN for the ones who care',
                              'News for all team members ',
                              'Fwd:RE:Re: Please take action on the action needed items',
                              'Fix all the mistakes please ',
                              'Fwd:Re: Take action on the attachments in this email',
                              'Fwd:RE: Action is required',
                              'Redemption!']})
df['clean'] = df['summary'].str.replace(r'^Fwd:|R[eE]:\s*','')
print(df)
</code>```

Output:

```<code>   index  ...                                              clean
0      0  ...   Please look at the attached documents and tak...
1      1  ...                          NSN for the ones who care
2      2  ...                         News for all team members
3      3  ...      Please take action on the action needed items
4      4  ...                       Fix all the mistakes please
5      5  ...       Take action on the attachments in this email
6      6  ...                                 Action is required
7      7  ...                                        Redemption!
</code>```

Body:
Hello I have a dataframe where I want to remove a specific set of characters 'fwd', 're', 'RE' from every row that starts with these phrases or contains these phrases. The issue I am facing is that I do not know how to apply regex for each case.

my dataframe looks like this:

      summary
0 Fwd: Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Fwd:RE:Re: Please take action on the action needed items
4 Fix all the mistakes please
5 Fwd:Re: Take action on the attachments in this email
6 Fwd:RE: Action is required

I want a result dataframe like this:

          summary
0 Please look at the attached documents and take action
1 NSN for the ones who care
2 News for all team members
3 Please take action on the action needed items
4 Fix all the mistakes please
5 Take action on the attachments in this email
6 Action is required

To get rid of 'Fwd' I used df['msg'].str.replace(r'^Fwd: ','')

Body:
The key concept in this case I believe is using the | operator which works as Either or Or for the pattern. It's very useful for these cases.

This is how I would solve the problem:

import pandas as pd
df = pd.DataFrame({'index':[0,1,2,3,4,5,6,7],
                   'summary':['Fwd: Please look at the attached documents and take action ',
                              'NSN for the ones who care',
                              'News for all team members ',
                              'Fwd:RE:Re: Please take action on the action needed items',
                              'Fix all the mistakes please ',
                              'Fwd:Re: Take action on the attachments in this email',
                              'Fwd:RE: Action is required',
                              'Redemption!']})
df['clean'] = df['summary'].str.replace(r'^Fwd:|R[eE]:\s*','')
print(df)

Output:

   index  ...                                              clean
0      0  ...   Please look at the attached documents and tak...
1      1  ...                          NSN for the ones who care
2      2  ...                         News for all team members
3      3  ...      Please take action on the action needed items
4      4  ...                       Fix all the mistakes please
5      5  ...       Take action on the attachments in this email
6      6  ...                                 Action is required
7      7  ...                                        Redemption!


问:
app is broken after updating to angular 9 and primeng
We have updated our angular application written on 8 to angular 9 and also the primeng library to 9.0.0-rc.4 but we are getting following error messages which is related to primeng.

```<code>import { MessageService } from 'primeng/components/common/api';
    src/app/component/attachm.component.ts:5:55 - error TS2307: Cannot find module 'primeng/components/common/api'.
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/components/common/api';
    src/app/component/email.component.ts:5:34 - error TS2307: Cannot find module 'primeng/components/common/api'.
</code>```

Package.json looks like this

```<code>"dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/localize": "^9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "primeflex": "^1.0.0",
    "primeicons": "^2.0.0",
    "primeng": "^9.0.0-rc.4",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.6.4"
  }
</code>```

is the specific things we need to do to fix this problem?

答:
change primeng/components/common/api to primeng/api.

DynamicDialogRef is probably changed to DynamicDialogModule from primeng/dynamicdialog

Now you may see the pattern. I use Visual Studio code and it helps me find the modules and their respective primeng src by suggesting as i type.

Body:
We have updated our angular application written on 8 to angular 9 and also the primeng library to 9.0.0-rc.4 but we are getting following error messages which is related to primeng.

import { MessageService } from 'primeng/components/common/api';
    src/app/component/attachm.component.ts:5:55 - error TS2307: Cannot find module 'primeng/components/common/api'.
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/components/common/api';
    src/app/component/email.component.ts:5:34 - error TS2307: Cannot find module 'primeng/components/common/api'.

Package.json looks like this

"dependencies": {
    "@angular/animations": "^9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/localize": "^9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "primeflex": "^1.0.0",
    "primeicons": "^2.0.0",
    "primeng": "^9.0.0-rc.4",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "~9.0.1",
    "@angular/language-service": "~9.0.1",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.6.4"
  }

is the specific things we need to do to fix this problem?


答:
1) separate Use separate in the tidyr package:

```<code>library(dplyr)
library(tidyr)

df %>%
  separate(x, c("x", "y"), sep = "-", extra = "merge")
</code>```

giving:

```<code>  x     y
1 a   b-c
2 b     d
3 c d_e-f
</code>```

2) Base R  Without using any packages we can use read.table.  Replace the first minus with space first.

```<code>read.table(text = sub("-", " ", df$x), col.names = c("x", "y"), as.is = TRUE)
</code>```

giving:

```<code>  x     y
1 a   b-c
2 b     d
3 c d_e-f
</code>```

3) read.fwf If the first field is always one character, as it is in the question, then we can use read.fwf

```<code>read.fwf(file = textConnection(as.character(df$x)), widths = c(1, 1, 99),
  colClasses = c(NA, "NULL", NA), col.names = c("x", NA, "y"))
</code>```

giving:

```<code>  x     y
1 a   b-c
2 b     d
3 c d_e-f
</code>```

Title: How to split string vector by first desired symbol in R?

Body:
Here is an example.

library(tidyverse)
df<-data.frame(x=c("a-b-c", "b-d","c-d_e-f"))
df
#        x
#1   a-b-c
#2     b-d
#3 c-d_e-f

What I wanted is to separate the column x by the first -, thus a desired output would be:

  x     y
1 a   b-c
2 b     d
3 c d_e-f

Body:
1) separate Use separate in the tidyr package:

library(dplyr)
library(tidyr)

df %>%
  separate(x, c("x", "y"), sep = "-", extra = "merge")

giving:

  x     y
1 a   b-c
2 b     d
3 c d_e-f

2) Base R  Without using any packages we can use read.table.  Replace the first minus with space first.

read.table(text = sub("-", " ", df$x), col.names = c("x", "y"), as.is = TRUE)

giving:

  x     y
1 a   b-c
2 b     d
3 c d_e-f

3) read.fwf If the first field is always one character, as it is in the question, then we can use read.fwf

read.fwf(file = textConnection(as.character(df$x)), widths = c(1, 1, 99),
  colClasses = c(NA, "NULL", NA), col.names = c("x", NA, "y"))

giving:

  x     y
1 a   b-c
2 b     d
3 c d_e-f


问:
print JSON objects using perl
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

```<code>  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }
</code>```

Output Getting

#

```<code>$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325
</code>```

答:
My Perl is getting rusty, but I think something like this should do the trick. You need to de-reference your array reference with another @{...} like @{${$hash_scalar}{$_}}.

use strict;
use warnings;
use Data::Dumper;
use JSON

my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

print Dumper($data);
my @hash_ref = from_json($data);

for my $hash_scalar (@hash_ref) {
    for my $key (keys(%{$hash_scalar})) {
        print("$key => @{${$hash_scalar}{$_}}\n");
    }
}
```

Title: print JSON objects using perl

Body:
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }

Output Getting

#

$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325


问:
how to disable remove option while uploading file in ng-zorro's nz-upload?
I am using ngzorro's nz-upload component to upload pdf files. But i have one issue that when the user removes the file while still upload , it causes problems in my array where i store responses.
Is there a way to disable the remove option while still uploading ? or another work-around maybe ?</p>

答:
You need to make 'showRemoveIcon=false' to disable remove icon in nz-zorro upload.</p>

```<code><nz-upload
  nzAction="https://jsonplaceholder.typicode.com/posts/"
  nzShowUploadList = "{showRemoveIcon?: false}"
  >
  <button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
</nz-upload>
</code>```

Body:
You need to make 'showRemoveIcon=false' to disable remove icon in nz-zorro upload.

<nz-upload
  nzAction="https://jsonplaceholder.typicode.com/posts/"
  nzShowUploadList = "{showRemoveIcon?: false}"
  >
  <button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
</nz-upload>


问:
Can I use closest() function in JavaScript?
I am trying to use the closest() function to delete a row from a table, but I am encountering an error.

Call function:<button onclick="validarIntervencao(1)">test</button>

function validarIntervencao(id) {
  var element = this;

  $.confirm({
    title: 'Confirmação!',
    content: "Quer mesmo validar a intervenção nº" + id + "? Esta ação envia o relatório ao cliente.",
    buttons: {
      Confirmar: {
        text: 'Confirmar',
        btnClass: 'btn btn-success',
        action: function() {
          $.ajax({
            url: base_url + "intervencoes/validarIntervencao/" + id,
            success: function(data) {

              if (data == false) {
                $.confirm({
                  title: 'Atenção!',
                  content: "Verifique a descrição e o relatório.",
                  buttons: {
                    Ok: {
                      text: 'Ok',
                      btnClass: 'btn btn-success'
                    }
                  }
                });
              } else {
                element.closest('tr').remove();
              }
            },
            error: function() {
              alert('Erro!');
            }
          });
        }
      },
      Cancelar: {
        text: 'Cancelar',
        btnClass: 'btn btn-danger'
      }
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="intervencoesTable" width="100%">
<thead>
<tr>
    <th>Teste</th>
    <th>Ações</th>
</tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>
            <button onclick="validarIntervencao(1)" id="validaBTN1">test</button>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>
            <button onclick="validarIntervencao(2)" id="validaBTN2">test</button>
        </td>
    </tr>
</tbody>
</table></code>```

I'm getting this error in console:

TypeError: element.closest is not a function

Can I use the closest() function inside a JavaScript function? Is there any alternative?

答:
Add another parameter to your function which will pass the element clicked.

<button onclick="validarIntervencao(this, 1)">test</button>
```

<pre class="lang-js prettyprint-override"><code>function validarIntervencao(element,id) {...}
</code>```

This will allow you to remove the element = this; declaration.

Body:
I am trying to use the closest() function to delete a row from a table, but I am encountering an error.

Call function:<button onclick="validarIntervencao(1)">test</button>

function validarIntervencao(id) {
  var element = this;

  $.confirm({
    title: 'Confirmação!',
    content: "Quer mesmo validar a intervenção nº" + id + "? Esta ação envia o relatório ao cliente.",
    buttons: {
      Confirmar: {
        text: 'Confirmar',
        btnClass: 'btn btn-success',
        action: function() {
          $.ajax({
            url: base_url + "intervencoes/validarIntervencao/" + id,
            success: function(data) {

              if (data == false) {
                $.confirm({
                  title: 'Atenção!',
                  content: "Verifique a descrição e o relatório.",
                  buttons: {
                    Ok: {
                      text: 'Ok',
                      btnClass: 'btn btn-success'
                    }
                  }
                });
              } else {
                element.closest('tr').remove();
              }
            },
            error: function() {
              alert('Erro!');
            }
          });
        }
      },
      Cancelar: {
        text: 'Cancelar',
        btnClass: 'btn btn-danger'
      }
    }
  });
}

    Teste
    Ações

        1

            <button onclick="validarIntervencao(1)" id="validaBTN1">test</button>

        2

            <button onclick="validarIntervencao(2)" id="validaBTN2">test</button>

I'm getting this error in console:

TypeError: element.closest is not a function

Can I use the closest() function inside a JavaScript function? Is there any alternative?

Body:
Add another parameter to your function which will pass the element clicked.

<button onclick="validarIntervencao(this, 1)">test</button>

function validarIntervencao(element,id) {...}

This will allow you to remove the element = this; declaration.