问:
Change the path of Database Adapter class in Zend Framework
I have written a customized Database Adapter extending Mysql Adapter (Zend_Db_Adapter_Mysqli) and my application.ini looks as under :-

```<code>resources.multidb.master.adapter = PDO_MYSQLCUSTOMIZED
resources.multidb.master.host = HOSTNAME
resources.multidb.master.username = USER
resources.multidb.master.password = PASS
resources.multidb.master.dbname = DB
</code>```

(Reason why it did so is this?)

Now my problem is I have to save Zend_Db_Adapter_Pdo_Mysqlcustomized in default path i.e. /library/Zend/Db/Adapter/Pdo/Mysqlcustomized.php.

I dont want to saveZend_Db_Adapter_Pdo_Mysqlndtv class in library.

What should I do?

答:
Probably the easiest thing to do is rename your class to something like My_Db_Adapter_Pdo_Mysql, store it in library/My/Db/Adapter/Pdo/Mysql.php and add / set these in your config file...

```<code>autoloaderNamespaces.My = "My_"
resources.multidb.master.adapter = "My_Db_Adapter_Pdo_Mysql"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have written a customized Database Adapter extending Mysql Adapter (Zend_Db_Adapter_Mysqli) and my application.ini looks as under :-

resources.multidb.master.adapter = PDO_MYSQLCUSTOMIZED
resources.multidb.master.host = HOSTNAME
resources.multidb.master.username = USER
resources.multidb.master.password = PASS
resources.multidb.master.dbname = DB

(Reason why it did so is this?)

Now my problem is I have to save Zend_Db_Adapter_Pdo_Mysqlcustomized in default path i.e. /library/Zend/Db/Adapter/Pdo/Mysqlcustomized.php.

I dont want to saveZend_Db_Adapter_Pdo_Mysqlndtv class in library.

What should I do?

Body:
Probably the easiest thing to do is rename your class to something like My_Db_Adapter_Pdo_Mysql, store it in library/My/Db/Adapter/Pdo/Mysql.php and add / set these in your config file...

autoloaderNamespaces.My = "My_"
resources.multidb.master.adapter = "My_Db_Adapter_Pdo_Mysql"


来源: stackexchange

问:
My query sys.database_audit_specification does't send back any record
I'm studying about SQL Server Audit. I have deployed Server Audit Specification. Now I want to query all the records but It doesn't return anything.

I use Windows Server 2012 Datacenter - SQL Server 2014 Developer Version

```<code>use master
go
select *
from sys.database_audit_specifications;
go
</code>```

I got no output and don't understand why.

How can I fix it?

答:
Here is an example that creates a server-level audit, then adds a database-level audit specification to track multiple operations on any object in the dbo schema.

```<code>USE master;
GO

-- create aserver audit
CREATE SERVER AUDIT Test_Server_Audit
  TO FILE ( FILEPATH = 'C:\temp\' ); -- you may need to change that'
GO

-- turn it on
ALTER SERVER AUDIT Test_Server_Audit WITH (STATE = ON);
GO

-- create a demo database
CREATE DATABASE floob;
GO
USE floob;
GO
CREATE TABLE dbo.blat(x INT);
GO

-- create a database audit specification that monitors for activity
-- against any dbo object:
CREATE DATABASE AUDIT SPECIFICATION Test_Database_Audit
    FOR SERVER AUDIT Test_Server_Audit
    ADD (SELECT, UPDATE, DELETE, INSERT, EXECUTE ON SCHEMA::dbo BY PUBLIC)
    WITH (STATE = ON);
GO

-- do a couple of things:
SELECT * FROM dbo.blat;
DELETE dbo.blat;
GO

-- you should see those couple of things in the audit file:
SELECT * FROM sys.fn_get_audit_file('C:\temp\*.sqlaudit', NULL, NULL);
GO
</code>```

For Further Reading follow this

ContentLicense: CC BY-SA 4.0

Body:
I'm studying about SQL Server Audit. I have deployed Server Audit Specification. Now I want to query all the records but It doesn't return anything.

I use Windows Server 2012 Datacenter - SQL Server 2014 Developer Version

use master
go
select *
from sys.database_audit_specifications;
go

I got no output and don't understand why.

How can I fix it?

Body:
Here is an example that creates a server-level audit, then adds a database-level audit specification to track multiple operations on any object in the dbo schema.

USE master;
GO

-- create aserver audit
CREATE SERVER AUDIT Test_Server_Audit
  TO FILE ( FILEPATH = 'C:\temp\' ); -- you may need to change that'
GO

-- turn it on
ALTER SERVER AUDIT Test_Server_Audit WITH (STATE = ON);
GO

-- create a demo database
CREATE DATABASE floob;
GO
USE floob;
GO
CREATE TABLE dbo.blat(x INT);
GO

-- create a database audit specification that monitors for activity
-- against any dbo object:
CREATE DATABASE AUDIT SPECIFICATION Test_Database_Audit
    FOR SERVER AUDIT Test_Server_Audit
    ADD (SELECT, UPDATE, DELETE, INSERT, EXECUTE ON SCHEMA::dbo BY PUBLIC)
    WITH (STATE = ON);
GO

-- do a couple of things:
SELECT * FROM dbo.blat;
DELETE dbo.blat;
GO

-- you should see those couple of things in the audit file:
SELECT * FROM sys.fn_get_audit_file('C:\temp\*.sqlaudit', NULL, NULL);
GO

For Further Reading follow this


问:
JavaScript Array splice vs slice
What is the difference between splice and slice ?

const array = [1, 2, 3, 4, 5];
array.splice(index, 1);
array.slice(index, 1);
```

答:
Here is a simple trick to remember the difference between slice vs splice

```<code>var a=['j','u','r','g','e','n'];

// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]

//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
</code>```

Trick to remember:

Think of "spl" (first 3 letters of splice) as short for "specifiy length", that the second argument should be a length not an index

Title: JavaScript Array splice vs slice

Body:
Here is a simple trick to remember the difference between slice vs splice

var a=['j','u','r','g','e','n'];

// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]

//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]

Trick to remember:

Think of "spl" (first 3 letters of splice) as short for "specifiy length", that the second argument should be a length not an index


问:
How to map a dataframe with a dictionary using a function?
I would like to apply a function while mapping a dataframe with the key's from a dictionary

```<code>col1 col2
foo 0
baa 1
wen 2

dict: {
'foo':a,
'baa':b,
'wen':c
}

def function(value1,value2):
    return value1+value2
</code>```

output

```<code>col1 col2
fooa 0
baab 1
wenc 2
</code>```

thanks

答:
```<code>df["col1"] =  df["col1"].apply(lambda x: x + (dict[x]))
</code>```

Should do the trick

.apply will let you apply a function to the whole column, and you can make a fast, anonymous function with lambda. Here's the docs on this: pandas.Series.apply

Body:
I would like to apply a function while mapping a dataframe with the key's from a dictionary

col1 col2
foo 0
baa 1
wen 2

dict: {
'foo':a,
'baa':b,
'wen':c
}

def function(value1,value2):
    return value1+value2

output

col1 col2
fooa 0
baab 1
wenc 2

thanks

Body:
df["col1"] =  df["col1"].apply(lambda x: x + (dict[x]))

Should do the trick

.apply will let you apply a function to the whole column, and you can make a fast, anonymous function with lambda. Here's the docs on this: pandas.Series.apply


问:
How do I check if a string is composed only of letters and numbers? (PHP)
Title says it all: I am checking to see if a user's username contains anything that isn't a number or letter, such as €{¥]^}+<€, punctuation, spaces or even things like âæłęč. Is this possible in php?</p>

答:
You can use the ctype_alnum() function in PHP.

From the manual..

Check for alphanumeric character(s)

  Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

var_dump(ctype_alnum("æøsads")); // false
var_dump(ctype_alnum("123asd")); // true
```

Live demo at https://3v4l.org/5etr7

Body:
You can use the ctype_alnum() function in PHP.

From the manual..

Check for alphanumeric character(s)

  Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

var_dump(ctype_alnum("æøsads")); // false
var_dump(ctype_alnum("123asd")); // true

Live demo at https://3v4l.org/5etr7


问:
How do I install an ODBC library in Jython
In python is possible to install pyodbc fairly easy, but in jython you are supposed either to install django, and to instal jdbc and then I do not know what else. Does any body know the proper steps? it is for windows an jython 2.5</p>

答: In Jython you can use JDBC drivers, and via JDBC-ODBC bridge you can connect to  ODBC configured source. With zxJDBC module you can use JDBC database just like DB-API2 compliant Python database interface. Have a look at example of such usage with Informix database: Consistent method of inserting TEXT column to Informix database using JDBC and ODBC


问:
Unexpected Results Splicing on Spreaded Array
This code is for a simple todo app built in react. Today I was trying to refactor my option 1 code into something like option 2 and was surprised to see that it broke my removeTask functionality. During troubleshooting I also tried option 3, which had the same results. I'm struggling to figure out why; to me option 2 and 3 look pretty much the same as option 1, just cleaner. When implementing option 2 or 3 I get no errors, yet clicking removeTask now deletes all the previous tasks. What is the difference between these three?

The problem code:

```<code>//Option 1 (working)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray];

  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};

//Option 2 (broken)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray].splice(index, 1);

  this.setState({ tasksarray: removedTaskArray });
};

