答:
Your question suggests that you think you can a function in the templates like a normal function (ie activityperiod.objects.get(...)).

You can't, the templating system is not made like this (for security reasons amongst others).

You should do something like, in your models:

```<code>def call_response(request):
    # ! first() not "all()" (if > 1 user, you'll have problem)!
    user = User.objects.first()
    activityperiod = activityperiod.objects.get(user=user)
    return render(request, "Test/list.html",
                  {"users":user ,"activityperiod":activityperiod})
</code>```

Title: how to use django model object in django templates?

Body:
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the  ActivityPeriod(model) of that user. Please check my code for the clarity:

Here is my code:

views.py

from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})

Test/list.html

{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}

But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'

What is the correct way? Can anyone please share it with me.

Body:
Your question suggests that you think you can a function in the templates like a normal function (ie activityperiod.objects.get(...)).

You can't, the templating system is not made like this (for security reasons amongst others).

You should do something like, in your models:

def call_response(request):
    # ! first() not "all()" (if > 1 user, you'll have problem)!
    user = User.objects.first()
    activityperiod = activityperiod.objects.get(user=user)
    return render(request, "Test/list.html",
                  {"users":user ,"activityperiod":activityperiod})


来源: stackexchange

问:
convert string to date object (no timestamp included in csv entry)
I keep getting a value error here. What am I doing wrong? The CSV I am reading and writing does not have a timestamp with each date entry. The dates are just entered in 'mm-dd-yyyy' format.

```<code>Traceback (most recent call last):
  File "C:/Users/Matthew Olive/PycharmProjects/excel_scripts/contango_cleaner.py", line 17, in <module>
    dateS = datetime.strptime(row[2], "%m-%d-%Y")
  File "C:\Users\Matthew Olive\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\Matthew Olive\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '' does not match format '%m-%d-%Y'
</code>```

here is my code:

```<code>import csv
from datetime import datetime

path = "C:\\Users\\Matthew Olive\\Desktop\\Trading Stuff\\sample_for_python .csv"
file = open(path, newline = '')
reader = csv.reader(file)
data =[]
for row in reader:
    dateC = datetime.strptime(row[0], "%m-%d-%Y")
    dateS = datetime.strptime(row[2], "%m-%d-%Y")
    contango = float(row[1])
    open_price = float(row[3])
    close_price = float(row[4])
    data.append([dateC, contango, dateS, open_price, close_price])
print(data[0])
</code>```

The problem seems to come when I am trying to convert the date strings into proper datetime objects. The end goal of the program is to say "If dateC does not match dateS, then delete the first and second entry in that particular row. Then create a new CSV file and export it into Excel. I am trying to automate a process I do manually a lot. (For each row, the first two columns are not needed if they don't have matching date and float values in the third, fourth, and fifth columns)

Here is how my CSV is structured (columns):
dateC and dateS should be datetime objects while the others are floats

[dateC, contango, dateS, open_price, close_price]

答:
An illustration of my comment; how this could work out using pandas:

```<code>import io
import pandas as pd

# some example input with missing dates (empty fields in the csv)...
data = io.StringIO("""dateC,contango,dateS,open_price,close_price
02-03-2020,1,02-04-2020,50,55
,2,02-04-2020,51,56
02-03-2020,3,,52,57""")

# just replace 'data' with the path to your csv:
df = pd.read_csv(data)

df['dateC'] = pd.to_datetime(df['dateC'], errors='coerce')
df['dateS'] = pd.to_datetime(df['dateS'], errors='coerce')

# df
#        dateC  contango      dateS  open_price  close_price
# 0 2020-02-03         1 2020-02-04          50           55
# 1        NaT         2 2020-02-04          51           56
# 2 2020-02-03         3        NaT          52           57
</code>```

Some references:

pandas
DataFrames

pandas.read_csv

pandas.to_datetime

ContentLicense: CC BY-SA 4.0

Body:
I keep getting a value error here. What am I doing wrong? The CSV I am reading and writing does not have a timestamp with each date entry. The dates are just entered in 'mm-dd-yyyy' format.

Traceback (most recent call last):
  File "C:/Users/Matthew Olive/PycharmProjects/excel_scripts/contango_cleaner.py", line 17, in <module>
    dateS = datetime.strptime(row[2], "%m-%d-%Y")
  File "C:\Users\Matthew Olive\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\Matthew Olive\AppData\Local\Programs\Python\Python38\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '' does not match format '%m-%d-%Y'

here is my code:

import csv
from datetime import datetime

path = "C:\\Users\\Matthew Olive\\Desktop\\Trading Stuff\\sample_for_python .csv"
file = open(path, newline = '')
reader = csv.reader(file)
data =[]
for row in reader:
    dateC = datetime.strptime(row[0], "%m-%d-%Y")
    dateS = datetime.strptime(row[2], "%m-%d-%Y")
    contango = float(row[1])
    open_price = float(row[3])
    close_price = float(row[4])
    data.append([dateC, contango, dateS, open_price, close_price])
print(data[0])

The problem seems to come when I am trying to convert the date strings into proper datetime objects. The end goal of the program is to say "If dateC does not match dateS, then delete the first and second entry in that particular row. Then create a new CSV file and export it into Excel. I am trying to automate a process I do manually a lot. (For each row, the first two columns are not needed if they don't have matching date and float values in the third, fourth, and fifth columns)

Here is how my CSV is structured (columns):
dateC and dateS should be datetime objects while the others are floats

[dateC, contango, dateS, open_price, close_price]

Body:
An illustration of my comment; how this could work out using pandas:

import io
import pandas as pd

# some example input with missing dates (empty fields in the csv)...
data = io.StringIO("""dateC,contango,dateS,open_price,close_price
02-03-2020,1,02-04-2020,50,55
,2,02-04-2020,51,56
02-03-2020,3,,52,57""")

# just replace 'data' with the path to your csv:
df = pd.read_csv(data)

df['dateC'] = pd.to_datetime(df['dateC'], errors='coerce')
df['dateS'] = pd.to_datetime(df['dateS'], errors='coerce')

# df
#        dateC  contango      dateS  open_price  close_price
# 0 2020-02-03         1 2020-02-04          50           55
# 1        NaT         2 2020-02-04          51           56
# 2 2020-02-03         3        NaT          52           57

Some references:

pandas
DataFrames

pandas.read_csv

pandas.to_datetime


问:
How to make background of table cell transparent
I am creating a table inside a table for my "all users" page. The first table was divided in to two parts--the ads and the users--. Inside the "users" table under
...
, I created another table for each of the user's data to appear via php.

Here's the image : http://postimg.org/image/3mbeyb411/

As you can see in the image, the right side of the parent table (which is larger than the left one) contained the "users" table where their profile pictures appeared which is good.

Now I put this nice blurry background on my page but the parent table's white cell background is blocking it.

How can I make that white background become transparent? I tried doing the background:transparent; but to no avail.

```<code><table id = "MainTable">
  <tr>
    <td width = "20%">

     </td>

    <td width = "80%">
        <table.......>***php users appear code here***</table>
    </td>
 </tr>
</table>
</code>```

And for CSS

```<code>#MainTable {
    width: 100%;
    background-color: #D8F0DA;
    border: 1px;
    min-width: 100%;
    position: relative;
    opacity: 0.97;
    background: transparent;
}
</code>```

Please I really need your help. I've been Googling this for days and still didn't find a single answer

UPDATE

What I was looking for is something like this  but still I didn't find it on the web. Or is it even possible to make the table and the cell's background transparent?

答:
Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.</p>

```<code>style="opacity: 0%;"
</code>```

Body:
I am creating a table inside a table for my "all users" page. The first table was divided in to two parts--the ads and the users--. Inside the "users" table under
...
, I created another table for each of the user's data to appear via php.

Here's the image : http://postimg.org/image/3mbeyb411/

As you can see in the image, the right side of the parent table (which is larger than the left one) contained the "users" table where their profile pictures appeared which is good.

Now I put this nice blurry background on my page but the parent table's white cell background is blocking it.

How can I make that white background become transparent? I tried doing the background:transparent; but to no avail.

***php users appear code here***

And for CSS

#MainTable {
    width: 100%;
    background-color: #D8F0DA;
    border: 1px;
    min-width: 100%;
    position: relative;
    opacity: 0.97;
    background: transparent;
}

Please I really need your help. I've been Googling this for days and still didn't find a single answer

UPDATE

What I was looking for is something like this  but still I didn't find it on the web. Or is it even possible to make the table and the cell's background transparent?

Body:
Just set the opacity for the inner table. You can do inline CSS if you want it just for a specific table element, so it doesn't apply to the entire table.

style="opacity: 0%;"


问:
How can I call some code after a property on my state object has been defined?
I have a component, which has a prop passed to it.

It seems that this prop is undefined at the point componentDidMount() is called.

Here's my component:

```<code>export class BookInventoryDetail extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            book_inventories: []
        }
    }

    componentDidMount() {
        console.log(this.props) // the prop book_id is undefined.
        Book.fetchInventories(this.props.book_id).then(book_inventories => {
            this.setState({book_inventories})
        })
    }

    render() {
        return (
            <div>

            </div>
        )
    }
}
</code>```

Am I doing this correctly, or is book_id simply not defined when I think it should be in the parent?

