问:
Why does the orientation of my web page change to landscape and the zooming go changing funny when focused inside a textarea?
When I load the web page in portrait on my smartphone, it shows all three columns underneath each other. When I load it in landscape, it shows all columns side by side. This is expected behaviour.

What is not expected behaviour, is that when I focus inside a text box, the layout messes up as the viewport changes. The culprit is the CSS below.

```<code>/* Landscape */
@media screen  and (orientation:landscape) {
    #acceptside, #neutralside, #rejectside { width: 33.3% !important; }
    /* Landscape styles */
}
</code>```

But it's only supposed to make the columns 33% when it's landscape. So why is that line of code being triggered when the textarea is focused on in portrait?

I have a test example here. https://compesh.com/test.html

答:
It is because of large font-size in the textarea. Try reducing the font-size (which is set to 2em currently).

Edit:
In File:
    https://compesh.com/assets/teststylesheet.css
Rule:

```<code> textarea:focus {
    min-height: 4.35em !important;
}
</code>```

is causing this. Removing this rule solves the problem.

Body:
When I load the web page in portrait on my smartphone, it shows all three columns underneath each other. When I load it in landscape, it shows all columns side by side. This is expected behaviour.

What is not expected behaviour, is that when I focus inside a text box, the layout messes up as the viewport changes. The culprit is the CSS below.

/* Landscape */
@media screen  and (orientation:landscape) {
    #acceptside, #neutralside, #rejectside { width: 33.3% !important; }
    /* Landscape styles */
}

But it's only supposed to make the columns 33% when it's landscape. So why is that line of code being triggered when the textarea is focused on in portrait?

I have a test example here. https://compesh.com/test.html

Body:
It is because of large font-size in the textarea. Try reducing the font-size (which is set to 2em currently).

Edit:
In File:
    https://compesh.com/assets/teststylesheet.css
Rule:

 textarea:focus {
    min-height: 4.35em !important;
}

is causing this. Removing this rule solves the problem.


来源: stackexchange

问:
C# XPath help - Expression not working
Here is an example XML doc that matches the one I am getting info from:

```<code><?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>
</code>```

Here is my code to get all books with the genre of Suspense:

```<code>//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}
</code>```

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?

答:
With VTD-XML, the namespace is much simpler... you can choose to whether to ignore namespace or not.</p>

```<code>VTDGen vg = new VTDGen();
if(vg.parseFile("product.xml",true)){
  VTDNav vn = vg.getNav();
  AutoPilot ap = new AutoPilot(vn);
  ap.selectXPath("Produt[Genre='suspence']");
  int i = -1;
  while ((i = ap.evalXPath()) != -1)
  {
                    // processing logic
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C# XPath help - Expression not working

Body:
Here is an example XML doc that matches the one I am getting info from:

<?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>

Here is my code to get all books with the genre of Suspense:

//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?

Body:
With VTD-XML, the namespace is much simpler... you can choose to whether to ignore namespace or not.

VTDGen vg = new VTDGen();
if(vg.parseFile("product.xml",true)){
  VTDNav vn = vg.getNav();
  AutoPilot ap = new AutoPilot(vn);
  ap.selectXPath("Produt[Genre='suspence']");
  int i = -1;
  while ((i = ap.evalXPath()) != -1)
  {
                    // processing logic
   }
}


问:
Error when using a parameter for a period in AWS Data Pipeline
I tried to create a parametrised pipeline on AWS and old the parameters wok fine except the ones to be plugged on a period:

```<code>{
  "id": "DefScheduler",
  "type": "Schedule",
  "startDateTime": "2016-09-26T00:00:00",
  "period": "#{myPeriod}"
}
</code>```

When I open the architect view on the AWS console, I see this error:

```<code>Object:DefScheduler
ERROR: 'period' value should be of the form: <number> [SECONDS|MINUTES|HOURS|DAYS|WEEKS|MONTHS]
</code>```

The value is defined on a parameters json file as follows:

```<code>{
  "description": "How ofter do you want to run the job",
  "id": "myPeriod",
  "type": "String",
  "watermark":"1 HOURS",
  "default":"1 HOURS"
},
</code>```

I tried to override it with a defined value, but no luck. Any ideas? Thank you!

答:
The parameter Period should be of Type Period, but if you trait it as it receive an error.

```<code> {
  "id": "myPeriod",
  "description": "N [years|months|weeks|days|hours|minutes] ",
  "type": "Period",
  "optional":"false"
}
</code>```

Value for parameter attribute 'type' is not supported.

I tried also to traits as two different arguments but doesn't work.

```<code> {
  "id": "myInterval",
  "description": "years|months|weeks|days|hours|minutes]",
  "type": "String",
  "optional":"false"
}