//Option 3 (broken)
removeTask = (event, index) => {
  event.stopPropagation();
  const copyOfTasksArray = [...this.state.tasksarray]
  const removedTaskArray = copyOfTasksArray.splice(index, 1);

  this.setState({ tasksarray: removedTaskArray });
};
</code>```

Full (working) code:

```<code>import React, { Component } from 'react';
import './App.css';

/* InputTaskForm renders a form, and returns the input to our storeTask method. */
const InputTaskForm = ({ formValidation }) => {
    return (
      <form name="charlie" onSubmit={formValidation}>
        <input name="userinput" type="text" placeholder="Task..." />
        <button type="submit">Submit</button>
      </form>
    );
}

const DisplayTasks = ({ tasks, removeTask, strikeTask }) => {
  return (
    <div id="orderedList">
      <ol>
        {tasks.map((task, index) => (
          <li onClick={() => strikeTask(index)} key={index} >
            {task.strike ? <strike>{task.title}</strike> : task.title}
            <button id="removeButton" onClick={event => removeTask(event, index)} >Remove</button>
          </li>
        ))}
      </ol>
    </div>
  );
};

class App extends Component {
  state = {
    userinput: '',
    tasksarray: [],
  }

/* ============================================== #FUNCTIONS ==============================================
=========================================================================================================== */
formValidation = event => {                                 // event prop passed from InputTaskForm component
  event.preventDefault();                                   // prevent form from auto-refreshing on submit
  const userInput = event.target.userinput.value            // userInput stored
  const userInputIsBlank = userInput.trim().length < 1      // trim (remove) prefixed and affixed spaces, then check length

  userInputIsBlank
    ? alert(`Error: invalid submission`)
    : this.storeTask(userInput);
};

storeTask = userInput => {                                  // userInput passed from formValidation function
    this.setState({
      userinput: userInput,
      tasksarray: [...this.state.tasksarray, { title: userInput, strike: false } ] //create a copy of tasks array then add a new object into the array filled out with user input
    });
    document.forms["charlie"].reset();
};

//Option 1 (working)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray];

  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};

strikeTask = index => {                                    // index prop passed from DisplayTasks component
  const { tasksarray } = this.state
  const selected = tasksarray[index];

  this.setState({
    tasksarray: [                                           // change tasksarray state to: [prior slice, change, after slice]
      ...tasksarray.slice(0, index),                        // slice off (copies) of array elements prior to index element
      Object.assign(selected, {strike: !selected.strike}),  // invert the selected line's strike value
      ...tasksarray.slice(index + 1)                        // slice off (copies) of array elements after index element
    ]
  });
};

componentDidUpdate() {
  console.log(this.state.tasksarray);                       // debugging :)
};

/* =============================================== #RENDER ================================================
=========================================================================================================== */
  render() {
    const { tasksarray } = this.state
    const { formValidation, storeTask, removeTask, strikeTask } = this

    return (
      <div>
        <InputTaskForm
          task={storeTask}
          formValidation={formValidation} />

        <DisplayTasks
          tasks={tasksarray}
          removeTask={removeTask}
          strikeTask={strikeTask} />
      </div>
      );
    };
};

/* ================================================ #EXPORT ===============================================
=========================================================================================================== */
export default App;
</code>```

答:
It all boils down to understanding what does Array##splice it actually returns an array containing the deleted items. Here is a small example:</p>

```<code>const a = [1, 2, 3, 4, 5].splice(3, 1); // same as a = [4]
const b = [1, 2, 3, 4, 5];
const c = b.splice(3, 1); // same as b = [1, 2, 3, 5] and c = [4]
</code>```

Body:
This code is for a simple todo app built in react. Today I was trying to refactor my option 1 code into something like option 2 and was surprised to see that it broke my removeTask functionality. During troubleshooting I also tried option 3, which had the same results. I'm struggling to figure out why; to me option 2 and 3 look pretty much the same as option 1, just cleaner. When implementing option 2 or 3 I get no errors, yet clicking removeTask now deletes all the previous tasks. What is the difference between these three?

The problem code:

//Option 1 (working)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray];

  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};

//Option 2 (broken)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray].splice(index, 1);

  this.setState({ tasksarray: removedTaskArray });
};

//Option 3 (broken)
removeTask = (event, index) => {
  event.stopPropagation();
  const copyOfTasksArray = [...this.state.tasksarray]
  const removedTaskArray = copyOfTasksArray.splice(index, 1);

  this.setState({ tasksarray: removedTaskArray });
};

Full (working) code:

import React, { Component } from 'react';
import './App.css';

/* InputTaskForm renders a form, and returns the input to our storeTask method. */
const InputTaskForm = ({ formValidation }) => {
    return (
      <form name="charlie" onSubmit={formValidation}>
        <input name="userinput" type="text" placeholder="Task..." />
        <button type="submit">Submit</button>
      </form>
    );
}

const DisplayTasks = ({ tasks, removeTask, strikeTask }) => {
  return (

        {tasks.map((task, index) => (

 strikeTask(index)} key={index} >
            {task.strike ? {task.title} : task.title}
            <button id="removeButton" onClick={event => removeTask(event, index)} >Remove</button>

        ))}

  );
};

class App extends Component {
  state = {
    userinput: '',
    tasksarray: [],
  }

/* ============================================== #FUNCTIONS ==============================================
=========================================================================================================== */
formValidation = event => {                                 // event prop passed from InputTaskForm component
  event.preventDefault();                                   // prevent form from auto-refreshing on submit
  const userInput = event.target.userinput.value            // userInput stored
  const userInputIsBlank = userInput.trim().length < 1      // trim (remove) prefixed and affixed spaces, then check length

  userInputIsBlank
    ? alert(`Error: invalid submission`)
    : this.storeTask(userInput);
};

storeTask = userInput => {                                  // userInput passed from formValidation function
    this.setState({
      userinput: userInput,
      tasksarray: [...this.state.tasksarray, { title: userInput, strike: false } ] //create a copy of tasks array then add a new object into the array filled out with user input
    });
    document.forms["charlie"].reset();
};

//Option 1 (working)
removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray];

  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};

strikeTask = index => {                                    // index prop passed from DisplayTasks component
  const { tasksarray } = this.state
  const selected = tasksarray[index];

  this.setState({
    tasksarray: [                                           // change tasksarray state to: [prior slice, change, after slice]
      ...tasksarray.slice(0, index),                        // slice off (copies) of array elements prior to index element
      Object.assign(selected, {strike: !selected.strike}),  // invert the selected line's strike value
      ...tasksarray.slice(index + 1)                        // slice off (copies) of array elements after index element
    ]
  });
};

componentDidUpdate() {
  console.log(this.state.tasksarray);                       // debugging :)
};

/* =============================================== #RENDER ================================================
=========================================================================================================== */
  render() {
    const { tasksarray } = this.state
    const { formValidation, storeTask, removeTask, strikeTask } = this

    return (

        <InputTaskForm
          task={storeTask}
          formValidation={formValidation} />

        <DisplayTasks
          tasks={tasksarray}
          removeTask={removeTask}
          strikeTask={strikeTask} />

      );
    };
};

/* ================================================ #EXPORT ===============================================
=========================================================================================================== */
export default App;

Body:
It all boils down to understanding what does Array##splice it actually returns an array containing the deleted items. Here is a small example:

const a = [1, 2, 3, 4, 5].splice(3, 1); // same as a = [4]
const b = [1, 2, 3, 4, 5];
const c = b.splice(3, 1); // same as b = [1, 2, 3, 5] and c = [4]


问:
How to make it so that after naving to a fragment, the last fragment can no longer be navigated to with the back button?
I have a nav structure like so:

```<code>StaringFragment -> nestedNavGraph
                         |
                   HomeFragment -> SecondFragment
</code>```

I need to make it so that after the user navigates away from StartingFragment to the nestedNavGraph the user can no longer hit the back button to return to the StartingFragment.

I am basically performing a permissions check, and if the check succeeds I navigate from the StartingFragment to the nestedNavGraph with this code:

findNavController(R.id.nav_host_frag).navigate(R.id.nestedNavGraph)

Then, on the action arrow between the StartingFrag -> nestedNavGraph in the nav graph editor, I set popUpTo to HomeFragment and inclusive to true. Did I misunderstand the documentation?

What's the proper way to remove the StartingFragment from the backstack as soon as I navigate away from it?

答:
I haven't used the nav lib yet, but from reading this bit in the documentation maybe you just have a typo and need to replace popTo with popUpTo?

To pop destinations when navigating from one destination to another, add a app:popUpTo attribute to the associated  element. app:popUpTo tells the Navigation library to pop some destinations off of the back stack as part of the call to navigate(). The attribute value is the ID of the most recent destination that should remain on the stack.

You can also include app:popUpToInclusive="true" to indicate that the destination specified in app:popUpTo should also be removed from the back stack.

Body:
I have a nav structure like so:

StaringFragment -> nestedNavGraph
                         |
                   HomeFragment -> SecondFragment

I need to make it so that after the user navigates away from StartingFragment to the nestedNavGraph the user can no longer hit the back button to return to the StartingFragment.

I am basically performing a permissions check, and if the check succeeds I navigate from the StartingFragment to the nestedNavGraph with this code:

findNavController(R.id.nav_host_frag).navigate(R.id.nestedNavGraph)

Then, on the action arrow between the StartingFrag -> nestedNavGraph in the nav graph editor, I set popUpTo to HomeFragment and inclusive to true. Did I misunderstand the documentation?

What's the proper way to remove the StartingFragment from the backstack as soon as I navigate away from it?


问:
Reuse function to delete an item
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.

I'm using the latest chrome browser version.

```<code><!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

    <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button type="button" class="btn btn-danger" id="danger">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
    <script src="./index.js"></script>