Either I'm doing something wrong in this component, or the issue exists in the parent component, and the prop isn't being set when I think it is.

答: All props should be already available in componentDidMount lifecycle method. I assume you sholud check book_id prop in parent component. Is everything ok there? May be you do not pass this value.

Body:
I have a component, which has a prop passed to it.

It seems that this prop is undefined at the point componentDidMount() is called.

Here's my component:

export class BookInventoryDetail extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            book_inventories: []
        }
    }

    componentDidMount() {
        console.log(this.props) // the prop book_id is undefined.
        Book.fetchInventories(this.props.book_id).then(book_inventories => {
            this.setState({book_inventories})
        })
    }

    render() {
        return (

        )
    }
}

Am I doing this correctly, or is book_id simply not defined when I think it should be in the parent?

Either I'm doing something wrong in this component, or the issue exists in the parent component, and the prop isn't being set when I think it is.


问:
Merging XML in PHP
Somthing wrong here, dont seem to be able to merge XML DOMDocumet's I get the error, "Fatal error: Call to undefined method DOMElement::importNode() in C:\xampp\htdocs\xmltest\xmltest.php on line 27" can anybody help me put this code right...</p>

```<code><?php
// include required files
include 'XML/Query2XML.php';
include 'MDB2.php';

// prepare xml document
$dom = new DomDocument('1.0');

// create tables section
$tables = $dom->appendChild($dom->createElement('tables'));

// create container for tblclients
$tblclients = $tables->appendChild($dom->createElement('tblclients'));

try {
// initialize Query2XML object
$q2x = XML_Query2XML::factory(MDB2::factory('mysql://root:@localhost/db_solconmgr'));

// generate SQL query
$sql = "SELECT ClientID, Client, Contacts, 'Address Line 1' as AddressLine1, 'Address Line 2' as AddressLine2, City, County, 'Zip Code' as ZipCode, Telephone, Fax, Mobile, 'E-mail Address' as EmailAddress, Date FROM tblclients";

// get results as XML
$tblclientsXML = $q2x->getFlatXML($sql);

//$dom = $tblclientsXML;

$node = $tblclients->importNode($tblclientsXML, true);

// send output to browser
header('Content-Type: text/xml');
$dom->formatOutput = true;
echo $dom->saveXML();
} catch (Exception $e) {
echo $e->getMessage();
}
?>
</code>```

答:
importNode() is a method belonging to the document, not an element. You want to import into the document ($dom) then append to the element ($tblclients).

A node is needed when importing (and $tblclientsXML is not a node, it's a document) so importing the generated XML would look similar to:

```<code>$tblclientsElement = $tblclientsXML->documentElement;
$tblclientsXML = $dom->importNode($tblclientsElement, TRUE);
$tblclients->appendChild($tblclientsXML);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Merging XML in PHP

Body:
Somthing wrong here, dont seem to be able to merge XML DOMDocumet's I get the error, "Fatal error: Call to undefined method DOMElement::importNode() in C:\xampp\htdocs\xmltest\xmltest.php on line 27" can anybody help me put this code right...

<?php
// include required files
include 'XML/Query2XML.php';
include 'MDB2.php';

// prepare xml document
$dom = new DomDocument('1.0');

// create tables section
$tables = $dom->appendChild($dom->createElement('tables'));

// create container for tblclients
$tblclients = $tables->appendChild($dom->createElement('tblclients'));

try {
// initialize Query2XML object
$q2x = XML_Query2XML::factory(MDB2::factory('mysql://root:@localhost/db_solconmgr'));

// generate SQL query
$sql = "SELECT ClientID, Client, Contacts, 'Address Line 1' as AddressLine1, 'Address Line 2' as AddressLine2, City, County, 'Zip Code' as ZipCode, Telephone, Fax, Mobile, 'E-mail Address' as EmailAddress, Date FROM tblclients";

// get results as XML
$tblclientsXML = $q2x->getFlatXML($sql);

//$dom = $tblclientsXML;

$node = $tblclients->importNode($tblclientsXML, true);

// send output to browser
header('Content-Type: text/xml');
$dom->formatOutput = true;
echo $dom->saveXML();
} catch (Exception $e) {
echo $e->getMessage();
}
?>

Body:
importNode() is a method belonging to the document, not an element. You want to import into the document ($dom) then append to the element ($tblclients).

A node is needed when importing (and $tblclientsXML is not a node, it's a document) so importing the generated XML would look similar to:

$tblclientsElement = $tblclientsXML->documentElement;
$tblclientsXML = $dom->importNode($tblclientsElement, TRUE);
$tblclients->appendChild($tblclientsXML);


问:
c/c++ extension downloading for long time in vscode
I am using the c++/c extension in vs code first time and after clicking on installing c/c++extension by microsoft and i cannot use this

```<code>**// Simple C++ program to display "Hello World"
// Header file for input output functions
#include<iostream>
using namespace std;
// main function -
// where the execution of program begins
int main()
{
    // prints hello world
    cout<<"Hello World";

    return 0;
}**
</code>```

答:
You can try to download the extension manually

Go to vscode cpp tools release page https://github.com/Microsoft/vscode-cpptools/releases

Scroll down and download the .vsix file corresponding to your OS (in your case it's win32)
look for your OS in a section like this

Open command prompt and type in
code --install-extension <path to your downloaded .vsix file>

Close and reopen VSCode and the extension downloading window should no longer appear

Body:
I am using the c++/c extension in vs code first time and after clicking on installing c/c++extension by microsoft and i cannot use this

**// Simple C++ program to display "Hello World"
// Header file for input output functions
#include<iostream>
using namespace std;
// main function -
// where the execution of program begins
int main()
{
    // prints hello world
    cout<<"Hello World";

    return 0;
}**


问:
How to create a python script that handles an input string or an input file?
I would like to make a python script that can either process a string fed into the command line

python my_script.py "Hello World"

or a set of strings inside a file (e.g. input_file.txt)

python my_script.py -i input_file.txt

Is there a way to do this via argparse? So far I can handle input files, but I don't know how to add the option of just processing a string fed directly in the command line.

答:
To process a command line string, you can use sys.argv, which is a list of all the arguments fed into the command line.

main.py:

```<code>import sys
print(sys.argv)
</code>```

Running the following line in the CLI

>> python main.py foo bar "hello world"

would output:

['main.py', 'foo', 'bar', 'hello world']

Body:
To process a command line string, you can use sys.argv, which is a list of all the arguments fed into the command line.

main.py:

import sys
print(sys.argv)

Running the following line in the CLI

>> python main.py foo bar "hello world"

would output:

['main.py', 'foo', 'bar', 'hello world']


问:
"jt: command not found"
I want to change the Jupyter notebook theme, so I installed the themes with:

```<code>pip install jupyterthemes
</code>```

The installation seems working fine but when I try to change the theme:

```<code>jt -t <theme_name>
</code>```

I get:

```<code>jt: command not found
</code>```

I tried to uninstall the themes:

```<code>pip uninstall jupyterthemes
</code>```

but I got:

```<code>Skipping jupyterthemes as it is not installed
</code>```

During the installation I got no error though.

What should I do to install the themes properly?

I'm using Ubuntu 16.04, and I installed Jupyter Notebook with pip. Jupyter works fine, it's just the themes that don't work

答:
Simply run this. I was facing same issue, it worked
.</p>

```<code>sudo pip install jupyterthemes
</code>```

Title: "jt: command not found"

Body:
I want to change the Jupyter notebook theme, so I installed the themes with:

pip install jupyterthemes

The installation seems working fine but when I try to change the theme:

jt -t <theme_name>

I get:

jt: command not found

I tried to uninstall the themes:

pip uninstall jupyterthemes

but I got:

Skipping jupyterthemes as it is not installed

During the installation I got no error though.

What should I do to install the themes properly?

I'm using Ubuntu 16.04, and I installed Jupyter Notebook with pip. Jupyter works fine, it's just the themes that don't work

Body:
Simply run this. I was facing same issue, it worked
.

sudo pip install jupyterthemes


问:
How to play access and play the video programmatically?
I am developing an application. In that my requirement is access the video from iPhone and play that videos and select one from that videos. So please tell me how to access and play the videos in iPhone programmatically.</p>

答:
Apple's MoviePlayer sample shows how to do this.

And refer - https://web.archive.org/web/20110528064432/http://developer.apple.com/library/ios/codinghowtos/AudioAndVideo/_index.html


问:
how to write a javascript variable as source for img tag in html
I have a variable that alternates from referencing different images. For example sometimes I have
var imageName = "A.png". I want to set the innerHTML of a div tag to "src=" + imageName + ">" but it doesn't work. When I used alert to get what the innerHTML actually was, I got this . Why is this happening?

As per request here is my HTML code pertaining to this problem. It's part of a larger body of code which receives an xml file from a servlet. I find it weird that the for loop at the bottom works fine but the img src bit doesn't.

EDIT: I managed to get the innerHTML into the form  by changing what the servlet wrote (I added the absolute path just to be sure that the file could be found.) However the picture still isn't loading. Odd

```<code>function displayResult(req)
{
    var doc = req.responseText;
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(doc,"text/xml");

    var imageName = xmlDoc.getElementsByTagName('ImageName').item(0).textContent + ".png";

    var comments = xmlDoc.getElementsByTagName('Comment');

    var imgDisplay = document.getElementById('ImageDisplay');

    var str = "<img src=" + imageName + ">";
    alert(str);
    imgDisplay.innerHTML = str;
    alert(imgDisplay.innerHTML);
    str = '';
    for (var j = 0; j < comments.length; j++)
    {
        str = str + "<p>"+ comments.item(j).textContent + "</p>";
        }

    var commentDisplay = document.getElementById('CommentDisplay');
    commentDisplay.innerHTML = str;

}
</code>```

答:
Another solution could be to use template literals:</p>

```<code>var str = `<img src="${imageName}">`;
</code>```

Body:
I have a variable that alternates from referencing different images. For example sometimes I have
var imageName = "A.png". I want to set the innerHTML of a div tag to "src=" + imageName + ">" but it doesn't work. When I used alert to get what the innerHTML actually was, I got this . Why is this happening?

As per request here is my HTML code pertaining to this problem. It's part of a larger body of code which receives an xml file from a servlet. I find it weird that the for loop at the bottom works fine but the img src bit doesn't.

EDIT: I managed to get the innerHTML into the form  by changing what the servlet wrote (I added the absolute path just to be sure that the file could be found.) However the picture still isn't loading. Odd

function displayResult(req)
{
    var doc = req.responseText;
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(doc,"text/xml");

    var imageName = xmlDoc.getElementsByTagName('ImageName').item(0).textContent + ".png";

    var comments = xmlDoc.getElementsByTagName('Comment');

    var imgDisplay = document.getElementById('ImageDisplay');

    var str = "";
    alert(str);
    imgDisplay.innerHTML = str;
    alert(imgDisplay.innerHTML);
    str = '';
    for (var j = 0; j < comments.length; j++)
    {
        str = str + "
"+ comments.item(j).textContent + "
";
        }

    var commentDisplay = document.getElementById('CommentDisplay');
    commentDisplay.innerHTML = str;

}

Body:
Another solution could be to use template literals:

var str = `<img src="${imageName}">`;


问:
How to display the GIF image from my assets in SwiftUI?
I want to use the image GIF type which named 'myAssetsGifName', presenting in my project(An App).

For example, I want to reach something just like this GIF:

I did some research before I asking this question.(Link1, Link2, Link3 for Watch OS, Link4 5 years ago...)

However, I didn't find any available solution or example to successfully present the GIF in SwiftUI.

Some of these references or posts are out-of-date. I did try these references's solutions, still not working in SwiftUI. So there are less info can be referenced. I want to reach these goals:

I can use Image params to call the gif from my assets.

Image("myAssetsGifName")

I can using the url to download the gif and show it(passing that to Image).
  Just found a possible direction about second issue. Link

If I cannot use Image params to present my GIF from local assets or url downloading. Is there any possible solution could satisfy the needs? (e.g., Using UIViewRepresentable or something else?)

Does anyone know the answer. Which way should I learn from it and using it to reach my goals?

Any help or advice will be greatly appreciated. Thanks a lot!

答:
I just found a possible way to solve this problem(present GIF in my project).

First, you need to know how to use the Cocoapods.

Second, I download this git about GIFView and install its pods.
SSSwiftUIGIFView

Third, after installing pods, opening your Xcode project and import
like this:

import SSSwiftUIGIFView

Fourth, according to SSSwiftUIGIFView class you should use below
code:

SwiftUIGIFPlayerView(gifName: "Your GIF image name here")

Ok, it's done. Now you can use some GIF image in your project or App.

Let's see this finished product!


问:
App crashes with error 'Could not execute method for android:onClick' when try to validate empty field
I tried to create empty field validation that if user don't put any String/Integer and just press on the button, he will recive popup stating that field is empty.

I would appriciate any help.

See my code below:

```<code>...

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        Integer userNum = Integer.parseInt(editText.getText().toString());
        String userField = editText.getText().toString().trim();
        String message = "";

        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            mynumber.number = userNum;
            if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == false)) {

                makeToast("The number " + userNum + " is a Square number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is a Triangular number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == false)) {
                makeToast("The number " + userNum + " is a not Square or Triangular shape");
            } else if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is both Square & Triangular shapes");
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

答:
the issue is related to

```<code>Integer userNum = Integer.parseInt(editText.getText().toString());
</code>```

it may throw NumberFormatException and you won't reach till validation.

you can try like this

```<code>    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        String userField = editText.getText().toString().trim();
        String message = "";
        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            Integer userNum;
            try {
                userNum = Integer.parseInt(editText.getText().toString());
            }catch (NumberFormatException ex) {
                message = "Not an integer";
            }
            mynumber.number = userNum;
            ...
        }
    }
</code>```

Body:
I tried to create empty field validation that if user don't put any String/Integer and just press on the button, he will recive popup stating that field is empty.

I would appriciate any help.

See my code below:

...

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        Integer userNum = Integer.parseInt(editText.getText().toString());
        String userField = editText.getText().toString().trim();
        String message = "";

        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            mynumber.number = userNum;
            if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == false)) {

                makeToast("The number " + userNum + " is a Square number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is a Triangular number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == false)) {
                makeToast("The number " + userNum + " is a not Square or Triangular shape");
            } else if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is both Square & Triangular shapes");
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Body:
the issue is related to

Integer userNum = Integer.parseInt(editText.getText().toString());

it may throw NumberFormatException and you won't reach till validation.

you can try like this

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        String userField = editText.getText().toString().trim();
        String message = "";
        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            Integer userNum;
            try {
                userNum = Integer.parseInt(editText.getText().toString());
            }catch (NumberFormatException ex) {
                message = "Not an integer";
            }
            mynumber.number = userNum;
            ...
        }
    }