{
      "id": "myTimeUnit",
      "description": "N ",
      "type": "Integer",
      "optional":"false"
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried to create a parametrised pipeline on AWS and old the parameters wok fine except the ones to be plugged on a period:

{
  "id": "DefScheduler",
  "type": "Schedule",
  "startDateTime": "2016-09-26T00:00:00",
  "period": "#{myPeriod}"
}

When I open the architect view on the AWS console, I see this error:

Object:DefScheduler
ERROR: 'period' value should be of the form: <number> [SECONDS|MINUTES|HOURS|DAYS|WEEKS|MONTHS]

The value is defined on a parameters json file as follows:

{
  "description": "How ofter do you want to run the job",
  "id": "myPeriod",
  "type": "String",
  "watermark":"1 HOURS",
  "default":"1 HOURS"
},

I tried to override it with a defined value, but no luck. Any ideas? Thank you!

Body:
The parameter Period should be of Type Period, but if you trait it as it receive an error.

 {
  "id": "myPeriod",
  "description": "N [years|months|weeks|days|hours|minutes] ",
  "type": "Period",
  "optional":"false"
}

Value for parameter attribute 'type' is not supported.

I tried also to traits as two different arguments but doesn't work.

 {
  "id": "myInterval",
  "description": "years|months|weeks|days|hours|minutes]",
  "type": "String",
  "optional":"false"
}

{
      "id": "myTimeUnit",
      "description": "N ",
      "type": "Integer",
      "optional":"false"
    }


问:
JSON move child keys up one level
I have a Python script that parses a JSON file like below:

```<code>[
  {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": null,
    "_source": {
      "lastseen": "2016-09-26T15:45:23",
      "references": [
        "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
      ],
      "affectedPackage": [
        {
          "OS": "OpenWrt",
          "OSVersion": "15.05",
          "packageVersion": "9.9.8-P3-1",
          "packageFilename": "UNKNOWN",
          "arch": "all",
          "packageName": "bind",
          "operator": "lt"
        }
      ],
      "edition": 1,
      "description": "value in here,
      "reporter": "OpenWrt Project",
      "published": "2016-01-24T13:33:41",
      "title": "bind: Security update (4 CVEs)",
      "type": "openwrt",
      "bulletinFamily": "unix",
      "cvelist": [
        "CVE-2015-8704",
      ],
      "modified": "2016-01-24T13:33:41",
      "id": "OPENWRT-SA-000001",
      "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
      "cvss": {
        "score": 7.1,
        "vector": "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
      }
    },
    "sort": [
      34872
    ]
  },
</code>```

I have removed some of the values to keep the post shorter but leaving some in to try to keep the structure.

I want to take all sub keys from the _source key and move them up to the same level as _source and then delete the _source key.

My code to parse the JSON is:

```<code>import json
import logging
import logging.handlers
import os
import pymongo
from pymongo import MongoClient

def import_json(mongo_server,mongo_port, vuln_folder):
    try:
        logging.info('Connecting to MongoDB')
        client = MongoClient(mongo_server, mongo_port)
        db = client['vuln_sets']
        coll = db['vulnerabilities']
        logging.info('Connected to MongoDB')
        basepath = os.path.dirname(__file__)
        filepath = os.path.abspath(os.path.join(basepath, ".."))
        archive_filepath = filepath + vuln_folder
        filedir = os.chdir(archive_filepath)
        file_count = 0
        for item in os.listdir(filedir):
            if item.endswith('.json'):
                file_name = os.path.abspath(item)
                with open(item, 'r') as currentfile:
                    vuln_counter = 0
                    duplicate_count = 0
                    logging.info('Currently processing ' + item)
                    file_count +=1
                    json_data = currentfile.read()
                    vuln_content = json.loads(json_data)
                    for vuln in vuln_content:
                        try:
                            del vuln['_type']
                            coll.insert(vuln, continue_on_error=True)
                            vuln_counter +=1
                        except pymongo.errors.DuplicateKeyError:
                            duplicate_count +=1

                logging.info('Added ' + str(vuln_counter) + ' vulnerabilities for ' + item)
                logging.info('Found ' + str(duplicate_count) + ' duplicate records!')
                os.remove(file_name)
        logging.info('Processed ' + str(file_count) + ' files')
    except Exception as e:
        logging.exception(e)
</code>```

Which you can see already deletes one key that is not needed but that key has no needed data where as I need the sub keys from _source. I am not sure on the best way to achieve this, whether it would be programmatically correct to just re-create the JSON file with the new info but I need to keep the order of the keys and structure apart from moving the sub keys up one level.

答:
I managed to get it working by using the following code:</p>

```<code>for vuln in vuln_content:
                    try:
                        del vuln['_type']
                        new_vuln = {key: vuln[key] for key in vuln if key != '_source'}
                        new_vuln.update(vuln['_source'])
                        coll.insert(new_vuln, continue_on_error=True)
                        vuln_counter +=1
                    except pymongo.errors.DuplicateKeyError:
                        duplicate_count +=1
</code>```

ContentLicense: CC BY-SA 4.0

Title: JSON move child keys up one level

Body:
I have a Python script that parses a JSON file like below:

[
  {
    "_index": "bulletins",
    "_type": "bulletin",
    "_id": "OPENWRT-SA-000001",
    "_score": null,
    "_source": {
      "lastseen": "2016-09-26T15:45:23",
      "references": [
        "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-3193",
      ],
      "affectedPackage": [
        {
          "OS": "OpenWrt",
          "OSVersion": "15.05",
          "packageVersion": "9.9.8-P3-1",
          "packageFilename": "UNKNOWN",
          "arch": "all",
          "packageName": "bind",
          "operator": "lt"
        }
      ],
      "edition": 1,
      "description": "value in here,
      "reporter": "OpenWrt Project",
      "published": "2016-01-24T13:33:41",
      "title": "bind: Security update (4 CVEs)",
      "type": "openwrt",
      "bulletinFamily": "unix",
      "cvelist": [
        "CVE-2015-8704",
      ],
      "modified": "2016-01-24T13:33:41",
      "id": "OPENWRT-SA-000001",
      "href": "https://lists.openwrt.org/pipermail/openwrt-security-announce/2016-January/000001.html",
      "cvss": {
        "score": 7.1,
        "vector": "AV:NETWORK/AC:MEDIUM/Au:NONE/C:NONE/I:NONE/A:COMPLETE/"
      }
    },
    "sort": [
      34872
    ]
  },

I have removed some of the values to keep the post shorter but leaving some in to try to keep the structure.

I want to take all sub keys from the _source key and move them up to the same level as _source and then delete the _source key.

My code to parse the JSON is:

import json
import logging
import logging.handlers
import os
import pymongo
from pymongo import MongoClient

def import_json(mongo_server,mongo_port, vuln_folder):
    try:
        logging.info('Connecting to MongoDB')
        client = MongoClient(mongo_server, mongo_port)
        db = client['vuln_sets']
        coll = db['vulnerabilities']
        logging.info('Connected to MongoDB')
        basepath = os.path.dirname(__file__)
        filepath = os.path.abspath(os.path.join(basepath, ".."))
        archive_filepath = filepath + vuln_folder
        filedir = os.chdir(archive_filepath)
        file_count = 0
        for item in os.listdir(filedir):
            if item.endswith('.json'):
                file_name = os.path.abspath(item)
                with open(item, 'r') as currentfile:
                    vuln_counter = 0
                    duplicate_count = 0
                    logging.info('Currently processing ' + item)
                    file_count +=1
                    json_data = currentfile.read()
                    vuln_content = json.loads(json_data)
                    for vuln in vuln_content:
                        try:
                            del vuln['_type']
                            coll.insert(vuln, continue_on_error=True)
                            vuln_counter +=1
                        except pymongo.errors.DuplicateKeyError:
                            duplicate_count +=1

                logging.info('Added ' + str(vuln_counter) + ' vulnerabilities for ' + item)
                logging.info('Found ' + str(duplicate_count) + ' duplicate records!')
                os.remove(file_name)
        logging.info('Processed ' + str(file_count) + ' files')
    except Exception as e:
        logging.exception(e)

Which you can see already deletes one key that is not needed but that key has no needed data where as I need the sub keys from _source. I am not sure on the best way to achieve this, whether it would be programmatically correct to just re-create the JSON file with the new info but I need to keep the order of the keys and structure apart from moving the sub keys up one level.

Body:
I managed to get it working by using the following code:

for vuln in vuln_content:
                    try:
                        del vuln['_type']
                        new_vuln = {key: vuln[key] for key in vuln if key != '_source'}
                        new_vuln.update(vuln['_source'])
                        coll.insert(new_vuln, continue_on_error=True)
                        vuln_counter +=1
                    except pymongo.errors.DuplicateKeyError:
                        duplicate_count +=1


问:
Communication beetween Javascript and PHP scripts in web app

THE CONTEXT

I'm developing a web app that loads contents dynamycally, retrieving data from a
catalogue of items stored as a MongoDB database in which records of the items and their authors are in two distinct collections of the same database.
Authors ID are stored in the item field creator and refer to the author field @id.
 Each item can have none,one or many authors.

Item sample

```<code>{
    "_id" : ObjectId("59f5de430fa594333bb338a6"),
    "@id" : "http://minerva.atcult.it/rdf/000000016009",
    "creator" : "http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec",
    "identifier" : "000000016009",
    "issued" : "fine sec. XIV - inizi sec. XV",
    "title" : "Quadrans vetus",
    "label" : "Quadrans vetus"
    }
</code>```

Author sample

```<code>    {
    "_id" : ObjectId("59f5d8e80fa594333bb1d72c"),
    "@id" : "http://minerva.atcult.it/rdf/0007e43e-107f-3d18-b4bc-89f8d430fe59",
    "@type" : "foaf:Person",
    "name" : "Risse, Wilhelm"
}
</code>```

WHAT WORKS

I query the database submitting a string in a form, using this PHP script

ITEM PHP SCRIPT

```<code><?php

require 'vendor/autoload.php';
$title=$_GET['item'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->items;

$regex=new MongoDB\BSON\Regex ('^'.$title,'im');
$documentlist=$collection->find(['title'=>$regex],['projection'=>['_id'=>0,'title'=>1,'creator'=>1,'issued'=>1]]);
$items=$documentlist->toArray();
echo (json_encode($items));

?>
</code>```

called by a Javascript script (new_search.js) using ajax, that has also the responsibility to attach to html document a
 for every item that matches the query, inserting the JSON fields and putting them in the provided tags (
,<li class=auth-name, and the last
 in div class=item-info for date).

WHAT DOES NOT WORK

My intent is reproduce the pattern to retrieve author names from another collection in the same database, querying it using author field @id from the html tag <li class=auth-name, using a similar php script and a similar ajax call.

I tried to make a nested ajax call (in the one I used to retrieve the items infos) to invoke author_query.php that performs the MongoDB query on the collection of authors.

So, the question is: Is it possible use the $_GET superglobal to get the html tag that contains the author id @id in order to search it in the database?

Otherwise, how can I adjust the code to pass a javascript variable to php (not by user input) that lets me keep the content already loaded on the page?

UPDATES

To make clearer the question, I follow the tips in the comments and I updated my scripts using JSON directly to provide the needed data.
I also perfom a debug on the js code and it's clear that PHP don't provide any response,in fact ajax calls for authors name fails systematically.

I suppose that occurs because PHP don't receive the data dueto the fact I'm not using the correct syntax probably (in js code or in the php with $_GET or in both) to pass the variable author (I also tried data:'author='+author treating the JSON object author has a string). Anyway I don't understand what is the correct form to write the variable to pass using the data field of ajax().

MY SCRIPTS

JS SCRIPT new_search.js

```<code>   $(document).ready(function () {
    $("#submit").on("tap", function () {
        var item = document.getElementById("search").value;
        var author;
        $.ajax({
            url: "item_query.php",
            type: "GET",
            data: 'item=' + item,
            dataType: "json",
            async:false,
            success: function (items) {
                for (var i = 0; i < items.length; i++) {
                    $("#items-list").append(
                        '<li class="item">' +
                        '<div class="item-photo-container">' +
                        '<img src=images/item_126.jpg>' +
                        "</div><!--end item-photo-container-->" +
                        '<div class="item-info">' +
                        '<ul>' +
                        '<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
                        '<li class="auth-name">' + items[i].creator+ '</li>' +
                        '<li>' + items[i].issued + '</li>' +
                        '</ul>' +
                        '</div><!--end item-info-->' +
                        '</li><!--end item-->'
                    );
                }
            }
        });

        $('.item').each(function () {
            author = $(this).find('.auth-name').text();
            if (author == 'undefined')
                $(this).find('.auth-name').text('Unknown');
            else if(author.indexOf(',')!=-1) {
                author='[{"author":"'+author+'"}]';
                author=author.replace(/,/g,'"},{"author":"');
                author = JSON.parse(author);
                console.log(author);
                $.ajax({
                    url: "author_query.php",
                    type: "GET",
                    data: author,
                    dataType: "json",
                    processData: false,
                    success: function (auth_json) {
                        $(this).find('.auth-name').text('');
                        var author_text=' ';
                        for(var i=0;i<auth_json.length;i++)
                            author_text+=auth_json.name+' ';
                        $(this).find('.auth-name').text(author_text);
                    },
                    error: function () {
                        console.log('Error 1');

                    }
                });
            }
            else{
                author='{"author":"'+author+"}";
                author=JSON.parse(author);
                $.ajax({
                    url: "author_query.php",
                    type: "GET",
                    data: author,
                    dataType: "json",
                    processData: false,
                    success: function (auth_json) {
                        $(this).find('.auth-name').text(auth_json.name);
                    },
                    error: function () {
                        console.log('Error 2');

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

AUTHOR PHP SCRIPT author_query.php

```<code><?php

require 'vendor/autoload.php';
$auth=$_GET['author'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
if(is_array($auth)){
    foreach ($auth as $a){
        $document=$collection->findOne(['@id'=>$a],['projection'=>['_id'=>0,'name'=>1]]);
        $auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
    }
}
else{
    $document=$collection->findOne(['@id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
    $auth_json=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}

echo (json_encode($auth_json));

?>
</code>```

答:
I make the first call to retrieve the item infos asynchronous and the nested that search for the authors name synchronous. In this way I solved the problem.

For sure it is not the best solution, and it needs a quite long,but acceptable, time (<1 second) to load the content.

JS SCRIPT

```<code>$(document).ready(function () {
    $("#submit").on("tap", function () {
        var item = document.getElementById("search").value;
        $.ajax({
            url: "item_query.php",
            type: "GET",
            data: 'item=' + item,
            dataType: "json",
            success: function (items) {
                for (var i = 0; i < items.length; i++) {
                        var authors_names=' ';
                        var authors= JSON.stringify(items[i]);
                        if(authors.indexOf('creator')!=-1){
                            if(authors.charAt(authors.indexOf('"creator":')+'"creator":'.length)!='[')
                                authors=authors.substring(authors.indexOf('"creator":"'),authors.indexOf('"',authors.indexOf('"creator":"')+'"creator":"'.length)+1);
                            else
                                authors=authors.substring(authors.indexOf('"creator"'),authors.indexOf(']',authors.indexOf('"creator"'))+1);
                            authors='{'+authors+'}';
                            //console.log(authors);
                            $.ajax({
                                url: "author_query_v3.php",
                                type: "GET",
                                data: 'authors='+authors,
                                dataType:"json",
                                async:false,
                                success: function (auth_json) {
                                    authors=[];
                                    authors=auth_json;
                                    var author;
                                    for(var j=0;j<authors.length;j++){
                                        author=JSON.parse(authors[j]);
                                        authors_names+=author.name+" | ";
                                    }

                                    console.log(authors_names);
                                },
                                error: function(jqXHR, textStatus, errorThrown) {
                                    console.log(jqXHR+' '+textStatus+ ' '+errorThrown);
                                }
                            });

                        }
                        else{
                            authors_names='Unknown';
                        }

                    $("#items-list").append(
                        '<li class="item">' +
                        '<div class="item-photo-container">' +
                        '<img src=images/item_126.jpg>' +
                        "</div><!--end item-photo-container-->" +
                        '<div class="item-info">' +
                        '<ul>' +
                        '<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
                        '<li class="auth-name">' + authors_names+ '</li>' +
                        '<li>' + items[i].issued + '</li>' +
                        '</ul>' +
                        '</div><!--end item-info-->' +
                        '</li><!--end item-->'
                    );

                }

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

PHP SCRIPT

```<code><?php
require 'vendor/autoload.php';
$auth=$_GET['authors'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
$auth=json_decode($auth);
$auth=$auth->creator;
if(is_array($auth)) {
    foreach ($auth as $a) {
        $document = $collection->findOne(['@id' => $a], ['projection' => ['_id' => 0, 'name' => 1]]);
        $auth_json[] = (MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
    }
}
else{
    $document=$collection->findOne(['@id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
    $auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo(json_encode($auth_json));
?>
</code>```

Body:
THE CONTEXT

I'm developing a web app that loads contents dynamycally, retrieving data from a
catalogue of items stored as a MongoDB database in which records of the items and their authors are in two distinct collections of the same database.
Authors ID are stored in the item field creator and refer to the author field @id.
 Each item can have none,one or many authors.

Item sample

{
    "_id" : ObjectId("59f5de430fa594333bb338a6"),
    "@id" : "http://minerva.atcult.it/rdf/000000016009",
    "creator" : "http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec",
    "identifier" : "000000016009",
    "issued" : "fine sec. XIV - inizi sec. XV",
    "title" : "Quadrans vetus",
    "label" : "Quadrans vetus"
    }

Author sample

    {
    "_id" : ObjectId("59f5d8e80fa594333bb1d72c"),
    "@id" : "http://minerva.atcult.it/rdf/0007e43e-107f-3d18-b4bc-89f8d430fe59",
    "@type" : "foaf:Person",
    "name" : "Risse, Wilhelm"
}

WHAT WORKS

I query the database submitting a string in a form, using this PHP script

ITEM PHP SCRIPT

<?php

require 'vendor/autoload.php';
$title=$_GET['item'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->items;

$regex=new MongoDB\BSON\Regex ('^'.$title,'im');
$documentlist=$collection->find(['title'=>$regex],['projection'=>['_id'=>0,'title'=>1,'creator'=>1,'issued'=>1]]);
$items=$documentlist->toArray();
echo (json_encode($items));

?>

called by a Javascript script (new_search.js) using ajax, that has also the responsibility to attach to html document a
 for every item that matches the query, inserting the JSON fields and putting them in the provided tags (
,<li class=auth-name, and the last
 in div class=item-info for date).

WHAT DOES NOT WORK

My intent is reproduce the pattern to retrieve author names from another collection in the same database, querying it using author field @id from the html tag <li class=auth-name, using a similar php script and a similar ajax call.

I tried to make a nested ajax call (in the one I used to retrieve the items infos) to invoke author_query.php that performs the MongoDB query on the collection of authors.

So, the question is: Is it possible use the $_GET superglobal to get the html tag that contains the author id @id in order to search it in the database?

Otherwise, how can I adjust the code to pass a javascript variable to php (not by user input) that lets me keep the content already loaded on the page?

UPDATES

To make clearer the question, I follow the tips in the comments and I updated my scripts using JSON directly to provide the needed data.
I also perfom a debug on the js code and it's clear that PHP don't provide any response,in fact ajax calls for authors name fails systematically.

I suppose that occurs because PHP don't receive the data dueto the fact I'm not using the correct syntax probably (in js code or in the php with $_GET or in both) to pass the variable author (I also tried data:'author='+author treating the JSON object author has a string). Anyway I don't understand what is the correct form to write the variable to pass using the data field of ajax().

MY SCRIPTS

JS SCRIPT new_search.js

   $(document).ready(function () {
    $("#submit").on("tap", function () {
        var item = document.getElementById("search").value;
        var author;
        $.ajax({
            url: "item_query.php",
            type: "GET",
            data: 'item=' + item,
            dataType: "json",
            async:false,
            success: function (items) {
                for (var i = 0; i < items.length; i++) {
                    $("#items-list").append(
                        '
' +
                        '
' +
                        '' +
                        "
" +
                        '
' +
                        '
' +
                        '

' + items[i].title + '

' +
                        '
' + items[i].creator+ '
' +
                        '
' + items[i].issued + '
' +
                        '
' +
                        '
' +
                        '
'
                    );
                }
            }
        });

        $('.item').each(function () {
            author = $(this).find('.auth-name').text();
            if (author == 'undefined')
                $(this).find('.auth-name').text('Unknown');
            else if(author.indexOf(',')!=-1) {
                author='[{"author":"'+author+'"}]';
                author=author.replace(/,/g,'"},{"author":"');
                author = JSON.parse(author);
                console.log(author);
                $.ajax({
                    url: "author_query.php",
                    type: "GET",
                    data: author,
                    dataType: "json",
                    processData: false,
                    success: function (auth_json) {
                        $(this).find('.auth-name').text('');
                        var author_text=' ';
                        for(var i=0;i<auth_json.length;i++)
                            author_text+=auth_json.name+' ';
                        $(this).find('.auth-name').text(author_text);
                    },
                    error: function () {
                        console.log('Error 1');

                    }
                });
            }
            else{
                author='{"author":"'+author+"}";
                author=JSON.parse(author);
                $.ajax({
                    url: "author_query.php",
                    type: "GET",
                    data: author,
                    dataType: "json",
                    processData: false,
                    success: function (auth_json) {
                        $(this).find('.auth-name').text(auth_json.name);
                    },
                    error: function () {
                        console.log('Error 2');

                    }
                });
            }
        });
    });
});

AUTHOR PHP SCRIPT author_query.php

<?php

require 'vendor/autoload.php';
$auth=$_GET['author'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
if(is_array($auth)){
    foreach ($auth as $a){
        $document=$collection->findOne(['@id'=>$a],['projection'=>['_id'=>0,'name'=>1]]);
        $auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
    }
}
else{
    $document=$collection->findOne(['@id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
    $auth_json=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}

echo (json_encode($auth_json));

?>

Body:
I make the first call to retrieve the item infos asynchronous and the nested that search for the authors name synchronous. In this way I solved the problem.

For sure it is not the best solution, and it needs a quite long,but acceptable, time (<1 second) to load the content.

JS SCRIPT

$(document).ready(function () {
    $("#submit").on("tap", function () {
        var item = document.getElementById("search").value;
        $.ajax({
            url: "item_query.php",
            type: "GET",
            data: 'item=' + item,
            dataType: "json",
            success: function (items) {
                for (var i = 0; i < items.length; i++) {
                        var authors_names=' ';
                        var authors= JSON.stringify(items[i]);
                        if(authors.indexOf('creator')!=-1){
                            if(authors.charAt(authors.indexOf('"creator":')+'"creator":'.length)!='[')
                                authors=authors.substring(authors.indexOf('"creator":"'),authors.indexOf('"',authors.indexOf('"creator":"')+'"creator":"'.length)+1);
                            else
                                authors=authors.substring(authors.indexOf('"creator"'),authors.indexOf(']',authors.indexOf('"creator"'))+1);
                            authors='{'+authors+'}';
                            //console.log(authors);
                            $.ajax({
                                url: "author_query_v3.php",
                                type: "GET",
                                data: 'authors='+authors,
                                dataType:"json",
                                async:false,
                                success: function (auth_json) {
                                    authors=[];
                                    authors=auth_json;
                                    var author;
                                    for(var j=0;j<authors.length;j++){
                                        author=JSON.parse(authors[j]);
                                        authors_names+=author.name+" | ";
                                    }

                                    console.log(authors_names);
                                },
                                error: function(jqXHR, textStatus, errorThrown) {
                                    console.log(jqXHR+' '+textStatus+ ' '+errorThrown);
                                }
                            });

                        }
                        else{
                            authors_names='Unknown';
                        }

                    $("#items-list").append(
                        '<li class="item">' +
                        '<div class="item-photo-container">' +
                        '<img src=images/item_126.jpg>' +
                        "</div><!--end item-photo-container-->" +
                        '<div class="item-info">' +
                        '<ul>' +
                        '<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
                        '<li class="auth-name">' + authors_names+ '</li>' +
                        '<li>' + items[i].issued + '</li>' +
                        '</ul>' +
                        '</div><!--end item-info-->' +
                        '</li><!--end item-->'
                    );

                }

            }
        });
    });
  });

PHP SCRIPT

<?php
require 'vendor/autoload.php';
$auth=$_GET['authors'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
$auth=json_decode($auth);
$auth=$auth->creator;
if(is_array($auth)) {
    foreach ($auth as $a) {
        $document = $collection->findOne(['@id' => $a], ['projection' => ['_id' => 0, 'name' => 1]]);
        $auth_json[] = (MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
    }
}
else{
    $document=$collection->findOne(['@id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
    $auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo(json_encode($auth_json));
?>


问:
Django ModelForm Instantiation after Form Creation
I have a form that consists of a response for each entry in another model. At the time the form is generated the response to each item may or may not exist. I need a form that allows me to update the response if it exists and create it with the form post data if it doesn't exist.

Currently I am iterating through a range and creating my forms with the post data:

```<code>forms = [SpecialNoteForm(request.POST, prefix=str(x), ) for x in rang(1,3)]
</code>```

I am doing this because I don't know how else to access the form data cleanly in order to identify the object that the form should be instantiated with. I tried doing something like this after the forms list was created because i can then access the form data:

```<code>for form in forms:
            try:
                instance = SpecialNote.objects.get(flag=form["flag"].data, host=form["host"].data)
                form.instance = instance
                form.save()
</code>```

The errors on the form persist after I do this, however. I need a way of accessing the data I need to instantiate the object at the time of form creation or a way of re-evaluating the form after i've attached an instance to it.

EDIT

I ran into the same problem with model formsets as I did with my initial approach--I don't know how to instantiate the forms while at the same time allowing for intial values on forms that don't have an instance. I don't want to create all of the model instances before hand because it is import whether or not the user has submitted these with the required fields filled in.

My current approach is still using the model forms:

```<code>forms = []
for n in form_range(request.POST): # calculates number of forms based on post data
    try:
        instance = SpecialNote.objects.get(flag=request.POST.get('%s'%n+'-flag'), host=request.POST.get('%s'%n+'-host'))
    except:
        instance = None
    forms.append(SpecialNoteForm(request.POST, prefix=str(n), instance=instance))
    for form in forms:
        if form.is_valid():
            form.save()
</code>```

In summary, the problem with formsets is I don't know how to properly instantiate the forms without having them be queriable, i.e. already in the database. The problem with using regular model forms and a prefix is that getting the objects that i need to instantiate them with is messy (as you can see from my current approach). I'm looking for a solution to either of these two problems.

答: Multiple identical model forms on one page is what model formsets are for. They should take care of all of those issues.</p>

Body:
I have a form that consists of a response for each entry in another model. At the time the form is generated the response to each item may or may not exist. I need a form that allows me to update the response if it exists and create it with the form post data if it doesn't exist.

Currently I am iterating through a range and creating my forms with the post data:

forms = [SpecialNoteForm(request.POST, prefix=str(x), ) for x in rang(1,3)]

I am doing this because I don't know how else to access the form data cleanly in order to identify the object that the form should be instantiated with. I tried doing something like this after the forms list was created because i can then access the form data:

for form in forms:
            try:
                instance = SpecialNote.objects.get(flag=form["flag"].data, host=form["host"].data)
                form.instance = instance
                form.save()

The errors on the form persist after I do this, however. I need a way of accessing the data I need to instantiate the object at the time of form creation or a way of re-evaluating the form after i've attached an instance to it.

EDIT

I ran into the same problem with model formsets as I did with my initial approach--I don't know how to instantiate the forms while at the same time allowing for intial values on forms that don't have an instance. I don't want to create all of the model instances before hand because it is import whether or not the user has submitted these with the required fields filled in.

My current approach is still using the model forms:

forms = []
for n in form_range(request.POST): # calculates number of forms based on post data
    try:
        instance = SpecialNote.objects.get(flag=request.POST.get('%s'%n+'-flag'), host=request.POST.get('%s'%n+'-host'))
    except:
        instance = None
    forms.append(SpecialNoteForm(request.POST, prefix=str(n), instance=instance))
    for form in forms:
        if form.is_valid():
            form.save()

In summary, the problem with formsets is I don't know how to properly instantiate the forms without having them be queriable, i.e. already in the database. The problem with using regular model forms and a prefix is that getting the objects that i need to instantiate them with is messy (as you can see from my current approach). I'm looking for a solution to either of these two problems.


问:
How to open file with tkfiledialog and read the content with notepad
I want to read the content of the selected file by opening with tk filedialog. When i select the file and click on open button the file doesn't open but rather close the dialog box .How can i  open the selected file with notepad so i can be able to read the content in the file.

```<code>from tkinter import *
from tkinter import filedialog

def my_file():
    filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file",
                                       filetypes=(("text files", "*.txt"), ("all files", "*.*")))

root = Tk()
root.geometry("300x300")
                              #open the selected txt file with notepad to read the content
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()
</code>```

EDIT
With hint from @PM 2RING and @Erik  i changed the filedialog.askopenfile to filedialog.askopenfilename to return it to open with notepad.exe when i select the file.
THis is the code:

```<code>from tkinter import *
from tkinter import filedialog
import os

def my_file():
    filename = filedialog.askopenfilename( initialdir="C:/", title="select
file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
    for f in filename:
        return f
    os.system(r"C:/notepad.exe" + f)

root = Tk()
root.geometry("300x300")
                          #open the selected txt file with notepad to read
the content
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()
</code>```

it output this error :

Blockquote'C:/notepad.exet' is not recognized as an internal or external command,
  operable program or batch file.
  Blockquote

but when i changed the return to print it print the directory to terminal.I tried to open with subprocess

```<code> subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f])
</code>```

it also doesn't open with this one to.

答:
There's a few things which need to be amended here.

First of all, C:/notepad.exe is not the location of Notepad (At least not on any Windows machine with a default setup), you can simply use notepad.exe which should make it more compatible with systems that have moved Notepad to another location (citation needed).

Secondly, executing . . .

```<code>for f in filename:
    return f
os.system(r"C:/notepad.exe" + f)
</code>```

Doesn't do what you seem to think it does. What's actually happening here is that your program is loading the string into the loop, evaluating the first character (Probably "C") and then returning the string to the Button widget which doesn't receive any returned values. This then breaks your function, so it never actually reaches your declaration of os.system(r"C:/notepad.exe" + f).

You also need to include a space between the statement used to open Notepad notepad.exe and the actual file declaration f, otherwise you're running something like notepad.exeC:/text.txt which is going to throw an error at you.

What you should be doing is something like the below:

```<code>from tkinter import *
from tkinter import filedialog
import os

def my_file():
    filename = filedialog.askopenfilename( initialdir="C:/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
    os.system(r"notepad.exe " + filename)

root = Tk()
root.geometry("300x300")
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()
</code>```

I'd like to add that I have no clue why you're doing this, why not simply display the text in a Text widget? What you're doing here is adding one extra step for people to open files in Notepad, instead of opening file explorer, finding the file and then opening it they have to open your program, then open file explorer, then find the file and then open it. It's adding at least one extra click not to mention the load time of your program.

Body:
I want to read the content of the selected file by opening with tk filedialog. When i select the file and click on open button the file doesn't open but rather close the dialog box .How can i  open the selected file with notepad so i can be able to read the content in the file.

from tkinter import *
from tkinter import filedialog

def my_file():
    filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file",
                                       filetypes=(("text files", "*.txt"), ("all files", "*.*")))

root = Tk()
root.geometry("300x300")
                              #open the selected txt file with notepad to read the content
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()

EDIT
With hint from @PM 2RING and @Erik  i changed the filedialog.askopenfile to filedialog.askopenfilename to return it to open with notepad.exe when i select the file.
THis is the code:

from tkinter import *
from tkinter import filedialog
import os

def my_file():
    filename = filedialog.askopenfilename( initialdir="C:/", title="select
file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
    for f in filename:
        return f
    os.system(r"C:/notepad.exe" + f)

root = Tk()
root.geometry("300x300")
                          #open the selected txt file with notepad to read
the content
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()

it output this error :

Blockquote'C:/notepad.exet' is not recognized as an internal or external command,
  operable program or batch file.
  Blockquote

but when i changed the return to print it print the directory to terminal.I tried to open with subprocess

 subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f])

it also doesn't open with this one to.

Body:
There's a few things which need to be amended here.

First of all, C:/notepad.exe is not the location of Notepad (At least not on any Windows machine with a default setup), you can simply use notepad.exe which should make it more compatible with systems that have moved Notepad to another location (citation needed).

Secondly, executing . . .

for f in filename:
    return f
os.system(r"C:/notepad.exe" + f)

Doesn't do what you seem to think it does. What's actually happening here is that your program is loading the string into the loop, evaluating the first character (Probably "C") and then returning the string to the Button widget which doesn't receive any returned values. This then breaks your function, so it never actually reaches your declaration of os.system(r"C:/notepad.exe" + f).

You also need to include a space between the statement used to open Notepad notepad.exe and the actual file declaration f, otherwise you're running something like notepad.exeC:/text.txt which is going to throw an error at you.

What you should be doing is something like the below:

from tkinter import *
from tkinter import filedialog
import os

def my_file():
    filename = filedialog.askopenfilename( initialdir="C:/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*")))
    os.system(r"notepad.exe " + filename)

root = Tk()
root.geometry("300x300")
b = Button(root, text="open text file", command = my_file).pack()

root.mainloop()

I'd like to add that I have no clue why you're doing this, why not simply display the text in a Text widget? What you're doing here is adding one extra step for people to open files in Notepad, instead of opening file explorer, finding the file and then opening it they have to open your program, then open file explorer, then find the file and then open it. It's adding at least one extra click not to mention the load time of your program.


问:
Why I cannot find window?
I use this example to send a string between two applications.

When I press the Send button for the first time, the string is sent to the Receiver, but only a part of the string is received.

When I press the Send button for the second time, I get "Window not found!".
The window is right there on screen. Why it works when I press the button the first time, but not the second time?

This is the sender:

```<code>procedure TfrmSender.SendString;
var
 stringToSend : string;
 copyDataStruct : TCopyDataStruct;
begin
 Caption:= 'Sending';
 stringToSend := 'About - Delphi - Programming';

 copyDataStruct.dwData := 12821676; //use it to identify the message contents
 copyDataStruct.cbData := 1 + Length(stringToSend) ;
 copyDataStruct.lpData := PChar(stringToSend);

 SendData(copyDataStruct) ;
end;

procedure TfrmSender.SendData(CONST copyDataStruct: TCopyDataStruct);
VAR
   receiverHandle : THandle;
   res : integer;
begin
 receiverHandle := FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver')) ;
 if receiverHandle = 0 then
  begin
   Caption:= 'Receiver window NOT found!';
   EXIT;
  end;

 res:= SendMessage(receiverHandle, WM_COPYDATA, Integer(Handle), Integer(@copyDataStruct));
 if res= 0 then Caption:= 'Receiver window found but msg not hand';
end;
</code>```

And this is the receiver:

```<code>procedure TfrmReceiver.WMCopyData(var Msg: TWMCopyData);
VAR
   s : string;
begin
 if Msg.CopyDataStruct.dwData = 12821676 then
  begin
   s := PChar(Msg.CopyDataStruct.lpData);
   msg.Result := 2006;  //Send something back

   Winapi.Windows.Beep(800, 300);
   Caption:= s;
  end
end;
</code>```

答:
To summarize the comments there are two errors

1) (See @Tom Brunberg) is that the length is set incorrectly which is why you only get part (about half? of the string)

It should be

```<code>copyDataStruct.cbData := sizeof( Char )*(Length(stringToSend) + 1 );
</code>```

2) The forms caption is being changed which invalidates the expression

```<code>FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver'))
</code>```

because the second parameter is the form's caption (in Delphi terminology)

Title: Why I cannot find window?

Body:
I use this example to send a string between two applications.

When I press the Send button for the first time, the string is sent to the Receiver, but only a part of the string is received.

When I press the Send button for the second time, I get "Window not found!".
The window is right there on screen. Why it works when I press the button the first time, but not the second time?

This is the sender:

procedure TfrmSender.SendString;
var
 stringToSend : string;
 copyDataStruct : TCopyDataStruct;
begin
 Caption:= 'Sending';
 stringToSend := 'About - Delphi - Programming';

 copyDataStruct.dwData := 12821676; //use it to identify the message contents
 copyDataStruct.cbData := 1 + Length(stringToSend) ;
 copyDataStruct.lpData := PChar(stringToSend);

 SendData(copyDataStruct) ;
end;

procedure TfrmSender.SendData(CONST copyDataStruct: TCopyDataStruct);
VAR
   receiverHandle : THandle;
   res : integer;
begin
 receiverHandle := FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver')) ;
 if receiverHandle = 0 then
  begin
   Caption:= 'Receiver window NOT found!';
   EXIT;
  end;

 res:= SendMessage(receiverHandle, WM_COPYDATA, Integer(Handle), Integer(@copyDataStruct));
 if res= 0 then Caption:= 'Receiver window found but msg not hand';
end;

And this is the receiver:

procedure TfrmReceiver.WMCopyData(var Msg: TWMCopyData);
VAR
   s : string;
begin
 if Msg.CopyDataStruct.dwData = 12821676 then
  begin
   s := PChar(Msg.CopyDataStruct.lpData);
   msg.Result := 2006;  //Send something back

   Winapi.Windows.Beep(800, 300);
   Caption:= s;
  end
end;

Body:
To summarize the comments there are two errors

1) (See @Tom Brunberg) is that the length is set incorrectly which is why you only get part (about half? of the string)

It should be

copyDataStruct.cbData := sizeof( Char )*(Length(stringToSend) + 1 );

2) The forms caption is being changed which invalidates the expression

FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver'))

because the second parameter is the form's caption (in Delphi terminology)


问:
In React, how to bind an input's value when rendering a list of inputs?
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

```<code>class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}
</code>```

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

答:
You can move the tweets variable to the state to maintain consistency in that array.

class App extends React.Component {
  constructor(props) {
   super(props)
    this.state = {
     tweets: [
       { id: 1, link: 'example.com' },
        { id: 2, link: 'example2.com' }
      ]
    };
  };

  setTweets = index => e => {
   const { tweets } = this.state
    tweets[index].text = e.target.value
    this.setState({ tweets })
  }

  render() {
   const { tweets } = this.state
    return (

        {tweets.map((tweet, index) =>

            <input type="text" placeholder="text" onChange={this.setTweets(index)} />
            Tweet

        )}

    );
  }
}```

Updated Jsfiddle: https://jsfiddle.net/u5c21wj9/6/

Body:
I'm rendering a list of inputs and I want to bind each input's value to a link's href. My current attempt renders https://twitter.com/intent/tweet?text=undefined:

class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  render() {
    return (

        {this.tweets.map(tweet =>

            <input type="text" placeholder="text" onChange={e => tweet.text = e.target.value} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet

        )}

    );
  }
}

This probably needs to involve setState but I have no idea how to achieve that when rendering a list. I've tried to do some research on this but didn't found anything helpful.

JSFiddle: https://jsfiddle.net/nunoarruda/u5c21wj9/3/

Any ideas?

Body:
You can move the tweets variable to the state to maintain consistency in that array.

class App extends React.Component {
  constructor(props) {
   super(props)
    this.state = {
     tweets: [
       { id: 1, link: 'example.com' },
        { id: 2, link: 'example2.com' }
      ]
    };
  };

  setTweets = index => e => {
   const { tweets } = this.state
    tweets[index].text = e.target.value
    this.setState({ tweets })
  }

  render() {
   const { tweets } = this.state
    return (
      <div>
        {tweets.map((tweet, index) =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={this.setTweets(index)} />
            <a href={`https://twitter.com/intent/tweet?text=${tweet.text}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}

Updated Jsfiddle: https://jsfiddle.net/u5c21wj9/6/


问:
How do I change the default schema in sql developer?
I don't see any tables in the tables section of a database that I've linked to w/ SQL developer. The DB admin says I need to change the default schema in SQL developer. How do I do that?

答:
After you granted the permissions to the specified user you have to do this at filtering:

First step:

Second step:

Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).


问:
Defining IFESLE in arena
I am using Arena simulation software. I need to define "if" in the expression section of the Process Module. I could not find any instruction to define "ifelse" function.</p>

答:
I never found IF statement in Arena simulation.

But don't worry. There is workaround with using expressions.

According to official Documentation:

Logical Expression Evaluation

ASSIGN: InventoryLevel = 50 *
  (SystemStatus==Early) +
              30 * (SystemStatus==Late);

Assign InventoryLevel a value of 50 if the variable SystemStatus is
  equal to Early (logical expressions evaluate to 1 for TRUE, 0 for
  FALSE). If SystemStatus equals Late, assign InventoryLevel to 30. If
  neither is true, assign SystemStatus equal to 0. This single ASSIGN
  block may have been used to replace a BRANCH block (to check the value
  of SystemStatus) and two ASSIGN blocks (to assign the correct value).

Title: Defining IFESLE in arena


问:
PHP website form to database doesn't work
I've currently made an php form on my website that sends the information to my database, but when someone uses it it only posts two of the 4 input fields to the database, see the image i linked below.

It's an refund site by the way written in Norwegian so, please use Google Translate if needed :D

Here's my refund.php:

```<code>    <html>

<head>
  <link type="text/css" media="all" href="https://bootswatch.com/4/lumen/bootstrap.min.css" rel="stylesheet" />

 <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <meta charset="utf-8" />
    <title>NattLAN</title>
    <meta name="author" content="ukieweb" />
    <meta name="keywords" content="soon, css3, template, html5 template" />
    <meta name="description" content="Balk - Page Template" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <!-- Favicons -->
    <link rel="apple-touch-icon" sizes="144x144" href="assets/img/favicons/apple-touch-icon-144x144.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="assets/img/favicons/apple-touch-icon-114x114.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="assets/img/favicons/apple-touch-icon-72x72.png" />
    <link rel="apple-touch-icon" href="assets/img/favicons/apple-touch-icon.png" />
    <link rel="shortcut icon" href="assets/img/favicons/favicon.png" />
    <!-- Google Fonts -->
    <link href='http://fonts.googleapis.com/css?family=Exo+2:400,100,100italic,200,200italic,300,300italic,400italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic' rel='stylesheet' type='text/css'>
<style>
body {
    background-color: #F0F0F0;
}
</style>
</head>

<body>
<!DOCTYPE html>
<p align="center"><img src="http://24.media.tumblr.com/0128a30614276768bf956ad868604b5d/tumblr_n6zhprHRGv1qgefibo1_400.gif"></p>
<p> </p>
<h3 align="center" color="black"> Refunderingsskjema</h3>
<form action="send.php" method="post">
<p align="center">Navn på deltaker:<br></p>
  <p align="center"><input type="text" name="u_deltaker" required><br></p>

<p align="center">Navn på betaler:<br></p>
  <p align="center"><input type="text" name="u_payer" required><br></p>

<p align="center">Telefonnummer:<br></p>
  <p align="center"><input type="text" name="u_phone" required><br></p>

<p align="center">Kontonummer:<br></p>
  <p align="center"><input type="text" name="u_konto" required><br></p>
<p align="center"><input class="btn btn-success" type="submit" value="Send"><br></p>
</form>
<p align="center"><a href="help.php">Hjelp! Hva betyr alt dette ovenfor? KLIKK HER!</a></p>
</body>
</html>
  <footer id="footer">
        <div class="container">

            <!-- footer socials -->
            <div class="row">

                <div class="footer_socials col-sm-12 text-center">

                    <div class="contact_icons">
                        <ul class="contact_socials clearfix">
                            <!-- social icons -->
                        </ul>
                    </div>
                     <img src="oldwebsite/assets/nb.png" width="162" height="53" class="navbar-logo-img" alt="">
<div class="copyright">Kontakt: kontakt@nattlan.net</div>
<div class="copyright">© Copyright 2017 NattLAN</div>
</code>```

Here's my send.php:

```<code><title>NattLAN - Refund</title>
<?php

require 'connection.php';
$conn        = Connect();
$deltaker    = $conn->real_escape_string($_POST['u_deltaker']);
$payer       = $conn->real_escape_string($_POST['u_payer']);
$phone       = $conn->real_escape_string($_POST['u_phone']);
$konto       = $conn->real_escape_string($_POST['u_konto']);
$query       = "INSERT into tb_cform (u_deltaker,u_payer,u_phone,u_konto) VALUES('" . $deltaker . "','" . $payer . "','" . $phone . "','" . $konto . "')";
$success     = $conn->query($query);

if (!$success) {
    die("Fail".$conn->error);

}

echo "Success";

$conn->close();

?>
</code>```

Here's my connection.php:

```<code><?php
function Connect()
{
 $dbhost = "PRIVATE";
 $dbuser = "PRIVATE";
 $dbpass = "PRIVATE";
 $dbname = "PRIVATE";

 // Create connection
 $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);

 return $conn;
}

?>
</code>```

My database only put's the two last information from the form in the database, image showing the problem:

Image form DB showing that it inputs 0's in two of the fields:

https://prntscr.com/had0ak

Can someone help me figure out why this happens?
Thanks :D

答: I think it's inserting 0 because the column type is int? Check on that and change to varchar.

Body:
I've currently made an php form on my website that sends the information to my database, but when someone uses it it only posts two of the 4 input fields to the database, see the image i linked below.

It's an refund site by the way written in Norwegian so, please use Google Translate if needed :D

Here's my refund.php:

  <link type="text/css" media="all" href="https://bootswatch.com/4/lumen/bootstrap.min.css" rel="stylesheet" />

 <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <meta charset="utf-8" />
    <title>NattLAN</title>
    <meta name="author" content="ukieweb" />
    <meta name="keywords" content="soon, css3, template, html5 template" />
    <meta name="description" content="Balk - Page Template" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

    <link rel="apple-touch-icon" sizes="144x144" href="assets/img/favicons/apple-touch-icon-144x144.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="assets/img/favicons/apple-touch-icon-114x114.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="assets/img/favicons/apple-touch-icon-72x72.png" />
    <link rel="apple-touch-icon" href="assets/img/favicons/apple-touch-icon.png" />
    <link rel="shortcut icon" href="assets/img/favicons/favicon.png" />

    <link href='http://fonts.googleapis.com/css?family=Exo+2:400,100,100italic,200,200italic,300,300italic,400italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic' rel='stylesheet' type='text/css'>

<!DOCTYPE html>

 Refunderingsskjema

<form action="send.php" method="post">

Navn på deltaker:

<input type="text" name="u_deltaker" required>

Navn på betaler:

<input type="text" name="u_payer" required>

Telefonnummer:

<input type="text" name="u_phone" required>

Kontonummer:

<input type="text" name="u_konto" required>

<input class="btn btn-success" type="submit" value="Send">

</form>

Hjelp! Hva betyr alt dette ovenfor? KLIKK HER!

Kontakt: kontakt@nattlan.net

© Copyright 2017 NattLAN

Here's my send.php:

<title>NattLAN - Refund</title>
<?php

require 'connection.php';
$conn        = Connect();
$deltaker    = $conn->real_escape_string($_POST['u_deltaker']);
$payer       = $conn->real_escape_string($_POST['u_payer']);
$phone       = $conn->real_escape_string($_POST['u_phone']);
$konto       = $conn->real_escape_string($_POST['u_konto']);
$query       = "INSERT into tb_cform (u_deltaker,u_payer,u_phone,u_konto) VALUES('" . $deltaker . "','" . $payer . "','" . $phone . "','" . $konto . "')";
$success     = $conn->query($query);

if (!$success) {
    die("Fail".$conn->error);

}

echo "Success";

$conn->close();

?>

Here's my connection.php:

<?php
function Connect()
{
 $dbhost = "PRIVATE";
 $dbuser = "PRIVATE";
 $dbpass = "PRIVATE";
 $dbname = "PRIVATE";

 // Create connection
 $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);

 return $conn;
}

?>

My database only put's the two last information from the form in the database, image showing the problem:

Image form DB showing that it inputs 0's in two of the fields:

https://prntscr.com/had0ak

Can someone help me figure out why this happens?
Thanks :D


问:
How do I give external or local html doc link to bootstrap nav-pills?
I need to link my another webpage to my pictures nav menu.
Ex: if I click my pictures menu , it opens google.com.

Framework: bootstrap 4

```<code>div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My music</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My videos</a>
                </li>
            </ul>
        </div>
    </div>
</code>```

答:
This will work  :)</p>

```<code><div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" target="_blank" href="http://google.com">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My music</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My videos</a>
                </li>
            </ul>
        </div>
    </div>
</code>```

Body:
I need to link my another webpage to my pictures nav menu.
Ex: if I click my pictures menu , it opens google.com.

Framework: bootstrap 4

div class="row row2">

                    About me

                    My pictures

                    My music

                    My files

                    My videos

Body:
This will work  :)

<div class="row row2">
        <div class="col-md-12">
            <ul class="nav nav-pills justify-content-center nav-justified" role="tablist">
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">About me</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" target="_blank" href="http://google.com">My pictures</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My music</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My files</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="pill" href="#">My videos</a>
                </li>
            </ul>
        </div>
    </div>


问:
Creating a database in Mongo: can't connect, get "connect failed"
I want to create a new database in Mongo. However, I'm having trouble connecting:

```<code>:~$ mongo
MongoDB shell version: 1.6.5
connecting to: test
Tue Dec 21 18:16:25 Error: couldn't connect to server 127.0.0.1 (anon):1154
exception: connect failed
</code>```

How can I connect to mongo in order to create a new database? Alternatively, can I create a new database from the command line?

Slightly surprisingly, the Mongo docs don't seem to cover how to create a database.

Thanks.

答: You'll need to run mongod (the daemon) before you can use mongo (the client), it's easiest to just run it in another shell; These should be in your path if mongo is installed correctly. After that the docs should get you through creating and editing dbs and collections.</p>

Body:
I want to create a new database in Mongo. However, I'm having trouble connecting:

:~$ mongo
MongoDB shell version: 1.6.5
connecting to: test
Tue Dec 21 18:16:25 Error: couldn't connect to server 127.0.0.1 (anon):1154
exception: connect failed

How can I connect to mongo in order to create a new database? Alternatively, can I create a new database from the command line?

Slightly surprisingly, the Mongo docs don't seem to cover how to create a database.

Thanks.


问:
How to use pkglib_LTLIBRARIES = test.la to only build *.so
I'm using autotools to build a shared object.

Using pkglib_LTLIBRARIES in my Makefile.am causes a libtest.la AND libtest.so to be built.

I only want it to build/install libtest.so.

Is this possible?

答:
Another option would be setting this in configure.ac:

```<code>LT_INIT([disable-static])
</code>```

See documentation on LT_INIT.

OwnerDisplayName: minimoses

Body:
Another option would be setting this in configure.ac:

LT_INIT([disable-static])

See documentation on LT_INIT.


问:
Select div with a text inside in JS
I want to modify a div with a special text inside like this.

```<code><div>
<p>
A global issue
</p>
</div>
</code>```

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

答:
If you want to use simple javascript solution, see snippet below

First, get all divs from page

Second, store your search text in a variable

Third, loop through all divs and find the one containing your text, then you can do whatever you want with it. I added a backgroundColor red to it

var divs = document.querySelectorAll("div");
var myText = "A global issue";
var i;
for (i = 0; i < divs.length; i++) {
  if (divs[i].textContent.indexOf(myText) > 0 ) {
  divs[i].style.backgroundColor = "red";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
    A global issue
  </p>
  <p>
    More text here
  </p>
</div>
<div>
  <p>
    Not a good text
  </p>
</div></code>```

Title: Select div with a text inside in JS

Body:
I want to modify a div with a special text inside like this.

A global issue

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

Body:
If you want to use simple javascript solution, see snippet below

First, get all divs from page

Second, store your search text in a variable

Third, loop through all divs and find the one containing your text, then you can do whatever you want with it. I added a backgroundColor red to it

var divs = document.querySelectorAll("div");
var myText = "A global issue";
var i;
for (i = 0; i < divs.length; i++) {
  if (divs[i].textContent.indexOf(myText) > 0 ) {
  divs[i].style.backgroundColor = "red";
  }
}

<div>
  <p>
    A global issue
  </p>
  <p>
    More text here
  </p>
</div>
<div>
  <p>
    Not a good text
  </p>
</div>


问:
Yndefined reference to function
When I build the code below, I get an error stating the following (on main functions A and B):

undefined reference to 'new_string(char const*)'

I'm not sure what's wrong, or how to fix it.

string.h (header)

```<code>typedef struct tag_string {
    char *str;
    unsigned int len;

    int (*compare)(struct tag_string *target);
    struct tag_string *(*set)(struct tag_string *target);

} string;

string *new_string(const char *str);
void delete_string(string *str);

int string_compare(string *target);
string *string_set(string *target);
</code>```

Other source file

```<code>#include "string.h"
#include <stdlib.h>

extern string *call;

string *new_string(char *str){
string *ptr = 0;

int n = 0;

ptr = (string *)malloc(sizeof(string));

ptr->str = 0;
ptr->len = 0;

ptr->compare = string_compare;
ptr->set = string_set;

if(str){
    for(ptr->len = 0; str[ptr->len];ptr->len++);

    ptr-> str = (char *)malloc(ptr->len+1);

    if(ptr->str == 0){
        free(ptr);
        return 0;
    }

    for(int i=0;i<ptr->len+1;i++){
        ptr->str[i] = str[i];
    }
}else {
    ptr->str = (char *)malloc(1);
    ptr->str[0] = 0;
}

return ptr;
}
</code>```

Main file

```<code>#include <iostream>
#include "string.h"

extern void *call;

int main(void){
    /*A*/ string *mystr = new_string("My str");
    /*B*/ string *strNULL = new_string(0);

}
</code>```

答:
It is likely to be a bad C/C++ mix.

The main source is a C++ source because of the #include <iostream>. When you include string.h, you get a C++ declaration for :

```<code>string *new_string(const char *str);
</code>```

If the other source file is a C one (plausible because of the #include <stdlib.h>) it only defines a C function, which is not the same as a C++ one: to reach the C function from C++ you need:

```<code>extern "C" string *new_string(const char *str);
</code>```

Just a guess, but changing the include in main should be enough:

```<code>#include <iostream>
extern "C" {
#include "string.h"
}

extern void *call;

int main(void){
    /*A*/ string *mystr = new_string("My str");
    /*B*/ string *strNULL = new_string(0);

}
</code>```

But you have an inconsistent declaration:

```<code>string *new_string(const char *str);  // in header file
</code>```

vs.

```<code>string *new_string(char *str);       // in other source file
</code>```

And using a name of the header from the standard library (string.h) that could be used under the hood by other standard include is a very bad idea: it broke in my CLang.

Title: Yndefined reference to function

Body:
When I build the code below, I get an error stating the following (on main functions A and B):

undefined reference to 'new_string(char const*)'

I'm not sure what's wrong, or how to fix it.

string.h (header)

typedef struct tag_string {
    char *str;
    unsigned int len;

    int (*compare)(struct tag_string *target);
    struct tag_string *(*set)(struct tag_string *target);

} string;

string *new_string(const char *str);
void delete_string(string *str);

int string_compare(string *target);
string *string_set(string *target);

Other source file

#include "string.h"
#include <stdlib.h>

extern string *call;

string *new_string(char *str){
string *ptr = 0;

int n = 0;

ptr = (string *)malloc(sizeof(string));

ptr->str = 0;
ptr->len = 0;

ptr->compare = string_compare;
ptr->set = string_set;

if(str){
    for(ptr->len = 0; str[ptr->len];ptr->len++);

    ptr-> str = (char *)malloc(ptr->len+1);

    if(ptr->str == 0){
        free(ptr);
        return 0;
    }

    for(int i=0;i<ptr->len+1;i++){
        ptr->str[i] = str[i];
    }
}else {
    ptr->str = (char *)malloc(1);
    ptr->str[0] = 0;
}

return ptr;
}

Main file

#include <iostream>
#include "string.h"

extern void *call;

int main(void){
    /*A*/ string *mystr = new_string("My str");
    /*B*/ string *strNULL = new_string(0);

}

Body:
It is likely to be a bad C/C++ mix.

The main source is a C++ source because of the #include <iostream>. When you include string.h, you get a C++ declaration for :

string *new_string(const char *str);

If the other source file is a C one (plausible because of the #include <stdlib.h>) it only defines a C function, which is not the same as a C++ one: to reach the C function from C++ you need:

extern "C" string *new_string(const char *str);

Just a guess, but changing the include in main should be enough:

#include <iostream>
extern "C" {
#include "string.h"
}

extern void *call;

int main(void){
    /*A*/ string *mystr = new_string("My str");
    /*B*/ string *strNULL = new_string(0);

}

But you have an inconsistent declaration:

string *new_string(const char *str);  // in header file

vs.

string *new_string(char *str);       // in other source file

And using a name of the header from the standard library (string.h) that could be used under the hood by other standard include is a very bad idea: it broke in my CLang.


问:
LibreOffice Basic Macro command converting Calc cellRange to RTF/HTML
My goal is to fill a LibreOffice calc sheet, and silently send a cell range by email when the user clicks the send-off button (and once more to confirm).

So there is three part to this.

A push button with a request to confirm. (Easy and done.)

Select Cell Range and turn it into rich text format (Haven't yet found)

Send rich text email from within the sheet. (Will tackle the "silent" part later)

I tried copying the range to the clipboard with unoService but it seemed over-complicated and full of errors.

Here's what I have:

''''Send by e-mail enriched text

Sub Main
    Dim Doc, Sheet, Range, Rtf, Exec as Object
End Sub

'Confirm it
Sub SendTableApproval
    If MsgBox ("Ready to email?", MB_YESNO + MB_DEFBUTTON2) = IDYES Then
        CopyTable()
    End If
End Sub

'Copy it
Sub CopyTable
    Doc = ThisComponent
    View = Doc.CurrentController
    Frame = View.Frame
    Sheet = Doc.Sheets.getByIndex(0)
    Range = Sheet.getCellrangeByName("a1:f45")
    Exec = createUnoService("com.sun.star.frame.DispatchHelper")

    View.Select(Range)
    Cells = View.getTransferable()
    Exec.executeDispatch(Frame, ".uno:Deselect", "", 0, array())
    'SimpleMailTo(Cells)
End Sub

'Mail it
Sub SimpleMailTo(body)
    Dim launcher as object
    Dim eAddress, eSubject, eBody, aHTMLanchor as string
    launcher = CreateUnoService("com.sun.star.system.SystemShellExecute")
    eAddress = "tu@domo.eg"
    eSubject = "Cotidie agenda futuendane"
    eBody = body
    aHTMLanchor = "mailto:" & eAddress & "?subject=" & eSubject & "&&body=" & eBody
    launcher.execute(aHTMLanchor, "", 0)
End Sub
```

I still do not know after three days of research over methods, properties, uno.

My question is, simply put, How can I convert a transferable content to HTML/RTF?

答:
Simply copying and pasting into an email produces the result you are asking for.  The code on the LibreOffice side should look like this.

```<code>dispatcher.executeDispatch(document, ".uno:Copy", "", 0, Array())
</code>```

It sounds like you already tried this, but something didn't work.  Perhaps you could elaborate on what went wrong.

Another approach would be to write the spreadsheet to a temporary HTML or XHTML file.   Then parse the temporary file to grab the part needed for the email.

AFAIK there is no such command to turn a cell range into rich text format with UNO.  To do it that way, you would need to loop through each text range of each cell, read its formatting properties and then generate the HTML yourself.

EDIT:

Good idea about XTransferable.  The following Java code adapted from the DevGuide gets an HTML string and then prints it.  I believe this would be a good solution for your needs.

```<code>public void displayHTMLFromClipboard()
{
    try
    {
        Object oClipboard = xMCF.createInstanceWithContext(
            "com.sun.star.datatransfer.clipboard.SystemClipboard", xContext);
        XClipboard xClipboard = (XClipboard)
            UnoRuntime.queryInterface(XClipboard.class, oClipboard);
        XTransferable xTransferable = xClipboard.getContents();
        DataFlavor[] aDflvArr = xTransferable.getTransferDataFlavors();
        System.out.println("Available clipboard formats:");
        DataFlavor aChosenFlv = null;
        for (int i=0;i<aDflvArr.length;i++)
        {
            System.out.println(
                "MimeType: " + aDflvArr[i].MimeType +
                " HumanPresentableName: " + aDflvArr[i].HumanPresentableName );
            if (aDflvArr[i].MimeType.equals("text/html"))
            {
                aChosenFlv = aDflvArr[i];
            }
        }
        System.out.println("");
        try
        {
            if (aChosenFlv != null)
            {
                System.out.println("HTML text on the clipboard...");
                Object aData = xTransferable.getTransferData(aChosenFlv);
                String s = new String((byte[])aData, Charset.forName("ISO-8859-1"));
                System.out.println(s);
            }
        }
        catch (UnsupportedFlavorException exc)
        {
            exc.printStackTrace();
        }
    }
    catch(com.sun.star.uno.Exception exc)
    {
        exc.printStackTrace();
    }
}
</code>```

If you plan to use Basic, it might be a good idea to do some research into the proper way to convert bytes.  The code I have below seems to work but is probably unreliable and unsafe, and will not work for many languages.  A few of my initial attempts crashed before this finally worked.

```<code>Sub DisplayClipboardData
    oClipboard = createUnoService("com.sun.star.datatransfer.clipboard.SystemClipboard")
    xTransferable = oClipboard.getContents()
    aDflvArr = xTransferable.getTransferDataFlavors()
    For i = LBound(aDflvArr) To UBound(aDflvArr)
        If aDflvArr(i).MimeType = "text/html" Then
            Dim aData() As Byte
            aData = xTransferable.getTransferData(aDflvArr(i))
            Dim s As String
            For j = LBound(aData) to UBound(aData)
                s = s & Chr(aData(j))  'XXX: Probably a bad way to do this!
            Next j
            Print(s)
        End If
    Next
End Sub
</code>```

One more suggestion: Python might be a better language choice here.  In many ways, using Python with LibreOffice is easier than Java.  And unlike Basic, Python is powerful enough to comfortably handle byte strings.

Body:
My goal is to fill a LibreOffice calc sheet, and silently send a cell range by email when the user clicks the send-off button (and once more to confirm).

So there is three part to this.

A push button with a request to confirm. (Easy and done.)

Select Cell Range and turn it into rich text format (Haven't yet found)

Send rich text email from within the sheet. (Will tackle the "silent" part later)

I tried copying the range to the clipboard with unoService but it seemed over-complicated and full of errors.

Here's what I have:

''''Send by e-mail enriched text

Sub Main
    Dim Doc, Sheet, Range, Rtf, Exec as Object
End Sub

'Confirm it
Sub SendTableApproval
    If MsgBox ("Ready to email?", MB_YESNO + MB_DEFBUTTON2) = IDYES Then
        CopyTable()
    End If
End Sub

'Copy it
Sub CopyTable
    Doc = ThisComponent
    View = Doc.CurrentController
    Frame = View.Frame
    Sheet = Doc.Sheets.getByIndex(0)
    Range = Sheet.getCellrangeByName("a1:f45")
    Exec = createUnoService("com.sun.star.frame.DispatchHelper")

    View.Select(Range)
    Cells = View.getTransferable()
    Exec.executeDispatch(Frame, ".uno:Deselect", "", 0, array())
    'SimpleMailTo(Cells)
End Sub

'Mail it
Sub SimpleMailTo(body)
    Dim launcher as object
    Dim eAddress, eSubject, eBody, aHTMLanchor as string
    launcher = CreateUnoService("com.sun.star.system.SystemShellExecute")
    eAddress = "tu@domo.eg"
    eSubject = "Cotidie agenda futuendane"
    eBody = body
    aHTMLanchor = "mailto:" & eAddress & "?subject=" & eSubject & "&&body=" & eBody
    launcher.execute(aHTMLanchor, "", 0)
End Sub

I still do not know after three days of research over methods, properties, uno.

My question is, simply put, How can I convert a transferable content to HTML/RTF?

Body:
Simply copying and pasting into an email produces the result you are asking for.  The code on the LibreOffice side should look like this.

dispatcher.executeDispatch(document, ".uno:Copy", "", 0, Array())

It sounds like you already tried this, but something didn't work.  Perhaps you could elaborate on what went wrong.

Another approach would be to write the spreadsheet to a temporary HTML or XHTML file.   Then parse the temporary file to grab the part needed for the email.

AFAIK there is no such command to turn a cell range into rich text format with UNO.  To do it that way, you would need to loop through each text range of each cell, read its formatting properties and then generate the HTML yourself.

EDIT:

Good idea about XTransferable.  The following Java code adapted from the DevGuide gets an HTML string and then prints it.  I believe this would be a good solution for your needs.

public void displayHTMLFromClipboard()
{
    try
    {
        Object oClipboard = xMCF.createInstanceWithContext(
            "com.sun.star.datatransfer.clipboard.SystemClipboard", xContext);
        XClipboard xClipboard = (XClipboard)
            UnoRuntime.queryInterface(XClipboard.class, oClipboard);
        XTransferable xTransferable = xClipboard.getContents();
        DataFlavor[] aDflvArr = xTransferable.getTransferDataFlavors();
        System.out.println("Available clipboard formats:");
        DataFlavor aChosenFlv = null;
        for (int i=0;i<aDflvArr.length;i++)
        {
            System.out.println(
                "MimeType: " + aDflvArr[i].MimeType +
                " HumanPresentableName: " + aDflvArr[i].HumanPresentableName );
            if (aDflvArr[i].MimeType.equals("text/html"))
            {
                aChosenFlv = aDflvArr[i];
            }
        }
        System.out.println("");
        try
        {
            if (aChosenFlv != null)
            {
                System.out.println("HTML text on the clipboard...");
                Object aData = xTransferable.getTransferData(aChosenFlv);
                String s = new String((byte[])aData, Charset.forName("ISO-8859-1"));
                System.out.println(s);
            }
        }
        catch (UnsupportedFlavorException exc)
        {
            exc.printStackTrace();
        }
    }
    catch(com.sun.star.uno.Exception exc)
    {
        exc.printStackTrace();
    }
}

If you plan to use Basic, it might be a good idea to do some research into the proper way to convert bytes.  The code I have below seems to work but is probably unreliable and unsafe, and will not work for many languages.  A few of my initial attempts crashed before this finally worked.

Sub DisplayClipboardData
    oClipboard = createUnoService("com.sun.star.datatransfer.clipboard.SystemClipboard")
    xTransferable = oClipboard.getContents()
    aDflvArr = xTransferable.getTransferDataFlavors()
    For i = LBound(aDflvArr) To UBound(aDflvArr)
        If aDflvArr(i).MimeType = "text/html" Then
            Dim aData() As Byte
            aData = xTransferable.getTransferData(aDflvArr(i))
            Dim s As String
            For j = LBound(aData) to UBound(aData)
                s = s & Chr(aData(j))  'XXX: Probably a bad way to do this!
            Next j
            Print(s)
        End If
    Next
End Sub

One more suggestion: Python might be a better language choice here.  In many ways, using Python with LibreOffice is easier than Java.  And unlike Basic, Python is powerful enough to comfortably handle byte strings.


问:
Container migration in Docker
I am searching for a simple tutorial to test container migration between two VMs. I have seen some videos but they do not show exactly how they did that or didn't actually found any good tutorial by myself.
I am new to docker so I just wanted to test how this migration works. So, it will be very nice you can give me some tutorials/links that clearly explains how to do it.
Your help will be really appreciated, thanks :) </p>

答:
You can export a containet by running

```<code>docker export <container-name> -o container.tar
</code>```

You then can copy the tar into a different VM and import it by running

```<code>docker import container.tar <image-name>
</code>```

WARNINIG:

The export does not export mounted volumes as part of the tarball. Check the documentation for more info.

If you have a volume and you want to migrate it to the new VM, check How to port data-only volumes from one host to another?

Title: Container migration in Docker

Body:
You can export a containet by running

docker export <container-name> -o container.tar

You then can copy the tar into a different VM and import it by running

docker import container.tar <image-name>

WARNINIG:

The export does not export mounted volumes as part of the tarball. Check the documentation for more info.

If you have a volume and you want to migrate it to the new VM, check How to port data-only volumes from one host to another?


问:
Python 3 Please Insert disk into drive
I get this error when running a python 3 script

Sample error box

(edit) sorry forgot to mention this is on windows 7 if that wasn't clear. Selenium chrome web driver. let me know if you want to know anything else.

I think it would be impractical to post the whole project. I will provide a link to the git repository here.

Please excuse the amateur coding I'm working on refining my conventions.

This is a tool for scraping various sources, in this case website, for data. Specifically this is happening to the Kawasaki scrape. It happens once or twice in the course of scrapping aprox. 4500 parts. Normally i could handle this error well enough but I don't know how to handle the actual window it is currently requiring a physical click so if I leave this to run overnight it gets stuck there and wont finish.

the flow of the program in github is that i run the part scraper file that is in the main directory that instantiates user interface. then the file run_all then distributor_kawasaki specifically in this case which inherits from distributor.

(edit)Well ariens did it too now.

I have scoured all the solution all over stack exchange and the internet and general and none of the solutions have worked.

(edit)I have tried uninstall just about everything i can from device manager to see if its a windows problem. I have reinstalled libraries. i have made sure everything is up to date.

The really strange part is that it only happens when i run the script file as normal, but not in pycharm. pycharm IDE has no problems with this at all.

for solutions I would obviously prefer to fix this issue.

If this question is lacking in some way please let me know before flagging it and i will fix/add anything that is needed. like i said I'm pretty new and am working on it I swear.

small aside if anyone has any pointers for me in general after looking at the code i would love to take any constructive criticism seperatly.

答: In case anyone else comes upon this problem as well, I figured out that the computer was running out of memory. I assume because of the browsing history. I don't know the best fix for this, but mine was to close, reopen the browser and then continue every so often to clear the memory. I am still playing around with the magical number for me but it will depend on the computers available memory.</p>

Title: Python 3 Please Insert disk into drive


答:
You need to save the text from the input in the state (using setState), not in the tweets array. Then you can render it getting the text from the state.</p>

```<code>class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  state = {
    tweetsText :{}
  }

  handleTextChange = (event, tweetId) => {
     const tweetsTextCopy = Object.assign({}, this.state.tweetsText)
    tweetsTextCopy[tweetId] = event.target.value
    this.setState({tweetsText: tweetsTextCopy})
  }

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => this.handleTextChange(e, tweet.id)} />
            <a href={`https://twitter.com/intent/tweet?text=${this.state.tweetsText[tweet.id]}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}
</code>```

Title: In React, how to bind an input's value when rendering a list of inputs?

Body:
You need to save the text from the input in the state (using setState), not in the tweets array. Then you can render it getting the text from the state.

class App extends React.Component {
  tweets = [
    { id: 1, link: 'example.com' },
    { id: 2, link: 'example2.com' }
  ];

  state = {
    tweetsText :{}
  }

  handleTextChange = (event, tweetId) => {
     const tweetsTextCopy = Object.assign({}, this.state.tweetsText)
    tweetsTextCopy[tweetId] = event.target.value
    this.setState({tweetsText: tweetsTextCopy})
  }

  render() {
    return (
      <div>
        {this.tweets.map(tweet =>
          <div key={tweet.id}>
            <input type="text" placeholder="text" onChange={e => this.handleTextChange(e, tweet.id)} />
            <a href={`https://twitter.com/intent/tweet?text=${this.state.tweetsText[tweet.id]}`}>Tweet</a>
          </div>
        )}
      </div>
    );
  }
}