</body>
</html>
</code>```

```<code>document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);

let inner_form = document.getElementById('form').innerHTML;

function open_google() {
    window.open('http://google.com', '_blank');
}

let buttons;

function button_change(button) {
    switch(button) {
        case "success":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Add form';
            buttons[1].className = 'btn btn-success';
            document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
            break;
        case "danger":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Delete form';
            buttons[1].className = 'btn btn-danger';
            break;
        default:
            break;
    }
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button_change("success");
}

function add_function() {
    document.getElementById('form').innerHTML = inner_form;
    button_change("danger");
}
</code>```

Example code: https://codepen.io/anon/pen/xNjPYj

答:
Why don't you just hide it? This is much easier

    function toggle() {
     var element = document.getElementById("form");
      if (element.style.display === "none") {
        element.style.display = "block";
      }
      else {
        element.style.display = "none";
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button onclick="toggle()" type="button" class="btn btn-danger" id="danger">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
</body>
</html></code>```

Title: Reuse function to delete an item

Body:
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.

I'm using the latest chrome browser version.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Task 1</title>

<button type="button" class="btn btn-primary">Open Google</button>

<button type="button" class="btn btn-danger" id="danger">Delete form</button>

            <form id="form">

                    Example label
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

                    Another label
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

            </form>

document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);

let inner_form = document.getElementById('form').innerHTML;

function open_google() {
    window.open('http://google.com', '_blank');
}

let buttons;

function button_change(button) {
    switch(button) {
        case "success":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Add form';
            buttons[1].className = 'btn btn-success';
            document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
            break;
        case "danger":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Delete form';
            buttons[1].className = 'btn btn-danger';
            break;
        default:
            break;
    }
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button_change("success");
}

function add_function() {
    document.getElementById('form').innerHTML = inner_form;
    button_change("danger");
}

Example code: https://codepen.io/anon/pen/xNjPYj

Body:
Why don't you just hide it? This is much easier

    function toggle() {
     var element = document.getElementById("form");
      if (element.style.display === "none") {
        element.style.display = "block";
      }
      else {
        element.style.display = "none";
      }
    }

<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <title>Task 1</title>
</head>
<body style="height: 100%">
    <div class="container h-100">
        <div class="row h-100 justify-content-center align-content-center">
            <div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
            <div class=""><button onclick="toggle()" type="button" class="btn btn-danger" id="danger">Delete form</button></div>
            <div class="breaker w-100" style="height:10%;"></div>
            <form id="form">
                <div class="form-group">
                    <label for="formGroupExampleInput">Example label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
                </div>
                <div class="form-group">
                    <label for="formGroupExampleInput2">Another label</label>
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
                </div>
            </form>
        </div>
    </div>
</body>
</html>


问:
Android grpc failed execption
Getting this error when trying to get location from latlong using Geocoder.

Error

Caused by java.io.IOException: grpc failed
         at android.location.Geocoder.getFromLocation(Geocoder.java:136)
         at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:676)
         at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:81)
         at com.google.android.gms.tasks.zzj.run(Unknown Source)
         at android.os.Handler.handleCallback(Handler.java:751)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6776)
         at java.lang.reflect.Method.invoke(Method.java)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

Code

```<code>    punch_button?.setOnClickListener {
    createLocationRequest()
}

protected fun createLocationRequest() {
    mLocationRequest = LocationRequest()
    mLocationRequest?.interval = 10
    mLocationRequest?.fastestInterval = 50
    mLocationRequest?.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest!!)

    mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            super.onLocationResult(p0)
            mCurrentLocation = p0?.lastLocation
        }

    }

    val client = LocationServices.getSettingsClient(context)
    val task = client.checkLocationSettings(builder.build())

    task.addOnSuccessListener(OnSuccessListener<LocationSettingsResponse> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            askForPermission();
        }
    })  }

    private fun askForPermission() {
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
        } else {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
        }
    } else {
        sendLocationData()
    }
}

    @SuppressLint("MissingPermission")
fun sendLocationData() {
try{
    Log.e("lat", mCurrentLocation?.latitude.toString())
    //mCurrentLocation?.latitude !=null && mCurrentLocation?.latitude !=null
    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null)

    mFusedLocationClient.lastLocation.addOnSuccessListener({ location ->
        if (location != null) {
            val address: List<Address> = geocoder?.getFromLocation(location.latitude, location.longitude, 1)!!
        }
    })

}catch(e:Exception){
  Log.e("tag","error")
}
}
</code>```

答:
This is a know bug reported to Google, but unfortunately not solved yet. This bug happens for real devices and emulators. You can see the thread about this issue here:

https://issuetracker.google.com/issues/64418751

https://issuetracker.google.com/issues/64247769

A workround to try solved this bug in your case is try to use Geocoding API web service:
https://github.com/googlemaps/google-maps-services-java

Or you can try just catch the except and handle the exception like this:

```<code>try{
geocoder = new Geocoder(this, Locale.getDefault())
   // ... your code that throws the exception here
}catch(e: IOException){
   Log.e("Error", "grpc failed: " + e.message, e)
   // ... retry again your code that throws the exeception
}
</code>```

Title: Android grpc failed execption

Body:
Getting this error when trying to get location from latlong using Geocoder.

Error

Caused by java.io.IOException: grpc failed
         at android.location.Geocoder.getFromLocation(Geocoder.java:136)
         at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:676)
         at com.example.myApp.test.Fragments.DashboardFragment$sendLocationData$1.onSuccess(DashboardFragment.kt:81)
         at com.google.android.gms.tasks.zzj.run(Unknown Source)
         at android.os.Handler.handleCallback(Handler.java:751)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6776)
         at java.lang.reflect.Method.invoke(Method.java)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

Code

    punch_button?.setOnClickListener {
    createLocationRequest()
}

protected fun createLocationRequest() {
    mLocationRequest = LocationRequest()
    mLocationRequest?.interval = 10
    mLocationRequest?.fastestInterval = 50
    mLocationRequest?.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest!!)

    mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult?) {
            super.onLocationResult(p0)
            mCurrentLocation = p0?.lastLocation
        }

    }

    val client = LocationServices.getSettingsClient(context)
    val task = client.checkLocationSettings(builder.build())

    task.addOnSuccessListener(OnSuccessListener<LocationSettingsResponse> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            askForPermission();
        }
    })  }

    private fun askForPermission() {
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
        } else {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 123);
        }
    } else {
        sendLocationData()
    }
}

    @SuppressLint("MissingPermission")
fun sendLocationData() {
try{
    Log.e("lat", mCurrentLocation?.latitude.toString())
    //mCurrentLocation?.latitude !=null && mCurrentLocation?.latitude !=null
    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null)

    mFusedLocationClient.lastLocation.addOnSuccessListener({ location ->
        if (location != null) {
            val address: List<Address> = geocoder?.getFromLocation(location.latitude, location.longitude, 1)!!
        }
    })

}catch(e:Exception){
  Log.e("tag","error")
}
}

Body:
This is a know bug reported to Google, but unfortunately not solved yet. This bug happens for real devices and emulators. You can see the thread about this issue here:

https://issuetracker.google.com/issues/64418751

https://issuetracker.google.com/issues/64247769

A workround to try solved this bug in your case is try to use Geocoding API web service:
https://github.com/googlemaps/google-maps-services-java

Or you can try just catch the except and handle the exception like this:

try{
geocoder = new Geocoder(this, Locale.getDefault())
   // ... your code that throws the exception here
}catch(e: IOException){
   Log.e("Error", "grpc failed: " + e.message, e)
   // ... retry again your code that throws the exeception
}


问:
how to decode jQuery json data posted to php
I have a web page that sends form data to php using jQuery.  I want to decode the data array and loop through it, displaying each of the four values using php print_r.

Here is the jQuery function to post the data to php:

```<code><script type="text/javascript">
function postData() {
    return $.ajax({
    var datastring = $("#echo_test").serialize();
    $.ajax({
       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
});
}
</script>
</code>```

Here is the php function echo_test:

```<code><?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>
</code>```

I think json_decode is wrong because the data posted is not json format.

When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back.  Ideally I would I loop through $obj to display each of the four values on the screen.

Ultimately I will post the data to Postgres on a cloud server.  For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.

Thanks for any help with this.

答:
What you need to do is use parse_str:
https://php.net/manual/en/function.parse-str.php</p>

```<code><?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
</code>```

Body:
I have a web page that sends form data to php using jQuery.  I want to decode the data array and loop through it, displaying each of the four values using php print_r.

Here is the jQuery function to post the data to php:

Here is the php function echo_test:

<?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>

I think json_decode is wrong because the data posted is not json format.

When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back.  Ideally I would I loop through $obj to display each of the four values on the screen.

Ultimately I will post the data to Postgres on a cloud server.  For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.

Thanks for any help with this.

Body:
What you need to do is use parse_str:
https://php.net/manual/en/function.parse-str.php