问:
Dremio ODBC with Python
Getting below error while running this code in Python, If anyone could advise me on this that would be appreciated. Thanks

dataframe = pandas.read_sql(sql,cnxn)

DatabaseError: Execution failed on sql 'SELECT * FROM train_data': ('HY000', "[HY000] [Dremio][Connector] (1040) Dremio failed to execute the query: SELECT * FROM train_data\n[30038]Query execution error. Details:[ \nVALIDATION ERROR: Table 'train_data' not found\n\nSQL Query SELECT * FROM train_data\nstartLine 1\nstartColumn 15\nendLine 1\nendColumn 24\n\n[Error Id: 24c7de0e-6e23-44c6-8cb6-b0a110bbd2fd on user:31010]\n\n  (org.apache.calcite.runtime.CalciteContextException) From line 1, column 15 to line 1, column 24: ...[see log] (1040) (SQLExecDirectW)")

答: this is being solved, it says that table does not exist, should give a valid table, in dremio it can be inside a specific space</p>

Title: Dremio ODBC with Python


问:
Is there a way to extract DialogFlow 'today' as the past 24 hours?
I have training phrases like:

How many customers visited my website in the past 24 hours?

How many people visited in the past 6 hours?

How many customers visited my website today?

I understand that for @sys.date-time, I am able to extract "past 6hours" and "past 24hours" as a date-time period with a startDate and endDate. However, for "today", I receive a singular date.
Is there a way to (through custom entities, etc) to parse "today" as a time-period too with startDate:  and endDate: <24hours earlier>?

Ultimately, I am trying to create a chatbot that requires passing a time period (startDate & endDate) to my external API during fulfillment, so I won't be able to work with singular dates.

答:
sys.time-period and sys.date-period entities does not accept today as a valid value.

So what you can do is create a composite custom entity, lets say with name myDateTimeRange and with value @sys.date-time:dateTime. When this entity is matched a json object will be returned and that's the trick here. Now this entity can give you result for both date-time and time-range, for example if the matched text is today then you will get the value of myDateTimeRange entity as { "dateTime": "2020-06-02T12:00:00+05:30" } and if the matched text is a range like past 6hours then the returned value will be like { "dateTime": { "endDateTime": "2020-06-02T12:12:10+05:30", "startDateTime": "2020-06-02T06:12:10+05:30" } }.

So now you can easily create some logic based on the returned value, like if you received only dateTime that means some date is entered (like today) and you can take it as both start date and end date, but if you get endDateTime and startDateTime sub properties also then you know you have received a range.

Note that you can improve your composite entity by adding more values to it like @sys.time-period:timePeriod, @sys.date-period:datePeriod, etc.


问:
Writing my first shiny app, How do I plot by selected variables, why does this script not work?
I'm trying to write my first shiny app that will give some statistical analysis between two variables and a plot that shows a relationship between them. My data will be predetermined. For the graph, I've decided to use highcharter but how do I write the code for this? The above code is my first try but I can't seem to figure out why it doesn't work. I've tried the example code for shiny from the highcharter guide too but it doesn't seem to work either.</p>

```<code>library(shiny)
library(highcharter)
library(tidyverse)

data(iris)

ui <- fluidPage(

  selectInput("First", label = "First Variable", width = "100%",
              choices = colnames(iris)),
  selectInput("Second", label = "Second", width = "100%",
              colnames(iris)),
  highchartOutput("hchartcont")

)

server = function(input, output) {

  output$hchartcont <- renderHighchart({
    hc <- highchart() %>%
      hc_chart(type="line") %>%
      hc_xAxis(input$First) %>%
      hc_yAxis_multiples(input$Second)
    hc
  }

  )

}

shinyApp(ui = ui, server = server)

</code>```

答:
Although not familiar with highcharter, your code doesn't seem to provide any data to the plot. You need to get the input data first and then draw a plot.

For example, this could work (I tried to preserve as much of your code as possible... the line plot does not make sense here, however; consider this to be only a quick working example :-)):

```<code>library(highcharter)
library(tidyverse)
library(shiny)

ui <- fluidPage(

    selectInput("First", label = "First Variable", width = "100%",
                choices = colnames(iris)),
    selectInput("Second", label = "Second", width = "100%",
                choices = colnames(iris)),
    highchartOutput("hchartcont")

)

server = function(input, output) {

    output$hchartcont <- renderHighchart({
        df <- iris %>% select(x = input$First, y = input$Second)
        hchart(df, "line", hcaes(x, y))
    })

}

shinyApp(ui = ui, server = server)
</code>```

Body:
I'm trying to write my first shiny app that will give some statistical analysis between two variables and a plot that shows a relationship between them. My data will be predetermined. For the graph, I've decided to use highcharter but how do I write the code for this? The above code is my first try but I can't seem to figure out why it doesn't work. I've tried the example code for shiny from the highcharter guide too but it doesn't seem to work either.

library(shiny)
library(highcharter)
library(tidyverse)

data(iris)

ui <- fluidPage(

  selectInput("First", label = "First Variable", width = "100%",
              choices = colnames(iris)),
  selectInput("Second", label = "Second", width = "100%",
              colnames(iris)),
  highchartOutput("hchartcont")

)

server = function(input, output) {

  output$hchartcont <- renderHighchart({
    hc <- highchart() %>%
      hc_chart(type="line") %>%
      hc_xAxis(input$First) %>%
      hc_yAxis_multiples(input$Second)
    hc
  }

  )

}

shinyApp(ui = ui, server = server)

Body:
Although not familiar with highcharter, your code doesn't seem to provide any data to the plot. You need to get the input data first and then draw a plot.

For example, this could work (I tried to preserve as much of your code as possible... the line plot does not make sense here, however; consider this to be only a quick working example :-)):

library(highcharter)
library(tidyverse)
library(shiny)

ui <- fluidPage(

    selectInput("First", label = "First Variable", width = "100%",
                choices = colnames(iris)),
    selectInput("Second", label = "Second", width = "100%",
                choices = colnames(iris)),
    highchartOutput("hchartcont")

)

server = function(input, output) {

    output$hchartcont <- renderHighchart({
        df <- iris %>% select(x = input$First, y = input$Second)
        hchart(df, "line", hcaes(x, y))
    })

}

shinyApp(ui = ui, server = server)


问:
How do I parse this json-response?
The response is structured like this, this is an extract, might be missing a curly brace:

```<code>{"2":{"date":1306411951,"price":4.8003,"low":"4.80000000","high":"4.80060000","nicedate":"15:12"},"6":{"date":1306418941,"price":4.654175,"low":"4.40000000","high":"4.80000000","nicedate":"17:02"}
</code>```

And I get cast exceptions when parsing the response string even though all the datamembers in the object are strings.

I'm using System.Runtime.Serialization.Json to deserialize the objects.

Right now I'm doing it like this:

```<code>        Currency[] MapJSONToObjects(string jsonString)
    {
        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {
            //Parse
            var ser = new DataContractJsonSerializer(typeof(Currency[]));
            Currency[] currencies = (Currency[])ser.ReadObject(ms);
            return currencies;
        }
    }
</code>```

答:
As mentioned already, you're missing a trailing } from the JSON. Assuming that what you receive is properly formatted and consistent JSON, then your Currency class should look something like this:

```<code>[DataContract]
public class Currency
{
    [DataMember(Name = "date")]
    public int Date { get; set; }
    [DataMember(Name = "price")]
    public double Price { get; set; }
    [DataMember(Name = "low")]
    public string Low { get; set; }
    [DataMember(Name = "high")]
    public string High { get; set; }
    [DataMember(Name = "nicedate")]
    public string NiceDate { get; set; }
}</code>```

Your deserialization code looks fine, though you could consider using JSON.NET if you're still having problems, as described here: Deserializing variable Type JSON array using DataContractJsonSerializer

Title: How do I parse this json-response?

Body:
The response is structured like this, this is an extract, might be missing a curly brace:

{"2":{"date":1306411951,"price":4.8003,"low":"4.80000000","high":"4.80060000","nicedate":"15:12"},"6":{"date":1306418941,"price":4.654175,"low":"4.40000000","high":"4.80000000","nicedate":"17:02"}

And I get cast exceptions when parsing the response string even though all the datamembers in the object are strings.

I'm using System.Runtime.Serialization.Json to deserialize the objects.

Right now I'm doing it like this:

        Currency[] MapJSONToObjects(string jsonString)
    {
        using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {
            //Parse
            var ser = new DataContractJsonSerializer(typeof(Currency[]));
            Currency[] currencies = (Currency[])ser.ReadObject(ms);
            return currencies;
        }
    }

Body:
As mentioned already, you're missing a trailing } from the JSON. Assuming that what you receive is properly formatted and consistent JSON, then your Currency class should look something like this:

[DataContract]
public class Currency
{
    [DataMember(Name = "date")]
    public int Date { get; set; }
    [DataMember(Name = "price")]
    public double Price { get; set; }
    [DataMember(Name = "low")]
    public string Low { get; set; }
    [DataMember(Name = "high")]
    public string High { get; set; }
    [DataMember(Name = "nicedate")]
    public string NiceDate { get; set; }
}

Your deserialization code looks fine, though you could consider using JSON.NET if you're still having problems, as described here: Deserializing variable Type JSON array using DataContractJsonSerializer


问:
In python how to update a value in CSV file which have more than 5K rows?
I'm a beginner to python, is there any way I can update the csv file while reading and writing in the same file, or is there any alternate way to do this. All the suggestions are welcomed.

NOTE: I have a CSV file with records 5k and above.

What I want to do is read the csv file line by line and if the value of msg_sent is False then update it to True

Here is the code snippet which I've tried but it is adding an new line at the end of CSV file instead of updating it,

```<code>with open('subscribers.csv', 'r+') as subscribers_csv:
reader = csv.DictReader(subscribers_csv)
writer = csv.DictWriter(subscribers_csv,
                        delimiter=",",
                        lineterminator="\n",
                        fieldnames=['user_id', 'name', 'msg_sent'])
    for subscriber in reader:
        if subscriber['msg_sent'] == 'False':
            subscriber_row = {'user_id': subscriber['user_id'],
                              'name': subscriber['name'],
                              'msg_sent': True}
            writer.writerow(subscriber_row)
</code>```

答:
any way I can update the csv file while reading and writing in the same file

CSV files are just text files, so you can use tools for text file processing. Python has fileinput module, which has fileinput.input context feauting inplace option, pymotw.com has example, how to modify the contents of a file where it is, rather than making a new file..

Body:
I'm a beginner to python, is there any way I can update the csv file while reading and writing in the same file, or is there any alternate way to do this. All the suggestions are welcomed.

NOTE: I have a CSV file with records 5k and above.

What I want to do is read the csv file line by line and if the value of msg_sent is False then update it to True

Here is the code snippet which I've tried but it is adding an new line at the end of CSV file instead of updating it,

with open('subscribers.csv', 'r+') as subscribers_csv:
reader = csv.DictReader(subscribers_csv)
writer = csv.DictWriter(subscribers_csv,
                        delimiter=",",
                        lineterminator="\n",
                        fieldnames=['user_id', 'name', 'msg_sent'])
    for subscriber in reader:
        if subscriber['msg_sent'] == 'False':
            subscriber_row = {'user_id': subscriber['user_id'],
                              'name': subscriber['name'],
                              'msg_sent': True}
            writer.writerow(subscriber_row)


答:
I also faced the same problem. I missed a step. </p>

```<code>ssh-copy-id localhost
</code>```

<p>Then you can successfully run, </p>

```<code>ansible-playbook -i hosts simple-docker-project.yml --check
</code>```

Title: ansible:Failed to connect to the host via ssh: Warning: Permanently added '10.90.0.2' (ECDSA) to the list of known hosts.\r\nPermission denied

Body:
i want to use the key login some host, but some err happened

my files is this below:

[jenkins@ci-jenkins-slave-dev test]$ ls
ansible.cfg  hosts  test.yml

my hosts file:

[jenkins@ci-jenkins-slave-dev test]$ cat hosts
[controller]
10.90.0.2 ssh_key_pass=passw0rd ansible_ssh_user=root

my playbook:

[jenkins@ci-jenkins-slave-dev test]$ cat test.yml
---

- name: test
  hosts: controller
  tasks:
    - name: add key
      authorized_key:
        user: root
        key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"

when run playbook :

[jenkins@ci-jenkins-slave-dev test]$ ansible-playbook test.yml

PLAY [test] ******************************************************************************************************************************************************************************************************************************************************************

TASK [add key] ***************************************************************************************************************************************************************************************************************************************************************
fatal: [10.90.0.2]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.90.0.2' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,password).\r\n", "unreachable": true}
    to retry, use: --limit @/home/jenkins/ansible-test/test/test.retry

PLAY RECAP *******************************************************************************************************************************************************************************************************************************************************************
10.90.0.2                  : ok=0    changed=0    unreachable=1    failed=0

I can use "ssh root@10.90.0.2 "and input "passw0rd" to login but ansible can't ,i want to know what's wrong ？

my ansible.cfg :

[jenkins@ci-jenkins-slave-dev test]$ cat ansible.cfg
# config file for ansible -- http://ansible.com/
# ==============================================

# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first

[defaults]

# some basic default values...

hostfile       = ./hosts
library        = /usr/share/ansible
remote_tmp     = $HOME/.ansible/tmp
pattern        = *
forks          = 5
poll_interval  = 15
sudo_user      = root
#ask_sudo_pass = True
#ask_pass      = True
transport      = smart
remote_port    = 22
module_lang    = C

# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
gathering = explicit

# additional paths to search for roles in, colon separated
#roles_path    = /etc/ansible/roles

# uncomment this to disable SSH key host checking
host_key_checking = False

# change this for alternative sudo implementations
sudo_exe = sudo

# what flags to pass to sudo
#sudo_flags = -H

# SSH timeout
timeout = 10

# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
remote_user = root

# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log

# default module name for /usr/bin/ansible
#module_name = command

# use this shell for commands executed under sudo
# you may need to change this to bin/bash in rare instances
# if sudo is constrained
#executable = /bin/sh

# if inventory variables overlap, does the higher precedence one win
# or are hash values merged together?  The default is 'replace' but
# this can also be set to 'merge'.
#hash_behaviour = replace

# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n

# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
private_key_file = ~/.ssh/id_rsa

# format of string {{ ansible_managed }} available within Jinja2
# templates indicates to users editing templates files will be replaced.
# replacing {file}, {host} and {uid} and strftime codes with proper values.
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}