<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>


问:
What is the significance of class data type in java?
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

```<code>Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}
</code>```

What does Node next = null; mean? I can understand the effort to create an object with

```<code>Node next = new Node();
</code>```

and then try to manipulate the next object.

答:
The line

```<code>Node next = null;
</code>```

means that you define a variable next which holds only references to objects of type (the class) Node. Additionally you initialize it with the null value which means no object created yet.

Those variables actually hold references to objects and null is a special value valid only for objects which indicates that your variable is empty. This something like next.append() will fail with a nullpointer exception if next is still null.

Body:
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}

What does Node next = null; mean? I can understand the effort to create an object with

Node next = new Node();

and then try to manipulate the next object.

Body:
The line

Node next = null;

means that you define a variable next which holds only references to objects of type (the class) Node. Additionally you initialize it with the null value which means no object created yet.

Those variables actually hold references to objects and null is a special value valid only for objects which indicates that your variable is empty. This something like next.append() will fail with a nullpointer exception if next is still null.


答:
Return value of splice is

An array containing the deleted elements. If only one element is
  removed, an array of one element is returned. If no elements are
  removed, an empty array is returned.

So in your 2nd and 3rd method you're placing deleted element arrays

so you can simply change your code to

```<code>removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray]
  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};
</code>```

Title: Unexpected Results Splicing on Spreaded Array

Body:
Return value of splice is

An array containing the deleted elements. If only one element is
  removed, an array of one element is returned. If no elements are
  removed, an empty array is returned.

So in your 2nd and 3rd method you're placing deleted element arrays

so you can simply change your code to

removeTask = (event, index) => {
  event.stopPropagation();
  const removedTaskArray = [...this.state.tasksarray]
  removedTaskArray.splice(index, 1);
  this.setState({ tasksarray: removedTaskArray });
};


问:
How to add Form title to data sent to a Google Sheets
I have multiple Google Forms with identical response fields inputting into a certain Google Sheets, and there is no way of telling them apart other than their names and descriptions. Using Google Apps Script, is there any way I can add the name and/or description of the Google Form into the Sheets, along with everything that is normally added to the Sheets? I did a bit of research about something with "source" but I have no idea how to implement it.

Thanks!