# by default, ansible-playbook will display "Skipping [host]" if it determines a task
# should not be run on a host.  Set this to "False" if you don't want to see these "Skipping"
# messages. NOTE: the task header will still be shown regardless of whether or not the
# task is skipped.
#display_skipped_hosts = True

# by default (as of 1.3), Ansible will raise errors when attempting to dereference
# Jinja2 variables that are not set in templates or action lines. Uncomment this line
# to revert the behavior to pre-1.3.
#error_on_undefined_vars = False

# by default (as of 1.6), Ansible may display warnings based on the configuration of the
# system running ansible itself. This may include warnings about 3rd party packages or
# other conditions that should be resolved if possible.
# to disable these warnings, set the following value to False:
#system_warnings = True

# by default (as of 1.4), Ansible may display deprecation warnings for language
# features that should no longer be used and will be removed in future versions.
# to disable these warnings, set the following value to False:
#deprecation_warnings = True

# set plugin path directories here, separate with colons
action_plugins     = /usr/share/ansible_plugins/action_plugins
callback_plugins   = /usr/share/ansible_plugins/callback_plugins
connection_plugins = /usr/share/ansible_plugins/connection_plugins
lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
vars_plugins       = /usr/share/ansible_plugins/vars_plugins
filter_plugins     = /usr/share/ansible_plugins/filter_plugins

# don't like cows?  that's unfortunate.
# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
#nocows = 1

# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1

# the CA certificate path used for validating SSL certs. This path
# should exist on the controlling node, not the target nodes
# common locations:
# RHEL/CentOS: /etc/pki/tls/certs/ca-bundle.crt
# Fedora     : /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
# Ubuntu     : /usr/share/ca-certificates/cacert.org/cacert.org.crt
#ca_file_path =

# the http user-agent string to use when fetching urls. Some web server
# operators block the default urllib user agent as it is frequently used
# by malicious attacks/scripts, so we set it to something unique to
# avoid issues.
#http_user_agent = ansible-agent

[paramiko_connection]

# uncomment this line to cause the paramiko connection plugin to not record new host
# keys encountered.  Increases performance on new host additions.  Setting works independently of the
# host key checking setting above.
record_host_keys=False

# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty=False

[ssh_connection]

# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use
# paramiko on older platforms rather than removing it
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o UserKnownHostsFile=/dev/null

# The path to use for the ControlPath sockets. This defaults to
# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
# very long hostnames or very long path names (caused by long user names or
# deeply nested home directories) this can exceed the character limit on
# file socket names (108 characters for most platforms). In that case, you
# may wish to shorten the string below.
#
# Example:
# control_path = %(directory)s/%%h-%%r
#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r

# Enabling pipelining reduces the number of SSH operations required to
# execute a module on the remote server. This can result in a significant
# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
#
#pipelining = False

# if True, make ansible use scp if the connection type is ssh
# (default is sftp)
#scp_if_ssh = True