答:
You can accomplish this by going to your form in edit mode selecting "Script Editor" and pasting the below code into the script.  You will need to click on the "Trigger" button (looks like a clock, if you can't find it follow here https://developers.google.com/apps-script/guides/triggers/installable). Click Add Trigger and select event type "On Form Submit"</p>

```<code>function writeFormTitle(){
  //Get Form
  var form = FormApp.getActiveForm();

  //Get Form's Title
  var formTitle = form.getTitle();

  //Get the Write To Spreadsheet ID where the data will be written to
  var destinationSpreadsheet = form.getDestinationId();

  //Activate that Spreadsheet by the destinationSpreadsheet ID
  var sheet = SpreadsheetApp.openById(destinationSpreadsheet).getActiveSheet();

  //Find the last column and row
  var writeToColumn = sheet.getLastColumn()+1;
  var writeToRow = sheet.getLastRow();

  //Write title to Spreadsheet next to submitted data.
  sheet.getRange(writeToRow, writeToColumn, 1, 1).setValue(formTitle);

}
</code>```

Body:
You can accomplish this by going to your form in edit mode selecting "Script Editor" and pasting the below code into the script.  You will need to click on the "Trigger" button (looks like a clock, if you can't find it follow here https://developers.google.com/apps-script/guides/triggers/installable). Click Add Trigger and select event type "On Form Submit"

function writeFormTitle(){
  //Get Form
  var form = FormApp.getActiveForm();

  //Get Form's Title
  var formTitle = form.getTitle();

  //Get the Write To Spreadsheet ID where the data will be written to
  var destinationSpreadsheet = form.getDestinationId();

  //Activate that Spreadsheet by the destinationSpreadsheet ID
  var sheet = SpreadsheetApp.openById(destinationSpreadsheet).getActiveSheet();

  //Find the last column and row
  var writeToColumn = sheet.getLastColumn()+1;
  var writeToRow = sheet.getLastRow();

  //Write title to Spreadsheet next to submitted data.
  sheet.getRange(writeToRow, writeToColumn, 1, 1).setValue(formTitle);

}


问:
How to inject activity context in modules with koin dependency library
I have a Util module as below, it requires the activity context [not application context] to do some of its functions.

How do I inject the activity context into it?

```<code>class MainPresenter internal constructor(private val iMainActivity: IActivity)  : IPresenter {

    //dependencies
    private val context = iMainActivity as AppCompatActivity

    private var util = UtilModule(context)         //<-- inject this
    private var httpClient = HttpClient(context)   //<-- inject this
</code>```

答:
In this case, as @commonsware said, it's not good that the presenter class depends on the activity.
The better solution with the injection can be like the following the structure:

```<code>class IActivity{

    private val utilModule: UtilModule by lazy { UtilModule(this@IActivity) }
    private val httpClient: HttpClient by lazy { HttpClient(this@IActivity) }

    private val presenter: MainPresenter by inject{ parametersOf(utilModel,
    httpClient) }

}

class MainPresenter(private val util: UtilModule, private val httpClient: HttpClient)
</code>```

Your module:

```<code>single { MainPresenter( it[0], it[1] ) }
</code>```

Body:
I have a Util module as below, it requires the activity context [not application context] to do some of its functions.

How do I inject the activity context into it?

class MainPresenter internal constructor(private val iMainActivity: IActivity)  : IPresenter {

    //dependencies
    private val context = iMainActivity as AppCompatActivity

    private var util = UtilModule(context)         //<-- inject this
    private var httpClient = HttpClient(context)   //<-- inject this

Body:
In this case, as @commonsware said, it's not good that the presenter class depends on the activity.
The better solution with the injection can be like the following the structure:

class IActivity{

    private val utilModule: UtilModule by lazy { UtilModule(this@IActivity) }
    private val httpClient: HttpClient by lazy { HttpClient(this@IActivity) }

    private val presenter: MainPresenter by inject{ parametersOf(utilModel,
    httpClient) }

}

class MainPresenter(private val util: UtilModule, private val httpClient: HttpClient)

Your module:

single { MainPresenter( it[0], it[1] ) }


答:
Node next = null; is a sort of pointer to a NodeObject. It's like declaring a variable not still initialized.
In this case the object will probably be instantiated later.
If you put an already existing object to a null value, if there aren't other references to the same object, then the garbage collector deletes it.

I have been programming at basic level for quite a while but I have trouble understanding class data type.
  when we say int a = 9; it means a is of data type int meaning it can contain only integers.
  like wise for String, boolean, double, float etc.

Pay attention that int and Integer are different in Java. int is a primitive type and it isn't an object. Integer is an object you can instantiate with new operator.

Title: What is the significance of class data type in java?


问:
Django if statement doesn't work as expected
I have the following in my html file:

```<code>{% trans "Result: "%} {{result}}
</code>```

Which will print out the word SUCCESS on the browser (because thats what the string contains)

But If I do the following:

```<code>{% if result == 'SUCCESS' %}
   do something
{% else %}
   do something else
{% endif %}
</code>```

I find that the if statement does not work as expected.

Why is this??

答:
Check this link:
Django String format.
according to django documentation you should use this format:

```<code>{% if result|stringformat:"s" == 'SUCCESS' %}
   do something
{% else %}
   do something else
{% endif %}
</code>```

or

```<code>{% if result|stringformat:"s" in 'SUCCESS' %}
       do something
    {% else %}
       do something else
    {% endif %}
</code>```

or

```<code>{% ifequal result|stringformat:"s" 'SUCCESS' %}
       do something
    {% else %}
       do something else
    {% endif %}
</code>```

this problem happen because of your variable type, you should change it to string before compare it to another string.

Body:
I have the following in my html file:

{% trans "Result: "%} {{result}}

Which will print out the word SUCCESS on the browser (because thats what the string contains)

But If I do the following:

{% if result == 'SUCCESS' %}
   do something
{% else %}
   do something else
{% endif %}

I find that the if statement does not work as expected.

Why is this??

Body:
Check this link:
Django String format.
according to django documentation you should use this format:

{% if result|stringformat:"s" == 'SUCCESS' %}
   do something
{% else %}
   do something else
{% endif %}

or

{% if result|stringformat:"s" in 'SUCCESS' %}
       do something
    {% else %}
       do something else
    {% endif %}

or

{% ifequal result|stringformat:"s" 'SUCCESS' %}
       do something
    {% else %}
       do something else
    {% endif %}

this problem happen because of your variable type, you should change it to string before compare it to another string.


问:
How to query users collection using array of IDs from group collection
I have a collection where I store user groups. Each group has a group name, group limit and an array of users ID's.

I wonder how the best way to retrieve one group details and then users details, like name, photo, etc.

Right now, I am doing two queries to the database. First retrieving the group data(name, etc), second getting a list of users who has in the user details the information of the group ID:

"syncDesp = a4sQ27xb1wuD2rhONU2K"

I'm afraid of calling the database to many times.

// Get Group details
Preferencias prefs = new Preferencias(view.getContext());
listenGroups = pFirestore.collection("syncDesps").document(prefs.getSyncDesp()).addSnapshotListener((documentSnapshot, e) -> {
    if(e != null){
        Log.i("dados erro", Objects.requireNonNull(e).getMessage());
    }
    if(documentSnapshot != null){
        String nomeGrupo = Objects.requireNonNull(documentSnapshot.get("nomeGrupo")).toString();
        textNomeGrupo.setText(nomeGrupo);
        ArrayList membrosGrupo = (ArrayList) Objects.requireNonNull(documentSnapshot.get("syncDesp"));

    }
});

// Get User Details
FirebaseFirestore grupoFire = FirebaseFirestore.getInstance();
grupoFire.collection("usuarios")
        .whereEqualTo("syncDesp", prefs.getSyncDesp())
        .addSnapshotListener((queryDocumentSnapshots, e1) -> {
            listaUsuarios.clear();
            if(e != null){
                Log.i("dados erro", Objects.requireNonNull(e1).getMessage());
            }
            for(DocumentSnapshot usuarioSnapshot : Objects.requireNonNull(queryDocumentSnapshots).getDocuments()){
                String idU = (usuarioSnapshot.get("id") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("id")).toString();
                String nomeUsuario = (usuarioSnapshot.get("nome") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("nome")).toString();
                String fotoUsuario = (usuarioSnapshot.get("imgUsuario") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("imgUsuario")).toString();

                UsuarioMeuGrupo usuarioMeuGrupo = new UsuarioMeuGrupo();//
                usuarioMeuGrupo.setIdUsuario(idU);
                usuarioMeuGrupo.setNome(nomeUsuario);
                usuarioMeuGrupo.setFoto(fotoUsuario);
                listaUsuarios.add(usuarioMeuGrupo);
            }

            adaptera.setOnItemClickRemoverListener(uMeuGrupo -> {
                Log.i("dados uMeuGrupo Clic", uMeuGrupo.getNome());
            });
            adaptera.notifyDataSetChanged();
        });
```

I wonder if I should query the group collection separately from the users collection or if there is a way of making only one function to retrieve data from both collections.

答:
It's not possible to make a single query in Cloud Firestore span multiple collections.  There is no join-like operation like you have in SQL.  The only exception to this is collection group queries, which doesn't apply to your situation.

What you're doing right now is probably the best you can do with the database structure you have.  If you want fewer queries, you'll have to do something to restructure your data to support that.

Body:
I have a collection where I store user groups. Each group has a group name, group limit and an array of users ID's.

I wonder how the best way to retrieve one group details and then users details, like name, photo, etc.

Right now, I am doing two queries to the database. First retrieving the group data(name, etc), second getting a list of users who has in the user details the information of the group ID:

"syncDesp = a4sQ27xb1wuD2rhONU2K"

I'm afraid of calling the database to many times.

// Get Group details
Preferencias prefs = new Preferencias(view.getContext());
listenGroups = pFirestore.collection("syncDesps").document(prefs.getSyncDesp()).addSnapshotListener((documentSnapshot, e) -> {
    if(e != null){
        Log.i("dados erro", Objects.requireNonNull(e).getMessage());
    }
    if(documentSnapshot != null){
        String nomeGrupo = Objects.requireNonNull(documentSnapshot.get("nomeGrupo")).toString();
        textNomeGrupo.setText(nomeGrupo);
        ArrayList membrosGrupo = (ArrayList) Objects.requireNonNull(documentSnapshot.get("syncDesp"));

    }
});

// Get User Details
FirebaseFirestore grupoFire = FirebaseFirestore.getInstance();
grupoFire.collection("usuarios")
        .whereEqualTo("syncDesp", prefs.getSyncDesp())
        .addSnapshotListener((queryDocumentSnapshots, e1) -> {
            listaUsuarios.clear();
            if(e != null){
                Log.i("dados erro", Objects.requireNonNull(e1).getMessage());
            }
            for(DocumentSnapshot usuarioSnapshot : Objects.requireNonNull(queryDocumentSnapshots).getDocuments()){
                String idU = (usuarioSnapshot.get("id") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("id")).toString();
                String nomeUsuario = (usuarioSnapshot.get("nome") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("nome")).toString();
                String fotoUsuario = (usuarioSnapshot.get("imgUsuario") == null) ? "" : Objects.requireNonNull(usuarioSnapshot.get("imgUsuario")).toString();

                UsuarioMeuGrupo usuarioMeuGrupo = new UsuarioMeuGrupo();//
                usuarioMeuGrupo.setIdUsuario(idU);
                usuarioMeuGrupo.setNome(nomeUsuario);
                usuarioMeuGrupo.setFoto(fotoUsuario);
                listaUsuarios.add(usuarioMeuGrupo);
            }

            adaptera.setOnItemClickRemoverListener(uMeuGrupo -> {
                Log.i("dados uMeuGrupo Clic", uMeuGrupo.getNome());
            });
            adaptera.notifyDataSetChanged();
        });

I wonder if I should query the group collection separately from the users collection or if there is a way of making only one function to retrieve data from both collections.


问:
How to render AmCharts as Canvas?
I am using a charting library, AmCharts to display different types of charts on my web page. Now, I want all those charts to be exported into a PDF. In order to implement this feature, I am using KendoReact's PDFExport Component.

The chart is displayed as a SVG and the PDF Export does not support SVG. Meaning, when the PDF is exported, it does not include charts in it. To fix this, the charts need to be rendered as canvas and not as SVG.

Any idea on how I can convert this SVG to canvas?

Please let me know. Thanks!

答:
By using chart.exporting.getSVG() you will get the URI format of the chart. then you need to remove the svg type header and decode it back to SVG code before putting it into a canvas.

Here's a snippet of code that might help

```<code>var svg = decodeURIComponent(chart.exporting.getSVG()._v).split("?>")[1]
canvg(document.getElementById('canvas'), svg);
</code>```

You will need the CANVG library to be included on your page.
AMCharts uses this inside their script.

AMCharts built in Export

```<code>chart.exporting.export("pdf");
</code>```

will trigger the chart to export to pdf (with its own built in SVG to Canvas To Image to PDF converter)

Title: How to render AmCharts as Canvas?

Body:
By using chart.exporting.getSVG() you will get the URI format of the chart. then you need to remove the svg type header and decode it back to SVG code before putting it into a canvas.

Here's a snippet of code that might help

var svg = decodeURIComponent(chart.exporting.getSVG()._v).split("?>")[1]
canvg(document.getElementById('canvas'), svg);

You will need the CANVG library to be included on your page.
AMCharts uses this inside their script.

AMCharts built in Export

chart.exporting.export("pdf");

will trigger the chart to export to pdf (with its own built in SVG to Canvas To Image to PDF converter)


问:
RegEx for capturing part of a string
I am trying to grab top level Markdown headings (i.e., headings beginning with a single hash -- # Introduction) in an .md doc with Python's re library and cannot for the life of me figure this out.

Here is the code I'm trying to execute:

```<code>import re

pattern = r"(# .+?\\n)"

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

header = re.search(pattern, text)
print(header.string)
</code>```

The result from the print(header.string) is:

# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n whereas I only want # Title\n

This example on regex101 says it should work, but I can't figure out why it isn't. https://regex101.com/r/u4ZIE0/9

答:
I'm guessing that we are wishing to extract the # Title\n, which in that case, your expression seems to be working fine with a slight modification:

```<code>(# .+?\\n)(.+)
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(# .+?\\n)(.+)"

test_str = "# Title\\n## Chapter\\n### sub-chapter#### The Bar\\nIt was a fall day.\\n"

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Title: RegEx for capturing part of a string

Body:
I am trying to grab top level Markdown headings (i.e., headings beginning with a single hash -- # Introduction) in an .md doc with Python's re library and cannot for the life of me figure this out.

Here is the code I'm trying to execute:

import re

pattern = r"(# .+?\\n)"

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

header = re.search(pattern, text)
print(header.string)

The result from the print(header.string) is:

# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n whereas I only want # Title\n

This example on regex101 says it should work, but I can't figure out why it isn't. https://regex101.com/r/u4ZIE0/9

Body:
I'm guessing that we are wishing to extract the # Title\n, which in that case, your expression seems to be working fine with a slight modification:

(# .+?\\n)(.+)

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(# .+?\\n)(.+)"

test_str = "# Title\\n## Chapter\\n### sub-chapter#### The Bar\\nIt was a fall day.\\n"

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.


问:
How to get the SQL server linked tables are connected to using VBA?
Is there a way to know which SQL Server the linked tables in MS Access database are pointing to using the ODBC connection?

I used the code below but I got the database name only and not the SQL server name.

```<code>Private Function checkconn()

Dim strConnect As String
Dim lngLocation As String

strConnect = CurrentDb.TableDefs("dbo_buh_summary").Connect
lngLocation = InStr(strConnect, ";DATABASE=")
If lngLocation <> 0 Then
GetDataPath = Mid(strConnect, lngLocation + 10)
End If

End Function
</code>```

答:
Assuming you used a FILE dsn to original link the tables?
(or a DSN less). I strong, but rather strong recommend you link always using a FILE dsn (not system or user). The reason is Access converts these links to DSN-less for you automatic. (and thus you don't need to setup a DSN on each computer).

Having noted  the above? You can grab the server and the database name with this:

```<code>Sub m34343()

  Dim strCon     As String

  strCon = CurrentDb.TableDefs("dbo_tblHotels3").Connect
  Debug.Print strCon

  Debug.Print Split(Split(strCon, "SERVER=")(1), ";")(0)
  Debug.Print Split(Split(strCon, "DATABASE=")(1), ";")(0)

End Sub
</code>```

Output:

```<code>ODBC;DRIVER=SQL Server;SERVER=ALBERTKALLAL-PC\SQLEXPRESS;
     Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=test3

ALBERTKALLAL-PC\SQLEXPRESS
test3
</code>```

So, I in above printed out the connection string, but then the next two lines grabs the server and the database name.

Body:
Is there a way to know which SQL Server the linked tables in MS Access database are pointing to using the ODBC connection?

I used the code below but I got the database name only and not the SQL server name.

Private Function checkconn()

Dim strConnect As String
Dim lngLocation As String

strConnect = CurrentDb.TableDefs("dbo_buh_summary").Connect
lngLocation = InStr(strConnect, ";DATABASE=")
If lngLocation <> 0 Then
GetDataPath = Mid(strConnect, lngLocation + 10)
End If

End Function

Body:
Assuming you used a FILE dsn to original link the tables?
(or a DSN less). I strong, but rather strong recommend you link always using a FILE dsn (not system or user). The reason is Access converts these links to DSN-less for you automatic. (and thus you don't need to setup a DSN on each computer).

Having noted  the above? You can grab the server and the database name with this:

Sub m34343()

  Dim strCon     As String

  strCon = CurrentDb.TableDefs("dbo_tblHotels3").Connect
  Debug.Print strCon

  Debug.Print Split(Split(strCon, "SERVER=")(1), ";")(0)
  Debug.Print Split(Split(strCon, "DATABASE=")(1), ";")(0)

End Sub

Output:

ODBC;DRIVER=SQL Server;SERVER=ALBERTKALLAL-PC\SQLEXPRESS;
     Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=test3

ALBERTKALLAL-PC\SQLEXPRESS
test3

So, I in above printed out the connection string, but then the next two lines grabs the server and the database name.


问:
Textview: Replace text between wildcard to smaller text
From a string, I need to make text between wildcard smaller.

Ex:
orange "apple" banana

"apple" need to apple in smaller font.

Part of the answer was probably a regex to catch text between "*".

Update: I've found that "*(.*?)*" may be a good way to catch the substring

Body: Pattern.compile("\\"([\w]+)\\"");


答:
The event listeners aren't being removed, so both functions are being called (potentially multiple times) depending on how many times the buttons are clicked.

Personally, I think it would be easier to create two buttons, each with independent click handlers, and hide/show them according to which one was clicked.

However, to resolve the current issue in your code, you'll need to remove the previous event listener using removeEventListener() before attaching the new one.

Title: Reuse function to delete an item

Body:
I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.

I'm using the latest chrome browser version.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Task 1</title>

<button type="button" class="btn btn-primary">Open Google</button>

<button type="button" class="btn btn-danger" id="danger">Delete form</button>

            <form id="form">

                    Example label
                    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

                    Another label
                    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

            </form>

document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);

let inner_form = document.getElementById('form').innerHTML;

function open_google() {
    window.open('http://google.com', '_blank');
}

let buttons;

function button_change(button) {
    switch(button) {
        case "success":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Add form';
            buttons[1].className = 'btn btn-success';
            document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
            break;
        case "danger":
            buttons = document.getElementsByClassName('btn');
            buttons[1].innerHTML = 'Delete form';
            buttons[1].className = 'btn btn-danger';
            break;
        default:
            break;
    }
}

function delete_function() {
    let element = document.getElementById('form');
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
    button_change("success");
}

function add_function() {
    document.getElementById('form').innerHTML = inner_form;
    button_change("danger");
}

Example code: https://codepen.io/anon/pen/xNjPYj


问:
I am entering birthdate inside edittext using datepicker. How to catch this?

Possible Duplicate:

  getDate with Jquery Datepicker

I have a registration page inside that I have birthdate box.
I am entering birthdate inside edittext using datepicker. How to catch this and put into web server. Do I need to parse to get integer ?

答:
Get reference to your EditText and use getText() method to get the text and
on How to put into web server,

This can be one of the way.
Check this,

Android (Java) Simple Send and receive with Server - Fast Setup Challenge


问:
Find next element by class after an specific element in the entire code (jQuery)
I need to do a jQuery script to mirror what I type in an <input> of class="a" to the next forward <input> of class="b", for every key pressed in the keyboard.

But I have some restrictions:

No, unfortunately I can't change the HTML. It is a legacy code. The only thing I can do is add a jQuery script.

No, it can't be a pure JavaScript code. It must be a jQuery code.

Yes, I need to use .on() because the div that contains the inputs are created dynamically.

I have tried using .next(), .find(), .each(), .closest()... but I'm a beginner, so I don't know how to use them properly. Probably it is something using these functions.

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

```

```$(document).on('keyup', '.a', function (ev) {
    //1 - get value in input and store in a variable
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
});
```

IMPORTANT: Please note that the code isn't exactly like this. Between one input and the other, there is some code, and they aren't event in the same parent div. The only thing I cant assure is that the next input is after, in the code, ant that it'll be inside a div.

答:
[1] To refer to the input you typed in you need to use $(this)

[2] To get its value use .val()

[3] To select the next .b element you need to use .next('.b')

$(this).next('.b').val($(this).val()) and I prefer to use input
  event instead of keyup

$(document).on('input', '.a', function (ev) {
    //1 - get value in input and store in a variable
    var GetThisValue = $(this).val();
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
    $(this).next('.b').val(GetThisValue);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div></code>```

[Other Selectors to select .b]

$(this).parent().find('.b')

$(this).closest('div').find('.b')

Snippet up to OP update

$(document).on('input', '.a', function (ev) {
    //1 - get value in input and store in a variable
    var GetThisValue = $(this).val();
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
    $(this).parent().nextAll('div:has(.b):first').find('.b').val(GetThisValue);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <input type="text" class="a" />
</div>
<div> any code </div>
<div>
    <input type="text" class="b" />
</div>
<!-- any code -->
<div>
    <input type="text" class="a" />
</div>
<div> any code </div>
<div>
    <input type="text" class="b" />
</div>
<div> any code </div>
<div>
    <input type="text" class="a" />
</div>
<!-- any code -->
<div>
    <input type="text" class="b" />
</div>
<!-- any code --></code>```

Body:
I need to do a jQuery script to mirror what I type in an <input> of class="a" to the next forward <input> of class="b", for every key pressed in the keyboard.

But I have some restrictions:

No, unfortunately I can't change the HTML. It is a legacy code. The only thing I can do is add a jQuery script.

No, it can't be a pure JavaScript code. It must be a jQuery code.

Yes, I need to use .on() because the div that contains the inputs are created dynamically.

I have tried using .next(), .find(), .each(), .closest()... but I'm a beginner, so I don't know how to use them properly. Probably it is something using these functions.

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

    <input type="text" class="a" />

    <input type="text" class="b" />

$(document).on('keyup', '.a', function (ev) {
    //1 - get value in input and store in a variable
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
});

IMPORTANT: Please note that the code isn't exactly like this. Between one input and the other, there is some code, and they aren't event in the same parent div. The only thing I cant assure is that the next input is after, in the code, ant that it'll be inside a div.

Body:
[1] To refer to the input you typed in you need to use $(this)

[2] To get its value use .val()

[3] To select the next .b element you need to use .next('.b')

$(this).next('.b').val($(this).val()) and I prefer to use input
  event instead of keyup

$(document).on('input', '.a', function (ev) {
    //1 - get value in input and store in a variable
    var GetThisValue = $(this).val();
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
    $(this).next('.b').val(GetThisValue);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div>
<div>
    <input type="text" class="a" />
    <input type="text" class="b" />
</div>

[Other Selectors to select .b]

$(this).parent().find('.b')

$(this).closest('div').find('.b')

Snippet up to OP update

$(document).on('input', '.a', function (ev) {
    //1 - get value in input and store in a variable
    var GetThisValue = $(this).val();
    //2 - search for the next forward input of class="b"
    //3 - set the variable to the value of input
    $(this).parent().nextAll('div:has(.b):first').find('.b').val(GetThisValue);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <input type="text" class="a" />
</div>
<div> any code </div>
<div>
    <input type="text" class="b" />
</div>
<!-- any code -->
<div>
    <input type="text" class="a" />
</div>
<div> any code </div>
<div>
    <input type="text" class="b" />
</div>
<div> any code </div>
<div>
    <input type="text" class="a" />
</div>
<!-- any code -->
<div>
    <input type="text" class="b" />
</div>
<!-- any code -->


问:
How do I limit a textarea box?
Can someone tell me how do I limit a text area to certain characters only? Let's say 250.

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p></code>```

答:
You can use maxlength attribute of textarea

The maximum number of characters (unicode code points) that the user
  can enter. If this value isn't specified, the user can enter an
  unlimited number of characters.

<textarea col="8" rows="8" maxlength='5'></textarea>```
</div>
</div>
</p>

<blockquote>
  <p>And what if I want to show how many characters remaining? Like how I'm
  seeing in the comments I'm writing?</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `Remaining charcaters   ${maxLength - Number(value.length)}`

}</code>```

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id='input' value=''></textarea>

```

Title: How do I limit a textarea box?

Body:
Can someone tell me how do I limit a text area to certain characters only? Let's say 250.

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`

}

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>

250 characters remaining

Body:
You can use maxlength attribute of textarea

The maximum number of characters (unicode code points) that the user
  can enter. If this value isn't specified, the user can enter an
  unlimited number of characters.

<textarea col="8" rows="8" maxlength='5'></textarea>

And what if I want to show how many characters remaining? Like how I'm
  seeing in the comments I'm writing?

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `Remaining charcaters   ${maxLength - Number(value.length)}`

}

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id='input' value=''></textarea>
<p id='remaining'></p>


问:
Why did Spark processed the same data twice?
I've stuck into a weird situation when the simplest possible spark application seemingly completed the same job twice.

What I've done

The application itself executes the query:

```<code>SELECT date, field1, field2, ..., field10
FROM table1
WHERE field1 = <some number>
  AND date BETWEEN date('2018-05-01') AND date('2018-05-30')
  ORDER BY 1
</code>```

and stores the results into HDFS.

Table table1 is a bunch of parquet files stored on HDFS and partitioned as follows

```<code>/root/date=2018-05-01/hour=0/data-1.snappy.parquet
/root/date=2018-05-01/hour=0/data-2.snappy.parquet
...
/root/date=2018-05-01/hour=1/data-1.snappy.parquet
...
/root/date=2018-05-02/hour=0/data-1.snappy.parquet
...
etc.
</code>```

All parquet files are from 700M to 2G size and have the same schema: 10 non null fields of int or bigint types.

The result of the application is tiny in size -- a couple of thousand rows only.

My spark application was running on YARN with cluster mode. Base spark parameters were

```<code>spark.driver.memory=2g
spark.executor.memory=4g
spark.executor.cores=4
spark.dynamicAllocation.enabled=true
spark.shuffle.service.enabled=true
spark.submit.deployMode=cluster
</code>```

During execution a couple of containers were preempted, no errors and no failures occured. The whole application completed in one attempt.

The weird thing

Screenshots from Spark UI:

As it can be seen stage 2 and 4 both processed the same number of input rows, but stage 4 also did some shuffling (those were the result rows). The failed tasks are those which containers were preempted.

So it looks like my application processed the same files twice.

I have no clue how's that possible and what happened. Please, help me understand why it Spark is doing such a weird thing.

Actual physical plan:

```<code>== Physical Plan ==
Execute InsertIntoHadoopFsRelationCommand InsertIntoHadoopFsRelationCommand hdfs://hadoop/root/tmp/1530123240802-PrQXaOjPoDqCBhfadgrXBiTtfvFrQRlB, false, CSV, Map(path -> /root/tmp/1530123240802-PrQXaOjPoDqCBhfadgrXBiTtfvFrQRlB), Overwrite, [date#10, field1#1L, field0#0L, field3#3L, field2#2L, field5#5, field4#4, field6#6L, field7#7]
+- Coalesce 16
   +- *(2) Sort [date#10 ASC NULLS FIRST], true, 0
      +- Exchange rangepartitioning(date#10 ASC NULLS FIRST, 200)
         +- *(1) Project [date#10, field1#1L, field0#0L, field3#3L, field2#2L, field5#5, field4#4, field6#6L, field7#7]
            +- *(1) Filter (isnotnull(field1#1L) && (field1#1L = 1234567890))
               +- *(1) FileScan parquet default.table1[field0#0L,field1#1L,field2#2L,field3#3L,field4#4,field5#5,field6#6L,field7#7,date#10,hour#11] Batched: true, Format: Parquet, Location: InMemoryFileIndex[hdfs://hadoop/table1], PartitionCount: 714, PartitionFilters: [(date#10 >= 17652), (date#10 <= 17682)], PushedFilters: [IsNotNull(field1), EqualTo(field1,1234567890)], ReadSchema: struct<field0:bigint,field1:bigint,field2:bigint,field3:bigint,field4:int,field5:int,field6:bigint,field7:...
</code>```

Here are DAGs for Stages 2 and 4:

答:
I ran into this exact same issue, and it turns out this behavior is entirely normal.

I observed this behavior in a Spark job that simply reads from HDFS, does some lightweight processing, and uses the orderBy method to sort on a column before writing back to HDFS. In the Spark UI, I saw two jobs that would scan the entire 6 TB table, just as you did. The first job used very little memory, wrote no shuffle records, and wrote no records to HDFS.

It turns out that the root cause is that before actually sorting the data, Spark executes a sampling operation that helps it define a RangePartitioner it uses to partition the data for its sorting algorithm: It needs to know the approximate range of the data in the column that defines the sort key to define a good RangePartitioner.

This operation is mentioned on this blog:

https://blog.cloudera.com/blog/2015/01/improving-sort-performance-in-apache-spark-its-a-double/

this StackOverflow post:

How does Spark achieve sort order?

and also in the great book, "High Performance Spark," by Holden Karau and Rachel Warran, on pg. 143.

In my case, I know the range of the key, so it occurred to me that I should in principle be able to define a RangePartitioner a priori. However, I dug around in the Spark source code for its sort method, but I didn't find any kind of workaround where I could pass a range explicitly.

Body:
I've stuck into a weird situation when the simplest possible spark application seemingly completed the same job twice.

What I've done

The application itself executes the query:

SELECT date, field1, field2, ..., field10
FROM table1
WHERE field1 = <some number>
  AND date BETWEEN date('2018-05-01') AND date('2018-05-30')
  ORDER BY 1

and stores the results into HDFS.

Table table1 is a bunch of parquet files stored on HDFS and partitioned as follows

/root/date=2018-05-01/hour=0/data-1.snappy.parquet
/root/date=2018-05-01/hour=0/data-2.snappy.parquet
...
/root/date=2018-05-01/hour=1/data-1.snappy.parquet
...
/root/date=2018-05-02/hour=0/data-1.snappy.parquet
...
etc.

All parquet files are from 700M to 2G size and have the same schema: 10 non null fields of int or bigint types.

The result of the application is tiny in size -- a couple of thousand rows only.

My spark application was running on YARN with cluster mode. Base spark parameters were

spark.driver.memory=2g
spark.executor.memory=4g
spark.executor.cores=4
spark.dynamicAllocation.enabled=true
spark.shuffle.service.enabled=true
spark.submit.deployMode=cluster

During execution a couple of containers were preempted, no errors and no failures occured. The whole application completed in one attempt.

The weird thing

Screenshots from Spark UI:

As it can be seen stage 2 and 4 both processed the same number of input rows, but stage 4 also did some shuffling (those were the result rows). The failed tasks are those which containers were preempted.

So it looks like my application processed the same files twice.

I have no clue how's that possible and what happened. Please, help me understand why it Spark is doing such a weird thing.

Actual physical plan:

== Physical Plan ==
Execute InsertIntoHadoopFsRelationCommand InsertIntoHadoopFsRelationCommand hdfs://hadoop/root/tmp/1530123240802-PrQXaOjPoDqCBhfadgrXBiTtfvFrQRlB, false, CSV, Map(path -> /root/tmp/1530123240802-PrQXaOjPoDqCBhfadgrXBiTtfvFrQRlB), Overwrite, [date#10, field1#1L, field0#0L, field3#3L, field2#2L, field5#5, field4#4, field6#6L, field7#7]
+- Coalesce 16
   +- *(2) Sort [date#10 ASC NULLS FIRST], true, 0
      +- Exchange rangepartitioning(date#10 ASC NULLS FIRST, 200)
         +- *(1) Project [date#10, field1#1L, field0#0L, field3#3L, field2#2L, field5#5, field4#4, field6#6L, field7#7]
            +- *(1) Filter (isnotnull(field1#1L) && (field1#1L = 1234567890))
               +- *(1) FileScan parquet default.table1[field0#0L,field1#1L,field2#2L,field3#3L,field4#4,field5#5,field6#6L,field7#7,date#10,hour#11] Batched: true, Format: Parquet, Location: InMemoryFileIndex[hdfs://hadoop/table1], PartitionCount: 714, PartitionFilters: [(date#10 >= 17652), (date#10 <= 17682)], PushedFilters: [IsNotNull(field1), EqualTo(field1,1234567890)], ReadSchema: struct<field0:bigint,field1:bigint,field2:bigint,field3:bigint,field4:int,field5:int,field6:bigint,field7:...

Here are DAGs for Stages 2 and 4:


问:
How to add dynamically v-model and it's initial values to existed html elements by vuejs
For SEO purposes I need to render html elements by php. For example I have these elements.

```<code><?php foreach ($elements as $key => $element): ?>
    <select name="first" v-model="model[<?= $key; ?>]">
        <option value="">Select</option>
        <option value="1">Some Text</option>
        <option value="2">Some Text</option>
    </select>
    <select name="second" v-model="model[<?= $key; ?>]>
        <option value="">Select</option>
        <option value="4">Some Text</option>
        <option value="5">Some Text</option>
    </select>
    ...
    ...
    ...
    <select name="eleven" v-model="model[<?= $key; ?>]>
        <option value="">Select</option>
        <option value="101">Some Text</option>
        <option value="102">Some Text</option>
    </select>
<?php endforeach; ?>
</code>```

And probably I can manipulate these elements like this on vue side.

```<code>const count_models = <?= count($elements) ?>; // in the html
const app = new Vue({
  el: '#app',
  data: {
    model:[]
  },
  mounted(){
    console.log(this.model);
    for (let $i = 0; $i < count_models; $i++) {
        this.model[$i] = "";
    }
  }
})
</code>```

I cannot declare the initial values for model[?]. I need an xhr or assign counted items to a javascript variable to get how many select element I have on DOM and to declare initial values as null for each model[]. Even I redeclare the initial values of the models, it doesn't bind. I just put an example on jsFiddle. In Angular1 there was ng-init attribute to declare initial value for the model.

How can I solve this problem ?

https://jsfiddle.net/ks7jmgwv/1/

答:
you just encountered one of the most common gotchas of Vuejs: reactivity (and therefor the lack off)!

The issue here is when the model property is created it's just an empty array/object and any property that you add to that element it's not going to be reactive: that means any kind of change made programmatically won't trigger the Vue's internal whatches, the only reason that the v-model still works is that the changes made by the user and not by the code does actually trigger native HTML events.

You have two possible solutions:

Ignore the reactivy part (but you won't be able to programmatically update the selected value, or at least it won't be visible) and just make sure that the 'Select' option will be selected by default by assigning it the correct value (in that way you can just skip all the default for-loop initialization).

<option :value="undefined" selected="selected" disabled>Select</option>

Follow the offical way suggested by the Vuejs' documentation to add a new property to an object and still having the advantage of reactivity

this.$set(this.model, $i, "");

You can check this plunker in which I'm showing you both the ways of obtaining your goal:
https://jsfiddle.net/8y7eu39z/18/

Also, did you know that for placeholder options in a select you can add the attribute disabled?

Reactivy Reference: https://v2.vuejs.org/v2/guide/reactivity.html

Also: if you want a "null" as a default value but did not manage to find a way to make it being recognized by the "select" options just use :value="null" instead of value="null" and then you should be able to use
this.$set(this.model, $i, null);

Body:
For SEO purposes I need to render html elements by php. For example I have these elements.

<?php foreach ($elements as $key => $element): ?>
    <select name="first" v-model="model[<?= $key; ?>]">
        <option value="">Select</option>
        <option value="1">Some Text</option>
        <option value="2">Some Text</option>
    </select>
    <select name="second" v-model="model[<?= $key; ?>]>
        <option value="">Select</option>
        <option value="4">Some Text</option>
        <option value="5">Some Text</option>
    </select>
    ...
    ...
    ...
    <select name="eleven" v-model="model[<?= $key; ?>]>
        <option value="">Select</option>
        <option value="101">Some Text</option>
        <option value="102">Some Text</option>
    </select>
<?php endforeach; ?>

And probably I can manipulate these elements like this on vue side.

const count_models = <?= count($elements) ?>; // in the html
const app = new Vue({
  el: '#app',
  data: {
    model:[]
  },
  mounted(){
    console.log(this.model);
    for (let $i = 0; $i < count_models; $i++) {
        this.model[$i] = "";
    }
  }
})

I cannot declare the initial values for model[?]. I need an xhr or assign counted items to a javascript variable to get how many select element I have on DOM and to declare initial values as null for each model[]. Even I redeclare the initial values of the models, it doesn't bind. I just put an example on jsFiddle. In Angular1 there was ng-init attribute to declare initial value for the model.

How can I solve this problem ?

https://jsfiddle.net/ks7jmgwv/1/


问:
Custom Class CLed doesnt change color always
I have a  user interface where I want to  change a Picture color according to the connection stability, simulating a ON/OFF LED.  But the problem is that it only works when going red. And in fact, in another "LED" it goes green without telling to.

The rectangle that goes red in the images

I have tried with things like m_statusMotor.UpdateWindow() or even UpdateData(0). However it does not work. When debugging I have seen that the value m_statusMotor.m_color changes correctly to 0, but doesnt change the LED color.

So this is what My class CLed does:

```<code>void CLed::OnPaint()
{
  CPaintDC dc(this);
  CRect r;
  GetClientRect(r);
  CBrush b1;
  switch(m_color){
  case 0:
    b1.CreateSolidBrush(RGB(0, 255, 0)); // verde
    break;
  case 1:
    b1.CreateSolidBrush(RGB(255, 0, 0)); // rojo
    break;
  case 2:
    b1.CreateSolidBrush(RGB(255, 118, 0)); // ambar
    break;
  default:
    b1.CreateSolidBrush(RGB(160, 160, 160)); // gris
    break;
  }
  dc.SelectObject(&b1);
  dc.Rectangle(r);
}
</code>```

This is where it does change to red:

```<code>if(!misoc1.Connect(m_ipMotor, m_portMotor)){
                            if(!connectedmotor) m_log.AddString("No conecta con el puerto de motor");
                            connectedmotor = true;
                            firststrmotor = false;
                            m_statusMotor.m_color = 1;
                            m_statusMotor.Invalidate(true);
                            m_log.UpdateWindow();
                            UpdateData(0);
                            m_statusMotor.UpdateWindow();

                    }else connectedmotor = false;
</code>```

And this is where it doenst change to green

```<code>    if(!firststrmotor){
                        m_log.AddString("Motor OK");
                        m_log.UpdateWindow();
                        m_statusMotor.m_color = 0;
                        UpdateData(0);
                        m_statusMotor.UpdateWindow();

                    }
</code>```

m_statusMotor is CLed class;

Any ideas why it works some times and some times not??

答:
```<code>function1()
{
    m_statusMotor.m_color = 1;
    m_statusMotor.Invalidate(true);
    m_statusMotor.UpdateWindow();
    ...
}

function2()
{
    m_statusMotor.m_color = 0;
    m_statusMotor.UpdateWindow();
    ...
}
</code>```

In the first function you have correctly called Invalidate, followed by the optional UpdateWindow (UpdateWindow can be useful here if the function is blocking windows messages)

In the second function you forgot to call Invalidate, you just called UpdateWindow which does not have any effect in this case. There is nothing to invalidate, so no paint messages will be sent, as explained in documentation:

UpdateWindow:

The UpdateWindow function updates the client area of the specified
  window by sending a WM_PAINT message to the window if the window's
  update region is not empty. The function sends a WM_PAINT message
  directly to the window procedure of the specified window, bypassing
  the application queue. If the update region is empty, no message is
  sent.

Therefore, call Invalidate() followed by the optional UpdateWindow().

Or call RedrawWindow() which will invalidate and update immediately, as noted in comments.

Side note, consider using CDC::FillSolidRect in your OnPaint function.

Body:
I have a  user interface where I want to  change a Picture color according to the connection stability, simulating a ON/OFF LED.  But the problem is that it only works when going red. And in fact, in another "LED" it goes green without telling to.

The rectangle that goes red in the images

I have tried with things like m_statusMotor.UpdateWindow() or even UpdateData(0). However it does not work. When debugging I have seen that the value m_statusMotor.m_color changes correctly to 0, but doesnt change the LED color.

So this is what My class CLed does:

void CLed::OnPaint()
{
  CPaintDC dc(this);
  CRect r;
  GetClientRect(r);
  CBrush b1;
  switch(m_color){
  case 0:
    b1.CreateSolidBrush(RGB(0, 255, 0)); // verde
    break;
  case 1:
    b1.CreateSolidBrush(RGB(255, 0, 0)); // rojo
    break;
  case 2:
    b1.CreateSolidBrush(RGB(255, 118, 0)); // ambar
    break;
  default:
    b1.CreateSolidBrush(RGB(160, 160, 160)); // gris
    break;
  }
  dc.SelectObject(&b1);
  dc.Rectangle(r);
}

This is where it does change to red:

if(!misoc1.Connect(m_ipMotor, m_portMotor)){
                            if(!connectedmotor) m_log.AddString("No conecta con el puerto de motor");
                            connectedmotor = true;
                            firststrmotor = false;
                            m_statusMotor.m_color = 1;
                            m_statusMotor.Invalidate(true);
                            m_log.UpdateWindow();
                            UpdateData(0);
                            m_statusMotor.UpdateWindow();

                    }else connectedmotor = false;

And this is where it doenst change to green

    if(!firststrmotor){
                        m_log.AddString("Motor OK");
                        m_log.UpdateWindow();
                        m_statusMotor.m_color = 0;
                        UpdateData(0);
                        m_statusMotor.UpdateWindow();

                    }

m_statusMotor is CLed class;

Any ideas why it works some times and some times not??

Body:
function1()
{
    m_statusMotor.m_color = 1;
    m_statusMotor.Invalidate(true);
    m_statusMotor.UpdateWindow();
    ...
}

function2()
{
    m_statusMotor.m_color = 0;
    m_statusMotor.UpdateWindow();
    ...
}

In the first function you have correctly called Invalidate, followed by the optional UpdateWindow (UpdateWindow can be useful here if the function is blocking windows messages)

In the second function you forgot to call Invalidate, you just called UpdateWindow which does not have any effect in this case. There is nothing to invalidate, so no paint messages will be sent, as explained in documentation:

UpdateWindow:

The UpdateWindow function updates the client area of the specified
  window by sending a WM_PAINT message to the window if the window's
  update region is not empty. The function sends a WM_PAINT message
  directly to the window procedure of the specified window, bypassing
  the application queue. If the update region is empty, no message is
  sent.

Therefore, call Invalidate() followed by the optional UpdateWindow().

Or call RedrawWindow() which will invalidate and update immediately, as noted in comments.

Side note, consider using CDC::FillSolidRect in your OnPaint function.