[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0

# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
accelerate_daemon_timeout = 30

# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
#accelerate_multi_key = yes

If you need any additional information, please let me know, and I will add

Body:
I also faced the same problem. I missed a step.

ssh-copy-id localhost

Then you can successfully run,

ansible-playbook -i hosts simple-docker-project.yml --check


问:
making columns inside a main column with flexbox
I have made the below image in Bootstrap 3. I am programming for a site there is using BS3. There is no possibility to use BS4.

I am having so many problems with the column height with BS3, so I am giving up now. I started working with flexboxes last week, because it seems so much easier to work with.

Is it possible to make the design lige on the image with flexboxes? I have made the 2 main columns with flexboxes, but I am not quite sure how to make the 2 columns inside the right main column. I tried to fit some bootstrap in it, but that went totally wrong.

.call-out-container {
        max-width: 1200px;
        margin: 40px auto 0 auto;
    }
    .call-out {
        padding: 20px;
        box-sizing: border-box;
        margin-bottom: 20px;
        flex-basis: 48%;
    }
    .call-out:nth-child(1) {background-color: pink}
    .call-out:nth-child(2) {background-color:rgb(41, 255, 201)}

    @media (min-width: 768px) {
        .call-out-container {
            display:flex;
            justify-content: space-between;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="call-out-container">
    <div class="call-out">
        <h4>Headline 1</h4>
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa</p>
    </div>
    <div class="call-out">
        <h4>Headline 2</h4><hr/>

        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
    </div>
</div></code>```

答:
In order to create the design on the right using flexbox, you need to:

1. Take your two columns and wrap them into a separate div.

```<code>   <div class="call-out">
            <h4>Headline 2</h4><hr/>
            <div class="two-column">
                <div class="column">
                    <img src="https://via.placeholder.com/250x150.png">
                    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
                </div>
                <div class="column">
                    <img src="https://via.placeholder.com/250x150.png">
                    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
                </div>

            </div>
        </div>
</code>```

In this example I wraped the two columns into a div called two column

2. Display Flex the newly created div

```<code>.two-column{
    display: flex;
    flex-direction: row;
}
</code>```

You can see the result here:

Please Note: You will have to add some adjustments/media-queries to give your desired responsive behavior, however this approach should easily allow you to create your nested-column layout.

Helpful Note: Remember you can always display: flex elements that are children on elements that are already using display: flex

Hope it helps.

Body:
I have made the below image in Bootstrap 3. I am programming for a site there is using BS3. There is no possibility to use BS4.

I am having so many problems with the column height with BS3, so I am giving up now. I started working with flexboxes last week, because it seems so much easier to work with.

Is it possible to make the design lige on the image with flexboxes? I have made the 2 main columns with flexboxes, but I am not quite sure how to make the 2 columns inside the right main column. I tried to fit some bootstrap in it, but that went totally wrong.

.call-out-container {
        max-width: 1200px;
        margin: 40px auto 0 auto;
    }
    .call-out {
        padding: 20px;
        box-sizing: border-box;
        margin-bottom: 20px;
        flex-basis: 48%;
    }
    .call-out:nth-child(1) {background-color: pink}
    .call-out:nth-child(2) {background-color:rgb(41, 255, 201)}

    @media (min-width: 768px) {
        .call-out-container {
            display:flex;
            justify-content: space-between;
        }
    }

Headline 1

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa

Headline 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium

Body:
In order to create the design on the right using flexbox, you need to:

1. Take your two columns and wrap them into a separate div.

   <div class="call-out">
            <h4>Headline 2</h4><hr/>
            <div class="two-column">
                <div class="column">
                    <img src="https://via.placeholder.com/250x150.png">
                    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
                </div>
                <div class="column">
                    <img src="https://via.placeholder.com/250x150.png">
                    <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium</p>
                </div>

            </div>
        </div>

In this example I wraped the two columns into a div called two column

2. Display Flex the newly created div

.two-column{
    display: flex;
    flex-direction: row;
}

You can see the result here:

Please Note: You will have to add some adjustments/media-queries to give your desired responsive behavior, however this approach should easily allow you to create your nested-column layout.

Helpful Note: Remember you can always display: flex elements that are children on elements that are already using display: flex

Hope it helps.


问:
hibernate search configuration
Im using hibernate search and elastic search as backend . When i config hibernate and hibernatesearch in xml file  everything is ok but whene i config it in java class this warning occur and nothing found in my search .
xml config is:

```<code><properties>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3399/elastic" />
        <property name="hibernate.connection.username" value="admin" />
        <property name="hibernate.connection.password" value="admin" />

        <property name="hibernate.show_sql" value="true" />

        <property name="hibernate.search.default.indexmanager" value="elasticsearch"/>
        <property name="hibernate.search.default.elasticsearch.host" value="http://127.0.0.1:9400"/>
        <property name="hibernate.search.default.elasticsearch.index_schema_management_strategy" value="CREATE"/>
        <property name="hibernate.search.default.elasticsearch.required_index_status" value="YELLOW"/>

    </properties>
</code>```

java class config is :

```<code>java.util.Properties settings = new java.util.Properties();
            settings.put(org.hibernate.cfg.Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
            settings.put(org.hibernate.cfg.Environment.URL, "jdbc:mysql://127.0.0.1:3399/elastic");
            settings.put(org.hibernate.cfg.Environment.USER, "admin");
            settings.put(org.hibernate.cfg.Environment.PASS, "admin");
           settings.put(org.hibernate.cfg.Environment.DIALECT,"org.hibernate.dialect.MySQL8Dialect");
            settings.put(org.hibernate.cfg.Environment.SHOW_SQL, "true");
            settings.put(org.hibernate.cfg.Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
            settings.put(org.hibernate.cfg.Environment.POOL_SIZE, "5");
settings.put("hibernate.search.default.indexmanager", "elasticsearch");
            settings.put("hibernate.search.default.elasticsearch.host", "http://127.0.0.1:9400");
            settings.put("hibernate.search.default.elasticsearch.index_schema_management_strategy", "CREATE");
            settings.put("hibernate.search.default.elasticsearch.required_index_status", "YELLOW");
</code>```

Warning is :

WARNING: request [HEAD http://127.0.0.1:9400/com.radar.elasticsearch.videogame] returned 1 warnings: [299 Elasticsearch-6.8.0-65b6179 "[types removal] The parameter include_type_name should be explicitly specified in get indices requests to prepare for 7.0. In 7.0 include_type_name will default to 'false', which means responses will omit the type name in mapping definitions."]

答:
Elasticsearch support in Hibernate Search 5 is experimental and was only tested with Elasticsearch up to version 5.6.

If you need to upgrade to Elasticsearch 7, upgrade to Hibernate Search 6.
Hibernate Search 6 is currently in Beta but offers revamped APIs that will be a much better fit for Elasticsearch.

It also offers new features not found in Hibernate Search 5, such as support for nested documents or the ability to inject JSON directly into your query (to take advantage of more exotic predicates/sorts/etc. not yet supported by the Hibernate Search DSL).

EDIT: Also, you can find information about the compatibility of Hibernate Search with various other components on this page of the official website.

Title: hibernate search configuration

Body:
Im using hibernate search and elastic search as backend . When i config hibernate and hibernatesearch in xml file  everything is ok but whene i config it in java class this warning occur and nothing found in my search .
xml config is:

<properties>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3399/elastic" />
        <property name="hibernate.connection.username" value="admin" />
        <property name="hibernate.connection.password" value="admin" />

        <property name="hibernate.show_sql" value="true" />

        <property name="hibernate.search.default.indexmanager" value="elasticsearch"/>
        <property name="hibernate.search.default.elasticsearch.host" value="http://127.0.0.1:9400"/>
        <property name="hibernate.search.default.elasticsearch.index_schema_management_strategy" value="CREATE"/>
        <property name="hibernate.search.default.elasticsearch.required_index_status" value="YELLOW"/>

    </properties>

java class config is :

java.util.Properties settings = new java.util.Properties();
            settings.put(org.hibernate.cfg.Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
            settings.put(org.hibernate.cfg.Environment.URL, "jdbc:mysql://127.0.0.1:3399/elastic");
            settings.put(org.hibernate.cfg.Environment.USER, "admin");
            settings.put(org.hibernate.cfg.Environment.PASS, "admin");
           settings.put(org.hibernate.cfg.Environment.DIALECT,"org.hibernate.dialect.MySQL8Dialect");
            settings.put(org.hibernate.cfg.Environment.SHOW_SQL, "true");
            settings.put(org.hibernate.cfg.Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
            settings.put(org.hibernate.cfg.Environment.POOL_SIZE, "5");
settings.put("hibernate.search.default.indexmanager", "elasticsearch");
            settings.put("hibernate.search.default.elasticsearch.host", "http://127.0.0.1:9400");
            settings.put("hibernate.search.default.elasticsearch.index_schema_management_strategy", "CREATE");
            settings.put("hibernate.search.default.elasticsearch.required_index_status", "YELLOW");

Warning is :

WARNING: request [HEAD http://127.0.0.1:9400/com.radar.elasticsearch.videogame] returned 1 warnings: [299 Elasticsearch-6.8.0-65b6179 "[types removal] The parameter include_type_name should be explicitly specified in get indices requests to prepare for 7.0. In 7.0 include_type_name will default to 'false', which means responses will omit the type name in mapping definitions."]


问:
How can I keep number and increment in child component with Vue JS?
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

```<code>  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },
</code>```

Do you know how?

答:
You can avoid modify props directly using .sync modifier:

App.vue:

<Child2 :todos.sync="todos" :keyName="keyName"/>
```
<p>Child2.vue:</p>
<pre class="lang-js prettyprint-override"><code>if (keyObject) {
     this.$emit('update:todos', keyObject);
}
</code>```

For get the next id, you can emit this value when you get the array from local storage:

App.vue:

<Child2 :todos.sync="todos" @setTargetId="setTargetId" :keyName="keyName"/>
```
<pre class="lang-js prettyprint-override"><code>methods: {
    // ...
    setTargetId(newTargetId){
        this.$set(this.target, 'id', newTargetId );
    }
}

</code>```

Child2.vue:

// ...
created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    // Check keyObject
    if (keyObject) {
        // update todo on App.vue
        this.$emit("update:todos", keyObject);

        // set target.id
        const setId = keyObject.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
        this.$emit('setTargetId', setId + 1)
    }
},
```

See here: https://codesandbox.io/s/keen-gates-q7efo

Body:
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },

Do you know how?

Body:
You can avoid modify props directly using .sync modifier:

App.vue:

<Child2 :todos.sync="todos" :keyName="keyName"/>

Child2.vue:

if (keyObject) {
     this.$emit('update:todos', keyObject);
}

For get the next id, you can emit this value when you get the array from local storage:

App.vue:

<Child2 :todos.sync="todos" @setTargetId="setTargetId" :keyName="keyName"/>

methods: {
    // ...
    setTargetId(newTargetId){
        this.$set(this.target, 'id', newTargetId );
    }
}

Child2.vue:

// ...
created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    // Check keyObject
    if (keyObject) {
        // update todo on App.vue
        this.$emit("update:todos", keyObject);

        // set target.id
        const setId = keyObject.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
        this.$emit('setTargetId', setId + 1)
    }
},

See here: https://codesandbox.io/s/keen-gates-q7efo


问:
Is there a Way to use Linq to Oracle
I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database.  I looked at the SQL generated and it is for MSSQL and not Oracle PSQL.

Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database?

答:
Look in codeplex:
Linq To Oracle project</p>

ContentLicense: CC BY-SA 2.5

Title: Is there a Way to use Linq to Oracle

LastEditorDisplayName: Keith


问:
What is the most efficient way to push and pop a list in Python?
In Python how do I write code which shifts off the last element of a list and adds a new one to the beginning - to run as fast as possible at execution?

There are good solutions involving the use of append, rotate etc but not all may translate to fast execution.

答:
You can use insert method of python list object.  </p>

```<code>l = [1, 2, 3]
#lets insert 10 at biggining, which means at index 0
l.insert(0, 10)
print(l) # this will print [10, 1, 2, 3]
</code>```

Body:
You can use insert method of python list object.

l = [1, 2, 3]
#lets insert 10 at biggining, which means at index 0
l.insert(0, 10)
print(l) # this will print [10, 1, 2, 3]


答:
Don't use a list.

A list can do fast inserts and removals of items only at its end. You'd use pop(-1) and append, and you'd end up with a stack.

Instead, use collections.deque, which is designed for efficient addition and removal at both ends. Working on the "front" of a deque uses the popleft and appendleft methods. Note, "deque" means "double ended queue", and is pronounced "deck".

Title: What is the most efficient way to push and pop a list in Python?

Body:
In Python how do I write code which shifts off the last element of a list and adds a new one to the beginning - to run as fast as possible at execution?

There are good solutions involving the use of append, rotate etc but not all may translate to fast execution.


问:
How to set run as Administrator for Csharp Windows Form exe

Possible Duplicate:

  How to force C# App to run as administrator on Windows 7

I had already done my codes and it's ready to Decode, however, i needed the pogramme to run as administrator. The question is how to make the program to enable RUN AS ADMINISTRATOR?

答: Add a manifest file to project with these contents</p>


问:
Please use override option or check for definition, koin android?
I am implementing Koin DI in my android application. I was successfully able to create some of the modules. However I got an exception where I tried to get object from another in module.

These are my modules

```<code>val networkModule = module {
factory { provideRetrofit() }

single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(
        GsonConverterFactory.create(
            GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create()
        )
    )
    .client(OkHttpClient.Builder().build())
    .build()

 }

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)
</code>```

view model module - i want to pass the network call object here

```<code>val viewModelModule = module {
single { provideNetworkApi(get ()) }
}
</code>```

This is my code in application class

```<code>startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(networkModule,viewModelModule))
    }
</code>```

This is the exception I get

```<code>java.lang.RuntimeException: Unable to create application com.mountmeru.BaseApp: org.koin.core.error.DefinitionOverrideException: Definition '[Factory:'com.mountmeru.network.NetworkCall']' try to override existing definition. Please use override option or check for definition '[Factory:'com.mountmeru.network.NetworkCall']'
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6465)
    at android.app.ActivityThread.access$1300(ActivityThread.java:219)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 Caused by: org.koin.core.error.DefinitionOverrideException: Definition '[Factory:'com.mountmeru.network.NetworkCall']' try to override existing definition. Please use override option or check for definition '[Factory:'com.mountmeru.network.NetworkCall']'
    at org.koin.core.scope.ScopeDefinition.save(ScopeDefinition.kt:25)
</code>```

Any clue whats wrong here?

答:
I was doing it all wrong. The correct implementation is

I wanted the NetworkCall object in my LoginViewModel

```<code>val viewModelModule = module {
single { LoginViewModel(get()) }
}
</code>```

And the viewmodel class is follows

```<code>class LoginViewModel(networkCall: NetworkCall) : ViewModel(){
 var networkCall: NetworkCall;
init {
    this.networkCall = networkCall
}
}
</code>```

So far I feel koin is quite good

Body:
I am implementing Koin DI in my android application. I was successfully able to create some of the modules. However I got an exception where I tried to get object from another in module.

These are my modules

val networkModule = module {
factory { provideRetrofit() }

single { provideNetworkApi(get()) }
}

fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
    .baseUrl(NetworkConstant.BASE_URL)
    .addConverterFactory(
        GsonConverterFactory.create(
            GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create()
        )
    )
    .client(OkHttpClient.Builder().build())
    .build()

 }

fun provideNetworkApi(retrofit: Retrofit): NetworkCall =
retrofit.create(NetworkCall::class.java)

view model module - i want to pass the network call object here

val viewModelModule = module {
single { provideNetworkApi(get ()) }
}

This is my code in application class

startKoin {
        androidLogger()
        androidContext(this@BaseApp)
        modules(listOf(networkModule,viewModelModule))
    }

This is the exception I get

java.lang.RuntimeException: Unable to create application com.mountmeru.BaseApp: org.koin.core.error.DefinitionOverrideException: Definition '[Factory:'com.mountmeru.network.NetworkCall']' try to override existing definition. Please use override option or check for definition '[Factory:'com.mountmeru.network.NetworkCall']'
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6465)
    at android.app.ActivityThread.access$1300(ActivityThread.java:219)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
 Caused by: org.koin.core.error.DefinitionOverrideException: Definition '[Factory:'com.mountmeru.network.NetworkCall']' try to override existing definition. Please use override option or check for definition '[Factory:'com.mountmeru.network.NetworkCall']'
    at org.koin.core.scope.ScopeDefinition.save(ScopeDefinition.kt:25)

Any clue whats wrong here?

Body:
I was doing it all wrong. The correct implementation is

I wanted the NetworkCall object in my LoginViewModel

val viewModelModule = module {
single { LoginViewModel(get()) }
}

And the viewmodel class is follows

class LoginViewModel(networkCall: NetworkCall) : ViewModel(){
 var networkCall: NetworkCall;
init {
    this.networkCall = networkCall
}
}

So far I feel koin is quite good


问:
render JSON tree object in html table
I have an problem in rendering a tree structure json in to the html so that i can have a view like in the image attached.

list for repeat in the table

   list = [
  {
    "level": "1",
    "leafFlag": "1",
    "path": "r125",
    "name": "car",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "r125/yhes",
        "name": "tata"
      }
    ]
  },
  {
    "level": "1",
    "leafFlag": "1",
    "path": "p123",
    "name": "food",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "p123/p095",
        "name": "banana",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "p123/p095/p546",
            "name": "grapes"
          }
        ]
      },
      {
        "level": "2",
        "leafFlag": "0",
        "path": "p123/p345",
        "name": "apple"
      }
    ]
  }
]```
<pre class="snippet-code-html lang-html prettyprint-override"><code>I tried something like this but didnt work

<tbody *ngFor="let element of list">
                    <tr *ngIf="element && (!element.children || element.children.length === 0); else loggedOut">
                        <td>
                            {{element.level}}
                        </td>
                        <td>
                            {{ element.path }}
                        </td>
                    </tr>
                    <ng-template #loggedOut>
                        <tr *ngFor="let child of element.children">
                            <td>
                                {{child.level}}
                            </td>
                            <td>{{ child.path }}</td>
                        </tr>
                    </ng-template>
                </tbody></code>```

I tried with below syntax but am not able to do that

but its not printing correctly

答:
Can you try this

I changed your logout tbody to

```<code><tbody *ngFor="let element of newarr">
<tr *ngIf="element && (!element.children || element.children.length === 0); else loggedOut">
    <td  [style.paddingLeft]="element.level*10+'px'">{{element.level}}</td>
    <td>{{ element.path }} </td>
</tr>
</code>```

in component convert from your nested object array to single object array

```<code>  newarr=[];
  ngOnInit(){
    this.arr.forEach(element=>{
      this.newarr.push({level:element.level,path:element.path})
      if(element.children&&element.children.length>0){
          this.callback(element.children);
      }
    })
  }
  callback(element){
    element.forEach(x=>{
      this.newarr.push({level:x.level,path:x.path})
       if(x.children&&x.children.length>0){ this.callback(x.children);  }
    })
  }
</code>```

Title: render JSON tree object in html table

Body:
I have an problem in rendering a tree structure json in to the html so that i can have a view like in the image attached.

list for repeat in the table

   list = [
  {
    "level": "1",
    "leafFlag": "1",
    "path": "r125",
    "name": "car",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "r125/yhes",
        "name": "tata"
      }
    ]
  },
  {
    "level": "1",
    "leafFlag": "1",
    "path": "p123",
    "name": "food",
    "children": [
      {
        "level": "2",
        "leafFlag": "1",
        "path": "p123/p095",
        "name": "banana",
        "children": [
          {
            "level": "3",
            "leafFlag": "0",
            "path": "p123/p095/p546",
            "name": "grapes"
          }
        ]
      },
      {
        "level": "2",
        "leafFlag": "0",
        "path": "p123/p345",
        "name": "apple"
      }
    ]
  }
]

I tried something like this but didnt work

                            {{element.level}}

                            {{ element.path }}

                    <ng-template #loggedOut>

                                {{child.level}}

                            {{ child.path }}

                    </ng-template>

I tried with below syntax but am not able to do that

but its not printing correctly

Body:
Can you try this

I changed your logout tbody to

<tbody *ngFor="let element of newarr">
<tr *ngIf="element && (!element.children || element.children.length === 0); else loggedOut">
    <td  [style.paddingLeft]="element.level*10+'px'">{{element.level}}</td>
    <td>{{ element.path }} </td>
</tr>

in component convert from your nested object array to single object array

  newarr=[];
  ngOnInit(){
    this.arr.forEach(element=>{
      this.newarr.push({level:element.level,path:element.path})
      if(element.children&&element.children.length>0){
          this.callback(element.children);
      }
    })
  }
  callback(element){
    element.forEach(x=>{
      this.newarr.push({level:x.level,path:x.path})
       if(x.children&&x.children.length>0){ this.callback(x.children);  }
    })
  }


问:
Gradle sync failed on android studio 4.0
After upgrading my android project to classpath 'com.android.tools.build:gradle:4.0.0'
and distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

I found this error

Gradle sync failed: Cause: org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

my project details is:

compileSdkVersion 29

ndkVersion "21.1.6352462"

minSdkVersion 21

targetSdkVersion 29

How I can solve this problem, on android studio 4.0?

答: Switch to gradle version 5.6.4. LazyConfigurationUsageContext doesn't have support in gradle versions 6.0+.</p>


问:
Jump to sequential tags by one button
I have the following source code(React.js, React-scroll, React-bootstrap).
Click the div, Jump to specific image tag.(In this example, jump to first image.)

```<code>render(){
  return(
    <React.Fragment>
      <Modal>
        <Modal.Header>
          <div className="jump-to-image">
            <Link to="page-image-1" containerId="containerElement"></Link>
          </div>
        </Modal.Header>
        <Modal.Body>
          <Element name="scroll-area" className="document-content-page-images" id="containerElement">
            {this.renderPageImages()}
          </Element>
        <Modal.Body>
        ...
  )
}
renderPageImages(){
  return _.map(page_images, (page_image, i) => (
    <Element key={i} name={"page-image-" + (i + 1)}>
      <img className="document-content-page-image" src={`/thumbnail?path=...}`}/>
    </Element>
  ))
}
</code>```

But I want (single) button jumping to image tags sequentially.

1st click: Jumping to first image tag(page-image-1)

2nd click: Jumping to next image tag(page-image-2)

3rd click: Jumping to next image tag(page-image-3)

...

Image that what I want.

Please tell me how to realize.

答:
Here you go

There is no need of <Link> you can use simple button an on that click increment the count right after scroll, so on next click you can scroll to next element

scroller.scrollTo("page-image-" + scrollTo, {

WORKING DEMO

Code:

```<code>import React, { useState } from "react";
import "./styles.css";
import { Element, scroller } from 'react-scroll'

// fake data to loop through
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

export default function App() {
  // use state to maintain the last/next to scroll index
  const [scrollTo, setScrollTo] = useState(1);

  const scrollToElement = () => {

    // You can scroll to element by it's name
    scroller.scrollTo("page-image-" + scrollTo, {
      duration: 1500,
      delay: 100,
      smooth: true,
      offset: 0 // Scrolls to element + 50 pixels down the page
    });

    // increment the state, so on next click you can scroll to next element
    setScrollTo(scrollTo => scrollTo + 1);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={scrollToElement}>Scroll to {scrollTo}</button>
      {data.map(d => (
        <Element name={`page-image-${d}`} className="block"> // <--- Element
          Scroll to : {d}
        </Element>
      ))}
    </div>
  );
}

</code>```

Title: Jump to sequential tags by one button

Body:
I have the following source code(React.js, React-scroll, React-bootstrap).
Click the div, Jump to specific image tag.(In this example, jump to first image.)

render(){
  return(
    <React.Fragment>
      <Modal>
        <Modal.Header>

            <Link to="page-image-1" containerId="containerElement"></Link>

        </Modal.Header>
        <Modal.Body>
          <Element name="scroll-area" className="document-content-page-images" id="containerElement">
            {this.renderPageImages()}
          </Element>
        <Modal.Body>
        ...
  )
}
renderPageImages(){
  return _.map(page_images, (page_image, i) => (
    <Element key={i} name={"page-image-" + (i + 1)}>
      <img className="document-content-page-image" src={`/thumbnail?path=...}`}/>
    </Element>
  ))
}

But I want (single) button jumping to image tags sequentially.

1st click: Jumping to first image tag(page-image-1)

2nd click: Jumping to next image tag(page-image-2)

3rd click: Jumping to next image tag(page-image-3)

...

Image that what I want.

Please tell me how to realize.

Body:
Here you go

There is no need of <Link> you can use simple button an on that click increment the count right after scroll, so on next click you can scroll to next element

scroller.scrollTo("page-image-" + scrollTo, {

WORKING DEMO

Code:

import React, { useState } from "react";
import "./styles.css";
import { Element, scroller } from 'react-scroll'

// fake data to loop through
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

export default function App() {
  // use state to maintain the last/next to scroll index
  const [scrollTo, setScrollTo] = useState(1);

  const scrollToElement = () => {

    // You can scroll to element by it's name
    scroller.scrollTo("page-image-" + scrollTo, {
      duration: 1500,
      delay: 100,
      smooth: true,
      offset: 0 // Scrolls to element + 50 pixels down the page
    });

    // increment the state, so on next click you can scroll to next element
    setScrollTo(scrollTo => scrollTo + 1);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={scrollToElement}>Scroll to {scrollTo}</button>
      {data.map(d => (
        <Element name={`page-image-${d}`} className="block"> // <--- Element
          Scroll to : {d}
        </Element>
      ))}
    </div>
  );
}


问:
How to get matched array object based on their values in javascript
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

```<code>var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

</code>```

Expected Output:

```<code>[
 {name: "country", value: "countries"}
]
</code>```

答:
If I understood you correctly, this should work:

```<code>var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]

function getMatchedObj(obj1, obj2){
    const values = obj2.reduce((acc, cur) => acc.concat(Object.values(cur)),[]);
    const newlist = obj1.filter(({value}) => values.includes(value));
    return newlist;
}
const result = getMatchedObj(obj1, obj2);
console.log(result);
</code>```

Here's a playground:

https://stackblitz.com/edit/js-6tmjcc

Body:
I would like to know how to get the array object based on values in javascript.
I have array object obj1, obj2 , how to get the object if name of obj1 matches with obj2 values in javascript

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]
var result = this.getMatchedObj(obj1, obj2);

function getMatchedObj(obj){
    const newlist = obj1.map((elem) => obj2.find(e=>Object.values(e)===elem.value));
    return newlist;
}

Expected Output:

[
 {name: "country", value: "countries"}
]

Body:
If I understood you correctly, this should work:

var obj1=[
  {name: "country", value: "countries"},
  {name: "city", value: "cities"}
]
var obj2=[
  {countries:"countries"},
  {sample: "sample"}
]

function getMatchedObj(obj1, obj2){
    const values = obj2.reduce((acc, cur) => acc.concat(Object.values(cur)),[]);
    const newlist = obj1.filter(({value}) => values.includes(value));
    return newlist;
}
const result = getMatchedObj(obj1, obj2);
console.log(result);

Here's a playground:

https://stackblitz.com/edit/js-6tmjcc


问:
Amazon Connect with Lex contact flow timeout
I have a contact flow that is using a pre-recorded voice prompt with a lex bot for voice rec. This is the main menu verbiage:

“Thank you for calling. If you would like to use your keypad to select the menu options, say “keypad”, otherwise please listen to the following menu options. For billing questions, say “billing”. To report a missed pickup, say “missed pickup”. If you are a current customer with recycling or other account questions, say “other”. If you are not a current customer, and have questions, say “sales”.  To hear the menu again, say “repeat menu”. For all other questions, please remain on the line.”

I have set the error handling in the Lex bot to speak "Sorry, I'm having a hard time understanding you. Let's try using the keypad instead to make sure we route your call properly."

This is working when an utterance is not matched or an invalid option is spoken or pressed. However, I cannot figure out if it's possible to allow the lex bot to timeout like in a normal DTMF contact flow and send the caller to the next step in the menu without playing the error handling in from the Lex bot.

Is this possible?

答:
That's the thing, Lex is not meant to be used this way. It MUST have an input to process, and if it reaches Lex's timeout, then it will always return an error and deliver the error handling response.

So you will have to get fancy in the Connect Flow to catch the Lex error message, and turn it into your own handling of it. But it will be hard to know whether Lex is erroring because it didn't understand, or because the user chose not to respond.

Therefore, I would personally avoid building the bot in a way that allows the user to remain silent. The user must direct Lex every step of the way and have easy ways of backing out of an unwanted action.

Remember that Lex is much more powerful than the old automatic call systems, so trying to force Lex into that old system won't work well. Depending on how you design your bot, you can make the conversation much much more natural, accepting a very wide range of responses and directing those into proper actions.

Tips:

Things may have changed more recently, but when I was building Lex/Connect, it was not possible for the user to interrupt a playback message. So I had to also avoid what you are trying to do in the welcome message:

If you would like to use your keypad to select the menu options, say “keypad”, otherwise please listen...

Naturally, a user who does want to use the keypad will try to immediately say "keypad" and probably get frustrated by having to listen to the rest of the playback message. So I design every playback message to be short, deliver information first, and always end on the question. Often breaking the conversation up into more branching points to make the questions as specific as possible.

Don't worry about going back and forth with the user too many times. It gives the user comfort knowing they are on the right path to what they want and are able to control the conversation in smaller steps. They will get stressed, having to listen to long list of options and remembering what they are while figuring out which one best applies to them.

So make each question as clear as possible and avoid spoonfeeding options. It feels less natural to explicitly state to the user what they should say:

To report a missed pickup, say “missed pickup”.

That is unnatural.

A good middle ground would be asking one question with a list of options and pausing between each option. The user will understand that these are responses they should make, but won't feel unnaturally pressured into exact phrases. For example:

Would you like to, check your billing, report a missed pickup, ask about sales, or something else?

That is natural.

We are comfortable handling those types of questions because we often do that when speaking with humans. You may even want to use a question mark instead of commas so that the playback voice uses a questioning intonation with each option. It looks less natural in written form, but would probably sound more natural.

Last tip: Don't design your bot based on your experience talking with bots. Design your bot based on your experience talking with humans.


答:
```<code>L = [1, 2, 3]
L.pop() # returns 3, L is now [1, 2]
L.append(4) # returns None, L is now [1, 2, 4]
L.insert(0, 5) # returns None, L is now [5, 1, 2, 4]
L.remove(2) # return None, L is now [5, 1, 4]
del(L[0]) # return None, L is now [1, 4]
L.pop(0) # return 1, L is now [4]
</code>```


问:
What is the best way to create page in Drupal 8 so that I can then add these posts with images?
I have a Home page on the Drupal website (such as is created after installation), but I still need to create this page:

What is the best way to create a page so that I can then add these posts with images?

I am just starting to learn Drupal and have heard so far about such ways of creating pages:

1) in admin toolbar: Content / Add Content / Article

2) in admin toolbar: Content / Add Content / Basic page

3) in admin toolbar: Structure / Views / Add Views

Which one should I use? Or maybe there is some other option that I don’t know about?

P.S. At the moment I am more interested how to create empty page on which I can then add posts later, and adding posts it is another question.

答:
Previous answers have given the flow of the work you should go through, I would like to add some resource that might help you achieve this.

Creating content type and fields: https://www.drupal.org/docs/administering-a-drupal-site/managing-content-0/working-with-content-types-and-fields
https://www.drupal.org/docs/user_guide/en/structure-content-type.html

View and View modes: https://www.drupal.org/docs/user_guide/en/views-concept.html
https://www.drupal.org/docs/8/api/entity-api/display-modes-view-modes-and-form-modes

Handling block of the view: https://www.drupal.org/docs/8/core/modules/block/overview

Feel free to ask if any further explanation is needed.
Thank you