问:
DDD - How does the domain receive client data
I'm planning to refactor a legacy .NET project that I'm maintaining, there are mainly 4 projects involved:

My.Company.Web - The presentation layer. ASP.NET MVC.

My.Company.Service - The service layer, defines service interfaces and contains command handlers. Invoked by the web layer.

My.Company.DTO - The assembly that contains DTO classes for data transfer between the domain and web layers.

My.Company.Domain - The domain layer.

My.Company.Data - The persistence layer.

When user submits a form to update a person's details, the process looks somewhat like this:

Using the submitted data, controller constructs a PersonDetailsDTO which consists of multiple simple fields to hold FirstName, LastName, Age and etc, and a complex type object called AddressDTO that holds address details: var dto = new PersonDetails(...);

Controller calls the service layer with the DTO:

```<code>_personService.UpdateDetails(dto);
</code>```

In the service:

```<code>public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    person.Update(dto);
    _personRepository.Update(person);
}
</code>```

In the Person domain:

```<code>public class Person : AggregateRoot
{
    private string FirstName;
    .... // other fields
    private Address Address;

    public void Update(PersonDetailsDTO dto)
    {
        FirstName = dto.FirstName;
        .... // other fields
        Address.Update(dto.AddressDTO); // update the value object - address
    }
}
</code>```

As you can see here, the Person domain references the PersonDetailsDTO. This feels wrong to me as DTOs are means to present the data in the domain to its clients while not exposing the domain itself. and the domain should not be concerned with how it's presented to the clients.

Also IMO the DTOs should live in the My.Company.Service project as it's the service that defines the operation/data transfer contracts.

But then how would the service pass the details on to the domain? Would it have to be a loooong list of parameters: person.Update(firstName, lastName, age, gender, street1, street2, state, postcode...). This certainly looks wrong to me.

Or does the domain have to define yet another set of it's own "DTOs" to receive client data?

I have gone through a LOT of tutorials and SO posts and no one seem to share my concern, so I'm starting to think I'm missing something here, could someone point me to the right direction?

答:
You could do as follows.
You already have a Value Object named Address similarly you could have another Value Object as PersonalDetails which will contain firstName, lastName, age, gender etc. and the Person entity will have two behaviors like updatePersonalDetails() and updateAddress(). Your application service will look like below.

```<code>public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    Address address = new Address(dto.getStreet1, dto.getStreet2,...);
    PersonalDetails details = new PersonalDetails(dto.getFirstName,dto.getLastName(),...);
    person.updatePersonalDetails(details);
    person.updateAddress(address);
   _personRepository.save(person);
}
</code>```

Body:
I'm planning to refactor a legacy .NET project that I'm maintaining, there are mainly 4 projects involved:

My.Company.Web - The presentation layer. ASP.NET MVC.

My.Company.Service - The service layer, defines service interfaces and contains command handlers. Invoked by the web layer.

My.Company.DTO - The assembly that contains DTO classes for data transfer between the domain and web layers.

My.Company.Domain - The domain layer.

My.Company.Data - The persistence layer.

When user submits a form to update a person's details, the process looks somewhat like this:

Using the submitted data, controller constructs a PersonDetailsDTO which consists of multiple simple fields to hold FirstName, LastName, Age and etc, and a complex type object called AddressDTO that holds address details: var dto = new PersonDetails(...);

Controller calls the service layer with the DTO:

_personService.UpdateDetails(dto);

In the service:

public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    person.Update(dto);
    _personRepository.Update(person);
}

In the Person domain:

public class Person : AggregateRoot
{
    private string FirstName;
    .... // other fields
    private Address Address;

    public void Update(PersonDetailsDTO dto)
    {
        FirstName = dto.FirstName;
        .... // other fields
        Address.Update(dto.AddressDTO); // update the value object - address
    }
}

As you can see here, the Person domain references the PersonDetailsDTO. This feels wrong to me as DTOs are means to present the data in the domain to its clients while not exposing the domain itself. and the domain should not be concerned with how it's presented to the clients.

Also IMO the DTOs should live in the My.Company.Service project as it's the service that defines the operation/data transfer contracts.

But then how would the service pass the details on to the domain? Would it have to be a loooong list of parameters: person.Update(firstName, lastName, age, gender, street1, street2, state, postcode...). This certainly looks wrong to me.

Or does the domain have to define yet another set of it's own "DTOs" to receive client data?

I have gone through a LOT of tutorials and SO posts and no one seem to share my concern, so I'm starting to think I'm missing something here, could someone point me to the right direction?

Body:
You could do as follows.
You already have a Value Object named Address similarly you could have another Value Object as PersonalDetails which will contain firstName, lastName, age, gender etc. and the Person entity will have two behaviors like updatePersonalDetails() and updateAddress(). Your application service will look like below.

public void UpdatePerson(PersonDetailsDTO dto)
{
    var person = _personRepository.GetById(dto.PersonId);
    Address address = new Address(dto.getStreet1, dto.getStreet2,...);
    PersonalDetails details = new PersonalDetails(dto.getFirstName,dto.getLastName(),...);
    person.updatePersonalDetails(details);
    person.updateAddress(address);
   _personRepository.save(person);
}


来源: stackexchange

问:
Compilation error when using isLeaf() method
I'm trying to move around nodes and append them either a 0 or a 1 depending on their position, as I'm doing a Huffman compression test.

However, when trying to use the method isLeaf() which is from javax.swing.tree.

Here's the segment of the code that's giving me issues.

```<code>private static void createTestMap(
final Node node,
final String string,
final Map<Character, String> map)
{
    if(!node.isLeaf())
    {
       createTestMap(nodo.leftChild, string + "0", map);
       createTestMap(nodo.rightChild, string + '1', map);
    }
    else
    {
        map.put(node.test, string);
    }
}
</code>```

With the node code on a different class.
On this one it's giving me an error:

```<code>cannot find symbol - method isLeaf()
</code>```

I'm extremely new to Java and coding in general so I'm not quite sure what's missing, as I've seen this method being used in several programs related to Huffman compression through nodes.

答:
The isLeaf() method is defined for a sub-class of TreeNode, specifically DefaultMutableTreeNode.

I've seen this method being used in several programs

Always consult the Java Docs to understand random snippets of code from the internet.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to move around nodes and append them either a 0 or a 1 depending on their position, as I'm doing a Huffman compression test.

However, when trying to use the method isLeaf() which is from javax.swing.tree.

Here's the segment of the code that's giving me issues.

private static void createTestMap(
final Node node,
final String string,
final Map<Character, String> map)
{
    if(!node.isLeaf())
    {
       createTestMap(nodo.leftChild, string + "0", map);
       createTestMap(nodo.rightChild, string + '1', map);
    }
    else
    {
        map.put(node.test, string);
    }
}

With the node code on a different class.
On this one it's giving me an error:

cannot find symbol - method isLeaf()

I'm extremely new to Java and coding in general so I'm not quite sure what's missing, as I've seen this method being used in several programs related to Huffman compression through nodes.


问:
Android Studio doesn't show import suggestion

After trying adding the GSON library with "compile 'com.google...' ",I get a situation that when I try to import modules the IDE suggest me nothing except static and *. So I have to type everything. How can I fix it? I created new projects and still get this problem.

答:
We're in 21 century and using modern IDE Android Studio. Why do you want to import packages manually just like we import when writing code in simple Notepad or any other text editor?

Just type the name of class which you want to use in your code. And the IDE is smart enough to show the suggestions which relates to your typed keyword.

I get a situation that when i try to import modules the IDE suggest me nothing except static and *.

Yes, it's indeed. Here is my screenshot

How can I fix it?

Very simple. Just type class name whatever you want and select it from suggestions. Android Studio automatically imports it.

For example (as per your requirement) you want to import @SerializedName() annotation. Type @Ser and hit Ctrl + Space and see the magic.

Now the Android Studio showing me the suggestions which matches with keyword Ser and I'll select SerializedName (com.google.gson.annotations.SerializedName). That's it.

Hope it'll be helpful.


问:
Android app Keystore password reset
How to reset Keystore password for android. I can't update application on play store.
How to resolve this problem?
When I tried to update the application with the new key then play store rejected it.
I have the old Keystore file but the password is not accepting.

答:
Faced the same problem

You can create a new keystore, but the Android Market wont allow you
  to upload the APK as an update - worse still, if you try uploading the
  apk as a new app it will not allow it either as it knows there is a
  'different' version of the same apk already in the market even if you
  delete your previous version from the play store.

Generally, the only advise that exists on keystores: "always back it up!"

Or you may try this.

Title: Android app Keystore password reset


问:
How to delete/update nested data in bigquery
Is there a way to delete/update nested field in bigquery?

Let's say I have this data

```<code>wives.age   wives.name  name
21             angel    adam
20             kale
21           victoria   rossi
20           jessica
</code>```

or in json:

```<code>{"name":"adam","wives":[{"name":"angel","age":21},{"name":"kale","age":20}]}
{"name":"rossi","wives":[{"name":"victoria","age":21},{"name":"jessica","age":20}]}
</code>```

As you can see from the data above.
Adam has 2 wives, named angel and kale. How to:

Delete kale record.

Update jessica to dessica

I tried to google this, but can't find it. I also tried to unnest, etc but no luck.

The reason why we want to do this is because we insert the array to the wrong records and want to remove/update array data with some condition.

答:
Below is for BigQuery Standard SQL

#standardSQL
WITH updates AS (
  SELECT 'rossi' name, 'jessica' oldname, 'dessica' newname UNION ALL
  SELECT 'rossi' name, 'victoria' oldname, 'polly' newname UNION ALL
  SELECT 'adam' name, 'angel' oldname, 'jen' newname
), divorces AS (
  SELECT 'adam' name, 'kale' wifename UNION ALL
  SELECT 'adam' name, 'milly' wifename UNION ALL
  SELECT 'rossi' name, 'linda' wifename
)
SELECT t.name,
  ARRAY(
    SELECT AS STRUCT
      age,
      CASE
        WHEN NOT oldname IS NULL THEN newname
        ELSE name
      END name
    FROM UNNEST(wives)
    LEFT JOIN UNNEST(updates) ON t.name = u.name AND name = oldname
    LEFT JOIN UNNEST(divorces) AS wifename ON t.name = d.name AND name = wifename
    WHERE wifename IS NULL
  ) waves
FROM `project.dataset.table` t
LEFT JOIN (
  SELECT name, ARRAY_AGG(STRUCT(oldname, newname)) updates
  FROM updates GROUP BY name
  ) u ON t.name = u.name
LEFT JOIN (
  SELECT name, ARRAY_AGG(wifename) divorces
  FROM divorces GROUP BY name
  ) d ON t.name = d.name
```

<p>You can test / play with above using dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'adam' name, [STRUCT<age INT64, name STRING>(21, 'angel'), (20, 'kale'), (22, 'milly')] wives UNION ALL
  SELECT 'rossi', [STRUCT<age INT64, name STRING>(21, 'victoria'), (20, 'jessica'), (23, 'linda')]
), updates AS (
  SELECT 'rossi' name, 'jessica' oldname, 'dessica' newname UNION ALL
  SELECT 'rossi' name, 'victoria' oldname, 'polly' newname UNION ALL
  SELECT 'adam' name, 'angel' oldname, 'jen' newname
), divorces AS (
  SELECT 'adam' name, 'kale' wifename UNION ALL
  SELECT 'adam' name, 'milly' wifename UNION ALL
  SELECT 'rossi' name, 'linda' wifename
)
SELECT t.name,
  ARRAY(
    SELECT AS STRUCT
      age,
      CASE
        WHEN NOT oldname IS NULL THEN newname
        ELSE name
      END name
    FROM UNNEST(wives)
    LEFT JOIN UNNEST(updates) ON t.name = u.name AND name = oldname
    LEFT JOIN UNNEST(divorces) AS wifename ON t.name = d.name AND name = wifename
    WHERE wifename IS NULL
  ) waves
FROM `project.dataset.table` t
LEFT JOIN (
  SELECT name, ARRAY_AGG(STRUCT(oldname, newname)) updates
  FROM updates GROUP BY name
  ) u ON t.name = u.name
LEFT JOIN (
  SELECT name, ARRAY_AGG(wifename) divorces
  FROM divorces GROUP BY name
  ) d ON t.name = d.name
</code>```

result is as expected

name    waves.age   waves.name
adam    21          jen
rossi   21          polly
        20          dessica
```

I hope you will be able to apply above to your real case :o)

Body:
Is there a way to delete/update nested field in bigquery?

Let's say I have this data

wives.age   wives.name  name
21             angel    adam
20             kale
21           victoria   rossi
20           jessica

or in json:

{"name":"adam","wives":[{"name":"angel","age":21},{"name":"kale","age":20}]}
{"name":"rossi","wives":[{"name":"victoria","age":21},{"name":"jessica","age":20}]}

As you can see from the data above.
Adam has 2 wives, named angel and kale. How to:

Delete kale record.

Update jessica to dessica

I tried to google this, but can't find it. I also tried to unnest, etc but no luck.

The reason why we want to do this is because we insert the array to the wrong records and want to remove/update array data with some condition.

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH updates AS (
  SELECT 'rossi' name, 'jessica' oldname, 'dessica' newname UNION ALL
  SELECT 'rossi' name, 'victoria' oldname, 'polly' newname UNION ALL
  SELECT 'adam' name, 'angel' oldname, 'jen' newname
), divorces AS (
  SELECT 'adam' name, 'kale' wifename UNION ALL
  SELECT 'adam' name, 'milly' wifename UNION ALL
  SELECT 'rossi' name, 'linda' wifename
)
SELECT t.name,
  ARRAY(
    SELECT AS STRUCT
      age,
      CASE
        WHEN NOT oldname IS NULL THEN newname
        ELSE name
      END name
    FROM UNNEST(wives)
    LEFT JOIN UNNEST(updates) ON t.name = u.name AND name = oldname
    LEFT JOIN UNNEST(divorces) AS wifename ON t.name = d.name AND name = wifename
    WHERE wifename IS NULL
  ) waves
FROM `project.dataset.table` t
LEFT JOIN (
  SELECT name, ARRAY_AGG(STRUCT(oldname, newname)) updates
  FROM updates GROUP BY name
  ) u ON t.name = u.name
LEFT JOIN (
  SELECT name, ARRAY_AGG(wifename) divorces
  FROM divorces GROUP BY name
  ) d ON t.name = d.name

You can test / play with above using dummy data as below

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'adam' name, [STRUCT<age INT64, name STRING>(21, 'angel'), (20, 'kale'), (22, 'milly')] wives UNION ALL
  SELECT 'rossi', [STRUCT<age INT64, name STRING>(21, 'victoria'), (20, 'jessica'), (23, 'linda')]
), updates AS (
  SELECT 'rossi' name, 'jessica' oldname, 'dessica' newname UNION ALL
  SELECT 'rossi' name, 'victoria' oldname, 'polly' newname UNION ALL
  SELECT 'adam' name, 'angel' oldname, 'jen' newname
), divorces AS (
  SELECT 'adam' name, 'kale' wifename UNION ALL
  SELECT 'adam' name, 'milly' wifename UNION ALL
  SELECT 'rossi' name, 'linda' wifename
)
SELECT t.name,
  ARRAY(
    SELECT AS STRUCT
      age,
      CASE
        WHEN NOT oldname IS NULL THEN newname
        ELSE name
      END name
    FROM UNNEST(wives)
    LEFT JOIN UNNEST(updates) ON t.name = u.name AND name = oldname
    LEFT JOIN UNNEST(divorces) AS wifename ON t.name = d.name AND name = wifename
    WHERE wifename IS NULL
  ) waves
FROM `project.dataset.table` t
LEFT JOIN (
  SELECT name, ARRAY_AGG(STRUCT(oldname, newname)) updates
  FROM updates GROUP BY name
  ) u ON t.name = u.name
LEFT JOIN (
  SELECT name, ARRAY_AGG(wifename) divorces
  FROM divorces GROUP BY name
  ) d ON t.name = d.name

result is as expected

name    waves.age   waves.name
adam    21          jen
rossi   21          polly
        20          dessica

I hope you will be able to apply above to your real case :o)


问:
How to convert XML to JSON in node.js without having first two elements from xml file?
I would like to know I can I parse XML to JSON without having the two first elements from the first xml conversion, but rather a result like the second convertion. xml2js gives me the first conversion.

```<code> <?xml version="1.0"?>
     <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
    </catalog>
</code>```

When I convert it with xml2json, I get this output :

```<code>`{
  "catalog": {
    "book": [
      {
        "-id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications
      with XML."
      },
      {
        "-id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world."
      }
    ]
  }
}`
</code>```

But i would want this output:

```<code>`[
   {
      "@id": "bk101",
      "author": "Gambardella, Matthew",
      "title": "XML Developer's Guide",
      "genre": "Computer",
      "price": "44.95",
      "publish_date": "2000-10-01",
      "description": "An in-depth look at creating applications \n      with XML."
   },
   {
      "@id": "bk102",
      "author": "Ralls, Kim",
      "title": "Midnight Rain",
      "genre": "Fantasy",
      "price": "5.95",
      "publish_date": "2000-12-16",
      "description": "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."
   }
]`
</code>```

The reason is I need this to insert in my mongodb, but the first conversion only puts all the json as one entry in my database. Also, I have a csv insertion (that I also converted in JSON) that matches the second format and was inserted correctly in the database. Is there a way to get the 2nd format instead of the first one?

答:
You can always convert your XML to JS object and do manipulations with it, removing unnecessary data.

Example

```<code>const obj = xml2json.toJson(xml, { object: true });
const books = obj.catalog.book;
// here you have an array of JS objects stored in your variable books
// and you can perform operations

// just an example for mongo insertion
const collection = db.collection('books');
collection.insertMany(books).then(function () {
    console.log('books inserted')
})
</code>```

Full set of options for parser can be found here

ContentLicense: CC BY-SA 4.0

Body:
I would like to know I can I parse XML to JSON without having the two first elements from the first xml conversion, but rather a result like the second convertion. xml2js gives me the first conversion.

 <?xml version="1.0"?>
     <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
    </catalog>

When I convert it with xml2json, I get this output :

`{
  "catalog": {
    "book": [
      {
        "-id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications
      with XML."
      },
      {
        "-id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world."
      }
    ]
  }
}`

But i would want this output:

`[
   {
      "@id": "bk101",
      "author": "Gambardella, Matthew",
      "title": "XML Developer's Guide",
      "genre": "Computer",
      "price": "44.95",
      "publish_date": "2000-10-01",
      "description": "An in-depth look at creating applications \n      with XML."
   },
   {
      "@id": "bk102",
      "author": "Ralls, Kim",
      "title": "Midnight Rain",
      "genre": "Fantasy",
      "price": "5.95",
      "publish_date": "2000-12-16",
      "description": "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."
   }
]`

The reason is I need this to insert in my mongodb, but the first conversion only puts all the json as one entry in my database. Also, I have a csv insertion (that I also converted in JSON) that matches the second format and was inserted correctly in the database. Is there a way to get the 2nd format instead of the first one?

Body:
You can always convert your XML to JS object and do manipulations with it, removing unnecessary data.

Example

const obj = xml2json.toJson(xml, { object: true });
const books = obj.catalog.book;
// here you have an array of JS objects stored in your variable books
// and you can perform operations

// just an example for mongo insertion
const collection = db.collection('books');
collection.insertMany(books).then(function () {
    console.log('books inserted')
})

Full set of options for parser can be found here


问:
Open-source Java-based framework that has many of the common features built in out-of-the-box?
I am looking for something like Drupal in Java -- not Drupal as a CMS but rather as an application programming framework.

For example I would like to get out the the box:

A Login screen

The ability to define new roles

The ability to tie permissions (capabilities) to roles

The ability to assign roles to specific users (and revoke roles)

The ability to self-service passwords (reset ones own password)

An ability to generate a CRUD app

A menu system (that allows you to define menus)

My understanding is that Ruby-on-Rails provides this type of stuff.

Thanks.

答:
Have a look at Liferay.

It has all you mentioned and a powerful built-in CMS, user management, lots of out-of-the box "applications" (portlets) to add to your pages, lots of themes to choose from, menus and all.

Basically, you can build a complete dynamic site with all the basic functionalities without writing one line of Java code (or any kind of code).

ContentLicense: CC BY-SA 2.5


答:
The only two Node classes in the JDK are javax.xml.soap.Node and org.w3c.dom.Node.

You should be using javax.swing.tree.TreeNode or indeed javax.swing.tree.DefaultMutableTreeNode.

Title: Compilation error when using isLeaf() method


问:
multiple dynamically created buttons with same name using ajax
I'm trying to implement a comment section and after button-press I want to update the comment section with ajax so the page doesn't have to refresh...

In this comment section I have 1 textarea + 1 button + a couple of hidden fields for every comment so users can answer specific comments...

so if there are 50 comments there are also 50 answer-fields, 1 for each...

And every thing works except for 1 thing...

- either I name all id's of the buttons and fields the same name (ie. id="sendAnswer" and id="answer", id="userID", ...) and then only the first one works...

-or I dynamically name them all (ie. id="sendAnswer(echo $i) ) thereby naming them all id="sendAnswer0", "sendAnswer1", "sendAnswer2", ... and then I do that for the textarea and hidden fields too (ie. id="answer(echo $i), id="userID(echo $i), ...)

And that works great too... except for now I have to make a jQuery-script for each... and since they are dynamically created that's difficult - as how many there are changes as more comments comes in...

Code for approach 1: naming them all the same...

```<code>$(document).ready(function(){
    "use strict";
    $("#sendAnswer").click(function(){
        var comment = $("#comment").val();
        var userID = $("#userID").val();
        var randomStringVideo = $("#randomStringVideo").val();
        var commentID = $("#commentID").val();
        $.ajax({
            type: "POST",
            url:'../scripts/comment.php',
            data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
            success:function(){
                $("#commentDiv").load(location.href + " #commentDiv>*", "");
                $("#commentsDiv").load(location.href + " #commentsDiv>*", "");
                $("#comment").val('');
            }
        });
    });
});
</code>```

And as I said... this works fine for the first one and the rest are duds...

Code for approach 2: I dynamically name all values...

```<code>$(document).ready(function(){
    "use strict";
    $("#sendAnswer"+$(this).val()).click(function(){ // this +$(this).val() doesn't work, only if I put #sendAnswer3 - then the 4th works and the rest are duds etc.
        var comment = $("#comment"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var userID = $("#userID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var randomStringVideo = $("#randomStringVideo"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var commentID = $("#commentID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        $.ajax({
            type: "POST",
            url:'../scripts/comment.php',
            data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
            success:function(){
                $("#commentDiv").load(location.href + " #commentDiv>*", "");
                $("#commentsDiv").load(location.href + " #commentsDiv>*", "");
                $("#comment"+$(this).val()).val(''); // this +$(this).val() doesn't work, only if I put #comment3 (matching the #sendAnswer)- then the 4th works and the rest are duds etc.
            }
        });
    });
});
</code>```

With this I would have to name every single possible #sendAnswer-number + #comment-number for it to work... and with an infinite set of numbers to choose from 0-(infinite) - that's not viable...

If of any interest...

Php that dynamically creates the buttons and fields in question

```<code>.
.
.
<?php if ($_SESSION[numberOfComments] != 0) {
    for ($i=0; $i<$_SESSION[numberOfComments]; $i++) ?> // run through all comments that aren't answers to other comments
        // show comment info
        <div class="media">// answer comment box starts here
            <img class="mr-3 rounded" src="<?php $file = USER . $_SESSION['randomString'] . THUMBNAIL; if ( file_exists ( $file ) ) {echo $file; } else { echo USER . "default" . THUMBNAIL; } ?>" width="50" height="50" data-toggle="tooltip" data-placement="left" title="<?php echo $_SESSION['username']; ?>">
            <div class="media-body">
                <textarea class="form-control" rows="2" type="text" name="comment<?php echo $i; ?>" id="comment<?php echo $i; ?>" value="" placeholder="Great video!"></textarea>
                <input type="hidden" name="userID<?php echo $i; ?>" id="userID<?php echo $i; ?>" value="<?php if ( isset ( $_SESSION['id'] ) ) { echo $_SESSION['id']; } ?>">
                <input type="hidden" name="randomStringVideo<?php echo $i; ?>" id="randomStringVideo<?php echo $i; ?>" value="<?php echo $_GET['v']; ?>">
                <input type="hidden" name="commentID<?php echo $i; ?>" id="commentID<?php echo $i; ?>" value="<?php echo $_SESSION['commentID_getComment']; ?>">
                <button type="button" class="btn btn-primary float-right margin-top-5" id="sendComment<?php echo $i; ?>" value="<?php echo $i; ?>">
                    Answer
                </button>
            </div>
        </div> // answer comment box ends here
        <?php if ($_SESSION[numberOfAnswers][$i] != 0) {
            for ($j=0; $j<$_SESSION[numberOfAnswers][$i]; $j++) { ?> // run through all answer to this comment
                // show answer info
            <?php }
        }
    }
} ?>
.
.
.
</code>```

答:
Using your current approach, where everything is identified with ids, the  best option would be to use event delegation.  Create just one event handler, on some parent element which exists at the time the page is loaded, which via delegation will handle any of your buttons - existing and future.  Once the handler fires, you can determine which set of elements you are working with, and continue as normal.

Here's an example, using body as the parent, but you can use any element which contains all your present and future buttons/inputs, eg maybe you have a parent
.  This also assumes your button inputs are actual button elements, you'll have to adjust if that's not the case:

```<code>$(document).ready(function(){
    "use strict";

    // A single event handler on body, which handles any child button
    $("body").on('click', 'button', function(event) {

        // $(this) will be the button that was clicked.  We can find its id,
        // and if your buttons all have ids like sendAnswer1, sendAnswer2,
        // sendAnswerX, we can find the X
        var id = $(this).attr('id').replace('sendAnswer', '');

        // Now we can use the X to access each of this button's matching
        // inputs etc. Again this assumes your other elements have ids like
        // commentX.
        var comment = $("#comment" + id).val(),
            userID = $("#userID" + id).val(),
            // ... etc, rest of your code
</code>```

As well as the article  linked above, the jQuery .on() docs have a good description of event delegation (see "Direct and delegated events").

Update

Another option, which I find neater, is to wrap each comment section in a div (or any identifying element, such that each comment/input/button set is nested inside it), and use only classes for each element.  Again using event delegation, you can find the section which contains the button that was clicked, and therefore identify which input elements you're working with.

For example, your HTML might look like:

```<code><div id="all-comments">
    <div class="comment-section">
        <textarea class="comment" name="whatever"> ... </textarea>
        <button name="button" type="submit">Post!</button>
        <!-- your hidden fields, etc -->
    </div>

    <div class="comment-section">
        ...
    </div>

    <!-- ... etc, many comment sections -->
</div>
</code>```

Now your JS would look something like this:

```<code>$(document).ready(function(){
    "use strict";

    // A single event handler on the parent div, which handles any child button
    $("#all-comments").on('click', 'button', function(event) {

        // $(this) will be the button that was clicked.  We need to find the
        // .comment-section containing that button
        var div = $(this).closest('div.comment-section');

        // Now we can find all elements inside that particular section
        var comment = $(".comment", div).val(),
            userID = $(".userID", div).val(),
            // ... etc, rest of your code
</code>```

Body:
I'm trying to implement a comment section and after button-press I want to update the comment section with ajax so the page doesn't have to refresh...

In this comment section I have 1 textarea + 1 button + a couple of hidden fields for every comment so users can answer specific comments...

so if there are 50 comments there are also 50 answer-fields, 1 for each...

And every thing works except for 1 thing...

- either I name all id's of the buttons and fields the same name (ie. id="sendAnswer" and id="answer", id="userID", ...) and then only the first one works...

-or I dynamically name them all (ie. id="sendAnswer(echo $i) ) thereby naming them all id="sendAnswer0", "sendAnswer1", "sendAnswer2", ... and then I do that for the textarea and hidden fields too (ie. id="answer(echo $i), id="userID(echo $i), ...)

And that works great too... except for now I have to make a jQuery-script for each... and since they are dynamically created that's difficult - as how many there are changes as more comments comes in...

Code for approach 1: naming them all the same...

$(document).ready(function(){
    "use strict";
    $("#sendAnswer").click(function(){
        var comment = $("#comment").val();
        var userID = $("#userID").val();
        var randomStringVideo = $("#randomStringVideo").val();
        var commentID = $("#commentID").val();
        $.ajax({
            type: "POST",
            url:'../scripts/comment.php',
            data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
            success:function(){
                $("#commentDiv").load(location.href + " #commentDiv>*", "");
                $("#commentsDiv").load(location.href + " #commentsDiv>*", "");
                $("#comment").val('');
            }
        });
    });
});

And as I said... this works fine for the first one and the rest are duds...

Code for approach 2: I dynamically name all values...

$(document).ready(function(){
    "use strict";
    $("#sendAnswer"+$(this).val()).click(function(){ // this +$(this).val() doesn't work, only if I put #sendAnswer3 - then the 4th works and the rest are duds etc.
        var comment = $("#comment"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var userID = $("#userID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var randomStringVideo = $("#randomStringVideo"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        var commentID = $("#commentID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
        $.ajax({
            type: "POST",
            url:'../scripts/comment.php',
            data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
            success:function(){
                $("#commentDiv").load(location.href + " #commentDiv>*", "");
                $("#commentsDiv").load(location.href + " #commentsDiv>*", "");
                $("#comment"+$(this).val()).val(''); // this +$(this).val() doesn't work, only if I put #comment3 (matching the #sendAnswer)- then the 4th works and the rest are duds etc.
            }
        });
    });
});

With this I would have to name every single possible #sendAnswer-number + #comment-number for it to work... and with an infinite set of numbers to choose from 0-(infinite) - that's not viable...

If of any interest...

Php that dynamically creates the buttons and fields in question

.
.
.
<?php if ($_SESSION[numberOfComments] != 0) {
    for ($i=0; $i<$_SESSION[numberOfComments]; $i++) ?> // run through all comments that aren't answers to other comments
        // show comment info

// answer comment box starts here
            <img class="mr-3 rounded" src="<?php $file = USER . $_SESSION['randomString'] . THUMBNAIL; if ( file_exists ( $file ) ) {echo $file; } else { echo USER . "default" . THUMBNAIL; } ?>" width="50" height="50" data-toggle="tooltip" data-placement="left" title="<?php echo $_SESSION['username']; ?>">

                <textarea class="form-control" rows="2" type="text" name="comment<?php echo $i; ?>" id="comment<?php echo $i; ?>" value="" placeholder="Great video!"></textarea>
                <input type="hidden" name="userID<?php echo $i; ?>" id="userID<?php echo $i; ?>" value="<?php if ( isset ( $_SESSION['id'] ) ) { echo $_SESSION['id']; } ?>">
                <input type="hidden" name="randomStringVideo<?php echo $i; ?>" id="randomStringVideo<?php echo $i; ?>" value="<?php echo $_GET['v']; ?>">
                <input type="hidden" name="commentID<?php echo $i; ?>" id="commentID<?php echo $i; ?>" value="<?php echo $_SESSION['commentID_getComment']; ?>">
                <button type="button" class="btn btn-primary float-right margin-top-5" id="sendComment<?php echo $i; ?>" value="<?php echo $i; ?>">
                    Answer
                </button>

 // answer comment box ends here
        <?php if ($_SESSION[numberOfAnswers][$i] != 0) {
            for ($j=0; $j<$_SESSION[numberOfAnswers][$i]; $j++) { ?> // run through all answer to this comment
                // show answer info
            <?php }
        }
    }
} ?>
.
.
.

Body:
Using your current approach, where everything is identified with ids, the  best option would be to use event delegation.  Create just one event handler, on some parent element which exists at the time the page is loaded, which via delegation will handle any of your buttons - existing and future.  Once the handler fires, you can determine which set of elements you are working with, and continue as normal.

Here's an example, using body as the parent, but you can use any element which contains all your present and future buttons/inputs, eg maybe you have a parent <div id="something">.  This also assumes your button inputs are actual button elements, you'll have to adjust if that's not the case:

$(document).ready(function(){
    "use strict";

    // A single event handler on body, which handles any child button
    $("body").on('click', 'button', function(event) {

        // $(this) will be the button that was clicked.  We can find its id,
        // and if your buttons all have ids like sendAnswer1, sendAnswer2,
        // sendAnswerX, we can find the X
        var id = $(this).attr('id').replace('sendAnswer', '');

        // Now we can use the X to access each of this button's matching
        // inputs etc. Again this assumes your other elements have ids like
        // commentX.
        var comment = $("#comment" + id).val(),
            userID = $("#userID" + id).val(),
            // ... etc, rest of your code

As well as the article  linked above, the jQuery .on() docs have a good description of event delegation (see "Direct and delegated events").

Update

Another option, which I find neater, is to wrap each comment section in a div (or any identifying element, such that each comment/input/button set is nested inside it), and use only classes for each element.  Again using event delegation, you can find the section which contains the button that was clicked, and therefore identify which input elements you're working with.

For example, your HTML might look like:

<div id="all-comments">
    <div class="comment-section">
        <textarea class="comment" name="whatever"> ... </textarea>
        <button name="button" type="submit">Post!</button>
        <!-- your hidden fields, etc -->
    </div>

    <div class="comment-section">
        ...
    </div>

    <!-- ... etc, many comment sections -->
</div>

Now your JS would look something like this:

$(document).ready(function(){
    "use strict";

    // A single event handler on the parent div, which handles any child button
    $("#all-comments").on('click', 'button', function(event) {

        // $(this) will be the button that was clicked.  We need to find the
        // .comment-section containing that button
        var div = $(this).closest('div.comment-section');

        // Now we can find all elements inside that particular section
        var comment = $(".comment", div).val(),
            userID = $(".userID", div).val(),
            // ... etc, rest of your code


问:
what is happening in following javascript function
below i have given a javascript code picture `` can any one help me in this code. what do this code. help me in this  </p>

```<code>function(){
    var _ = function()
        // The arguments object is an array-like object. It has a length property
        // that corresponds to the number of arguments passed into the function
    {
        var r={},a=arguments;
        for(var i=0; i<a.length; i+=2)
            r[a[i]]=a[i+1];
        return r;
    }
}
</code>```

答: The outer function does not make much sense but the inner function named '_' does this essentially _(1,2,3,4) function call will return {1:2,3:4}. Basically, odd arguments are keys and even arguments are values of the returned json object</p>

Body:
below i have given a javascript code picture `` can any one help me in this code. what do this code. help me in this

function(){
    var _ = function()
        // The arguments object is an array-like object. It has a length property
        // that corresponds to the number of arguments passed into the function
    {
        var r={},a=arguments;
        for(var i=0; i<a.length; i+=2)
            r[a[i]]=a[i+1];
        return r;
    }
}


问:
Xcode 8 App installation failed, unknown error occured

The following error occurred when I tried to run a project on my iOS device. Running it on a simulator works fine.

The other weird thing is that I am able to run my other projects on my device, only this particular project that is giving me this error.

I tried all the solutions I'm able to find:

Cleaning the project, deleting derived data

Restarting Xcode, my Mac, and my iOS device

Deselect 'Automatically manage signing' in the testing Target.

I couldn't delete the app from my device and re-install it because it wasn't installed on my device before.

Any help would mean alot to me! I am using Xcode 8.1 with Swift 3.0, running on a iOS 10.1.1 device.

答:
Restart your Xcode & Uninstall your app.

Build & Clean your Project, now it working good.
this works for me

above is not working please Restart your system


问:
Amchart Clicklabel event not working
I m fairly new to Amchart library and facing a problem with clickLabel event of legend.

here is the Javascript code I have tried:

```<code>var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "legend": {
    "horizontalGap": 10,
    "maxColumns": 1,
    "position": "right",
    "useGraphSettings": true,
    "markerSize": 10,
    "listeners": [{
      "event": "clickMarker",
      "method": function(e) {
        document.getElementById('clicked').textContent =
          e.dataItem.title + ' - marker status before toggle: ' + e.dataItem.hidden;
      }
    }]
  },

chart.legend.addListener('clickLabel', function(event) {

document.getElementById('clicked').textContent =
          e.dataItem.title + ' - marker status before toggle: ' + e.dataItem.hidden;

});
</code>```

here is Jsfiddle: http://jsfiddle.net/Shivin15/15k53omf/2/

Thank you for your help!

答:
You'll need to set textClickEnabled to true.

Check the updated example here: http://jsfiddle.net/15k53omf/3/

Title: Amchart Clicklabel event not working

Body:
I m fairly new to Amchart library and facing a problem with clickLabel event of legend.

here is the Javascript code I have tried:

var chart = AmCharts.makeChart("chartdiv", {
  "type": "serial",
  "theme": "light",
  "legend": {
    "horizontalGap": 10,
    "maxColumns": 1,
    "position": "right",
    "useGraphSettings": true,
    "markerSize": 10,
    "listeners": [{
      "event": "clickMarker",
      "method": function(e) {
        document.getElementById('clicked').textContent =
          e.dataItem.title + ' - marker status before toggle: ' + e.dataItem.hidden;
      }
    }]
  },

chart.legend.addListener('clickLabel', function(event) {

document.getElementById('clicked').textContent =
          e.dataItem.title + ' - marker status before toggle: ' + e.dataItem.hidden;

});

here is Jsfiddle: http://jsfiddle.net/Shivin15/15k53omf/2/

Thank you for your help!


问:
Create, write and display PDF file in android app
I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file.  I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7

```<code>    package com.example.sweetiean.androidpdfdemo;

        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.Color;
        import android.net.Uri;
        import android.os.Environment;
        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

        import com.lowagie.text.Document;
        import com.lowagie.text.DocumentException;
        import com.lowagie.text.Font;
        import com.lowagie.text.HeaderFooter;
        import com.lowagie.text.Paragraph;
        import com.lowagie.text.Phrase;
        import com.lowagie.text.pdf.PdfWriter;
        import com.lowagie.text.Image;

        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;

    public class MainActivity extends ActionBarActivity {

    private Button createPDF , openPDF;

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

        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });

        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    public void createPDF()
    {
        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            Log.d("PDFCreator", "PDF Path: " + path);

            File file = new File(dir, "demo.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

          /* Create Paragraph and S`enter code here`et Font */
            Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");

   /* Create Set Font and its Size */
            Font paraFont= new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);

            Paragraph p2 = new Paragraph("This is an example of a simple paragraph");

  /* You can also SET FONT and SIZE like this */
            Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
            p2.setAlignment(Paragraph.ALIGN_CENTER);
            p2.setFont(paraFont2);

            doc.add(p2);

   /* Inserting Image in PDF */
            /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);*/

            //set footer
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally
        {
            doc.close();
        }
    }

    void openPdf()
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File file = new File(path, "demo.pdf");

        intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

And this is the main activity.

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="100dp"
    android:text="Open PDF" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="44dp"
    android:text="Generate PDF" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="@string/hello_world" />
</code>```

答:
you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.

For this you'll need to add the jar of iTextG to your project:

OR

if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.

For Simple Create and Open pdf:

// Method for creating a pdf file from text, saving it then opening it for display

```<code>public void createandDisplayPdf(String text) {

    Document doc = new Document();

    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "mypdffile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);

        PdfWriter.getInstance(doc, fOut);

        //open the document
        doc.open();

        Paragraph p1 = new Paragraph(text);
        Font paraFont= new Font(Font.FontFamily.COURIER);
        p1.setAlignment(Paragraph.ALIGN_CENTER);
        p1.setFont(paraFont);

        //add paragraph to document
        doc.add(p1);

    } catch (DocumentException de) {
        Log.e("PDFCreator", "DocumentException:" + de);
    } catch (IOException e) {
        Log.e("PDFCreator", "ioException:" + e);
    }
    finally {
        doc.close();
    }

    viewPdf("mypdffile.pdf", "PDF");
}

// Method for opening a pdf file
private void viewPdf(String file, String directory) {

    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
    Uri path = Uri.fromFile(pdfFile);

    // Setting the intent for pdf reader
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(pdfIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
I have an android app which is basically a form to accept user input. This input is stored in a database. But I want to create a pdf file with the information a user enters and and display it so that the user can print the file or save the file to their android note tab. What is the best way to go about it. I have seen iText around but this does not render the file.  I found this code online and I tested it to understand the concept of pdf creation. This uses Lowagie 2.1.7

    package com.example.sweetiean.androidpdfdemo;

        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.Color;
        import android.net.Uri;
        import android.os.Environment;
        import android.support.v7.app.ActionBarActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

        import com.lowagie.text.Document;
        import com.lowagie.text.DocumentException;
        import com.lowagie.text.Font;
        import com.lowagie.text.HeaderFooter;
        import com.lowagie.text.Paragraph;
        import com.lowagie.text.Phrase;
        import com.lowagie.text.pdf.PdfWriter;
        import com.lowagie.text.Image;

        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;

    public class MainActivity extends ActionBarActivity {

    private Button createPDF , openPDF;

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

        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });

        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    public void createPDF()
    {
        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            Log.d("PDFCreator", "PDF Path: " + path);

            File file = new File(dir, "demo.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

          /* Create Paragraph and S`enter code here`et Font */
            Paragraph p1 = new Paragraph("Hi! I am Generating my first PDF using DroidText");

   /* Create Set Font and its Size */
            Font paraFont= new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);

            Paragraph p2 = new Paragraph("This is an example of a simple paragraph");

  /* You can also SET FONT and SIZE like this */
            Font paraFont2= new Font(Font.COURIER,14.0f, Color.GREEN);
            p2.setAlignment(Paragraph.ALIGN_CENTER);
            p2.setFont(paraFont2);

            doc.add(p2);

   /* Inserting Image in PDF */
            /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);*/

            //set footer
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally
        {
            doc.close();
        }
    }

    void openPdf()
    {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File file = new File(path, "demo.pdf");

        intent.setDataAndType( Uri.fromFile(file), "application/pdf" );
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And this is the main activity.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="100dp"
    android:text="Open PDF" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="44dp"
    android:text="Generate PDF" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="@string/hello_world" />

Body:
you'll find the correct code that actually works right.for creating a pdf file, putting some content in it, saving in and the opening the newly created file.

For this you'll need to add the jar of iTextG to your project:

OR

if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.

For Simple Create and Open pdf:

// Method for creating a pdf file from text, saving it then opening it for display

public void createandDisplayPdf(String text) {

    Document doc = new Document();

    try {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "mypdffile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);

        PdfWriter.getInstance(doc, fOut);

        //open the document
        doc.open();

        Paragraph p1 = new Paragraph(text);
        Font paraFont= new Font(Font.FontFamily.COURIER);
        p1.setAlignment(Paragraph.ALIGN_CENTER);
        p1.setFont(paraFont);

        //add paragraph to document
        doc.add(p1);

    } catch (DocumentException de) {
        Log.e("PDFCreator", "DocumentException:" + de);
    } catch (IOException e) {
        Log.e("PDFCreator", "ioException:" + e);
    }
    finally {
        doc.close();
    }

    viewPdf("mypdffile.pdf", "PDF");
}

// Method for opening a pdf file
private void viewPdf(String file, String directory) {

    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
    Uri path = Uri.fromFile(pdfFile);

    // Setting the intent for pdf reader
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.setDataAndType(path, "application/pdf");
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(pdfIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}


问:
ZipArchive gives Unexpected end of data corrupted error
I'm trying to create a zip stream on the fly with some byte array data and make it download via my MVC action.

But the downloaded file always gives the following corrupted error when opened in windows.

And this error when I try to xtract from 7z

But note that the files extracted from the 7z is not corrupted.

I'm using ZipArchive and the below is my code.

```<code>    private byte[] GetZippedPods(IEnumerable<POD> pods, long consignmentID)
    {
        using (var zipStream = new MemoryStream())
        {
            //Create an archive and store the stream in memory.
            using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                int index = 1;
                foreach (var pod in pods)
                {
                    var zipEntry = zipArchive.CreateEntry($"POD{consignmentID}{index++}.png", CompressionLevel.NoCompression);
                    using (var originalFileStream = new MemoryStream(pod.ByteData))
                    {
                        using (var zipEntryStream = zipEntry.Open())
                        {
                            originalFileStream.CopyTo(zipEntryStream);
                        }
                    }
                }
                return zipStream.ToArray();
            }
        }
    }

    public ActionResult DownloadPOD(long consignmentID)
    {
        var pods = _consignmentService.GetPODs(consignmentID);
        var fileBytes = GetZippedPods(pods, consignmentID);
        return File(fileBytes, MediaTypeNames.Application.Octet, $"PODS{consignmentID}.zip");
    }
</code>```

What am I doing wrong here.

Any help would be highly appreciated as I'm struggling with this for a whole day.

Thanks in advance

答:
Move zipStream.ToArray() outside of the zipArchive using.

The reason for your problem is that the stream is buffered. There's a few ways to deal wtih it:

You can set the stream's AutoFlush property to true.

You can manually call .Flush() on the stream.

Or, since it's MemoryStream and you're using .ToArray(), you can simply allow the stream to be Closed/Disposed first (which we've done by moving it outside the using).

Body:
I'm trying to create a zip stream on the fly with some byte array data and make it download via my MVC action.

But the downloaded file always gives the following corrupted error when opened in windows.

And this error when I try to xtract from 7z

But note that the files extracted from the 7z is not corrupted.

I'm using ZipArchive and the below is my code.

    private byte[] GetZippedPods(IEnumerable<POD> pods, long consignmentID)
    {
        using (var zipStream = new MemoryStream())
        {
            //Create an archive and store the stream in memory.
            using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                int index = 1;
                foreach (var pod in pods)
                {
                    var zipEntry = zipArchive.CreateEntry($"POD{consignmentID}{index++}.png", CompressionLevel.NoCompression);
                    using (var originalFileStream = new MemoryStream(pod.ByteData))
                    {
                        using (var zipEntryStream = zipEntry.Open())
                        {
                            originalFileStream.CopyTo(zipEntryStream);
                        }
                    }
                }
                return zipStream.ToArray();
            }
        }
    }

    public ActionResult DownloadPOD(long consignmentID)
    {
        var pods = _consignmentService.GetPODs(consignmentID);
        var fileBytes = GetZippedPods(pods, consignmentID);
        return File(fileBytes, MediaTypeNames.Application.Octet, $"PODS{consignmentID}.zip");
    }

What am I doing wrong here.

Any help would be highly appreciated as I'm struggling with this for a whole day.

Thanks in advance


答:
Function _ converts list of arguments into object</p>

```<code>_(name1, value1, name2, value2, ...)
// returns { name1: value1, name2: value2, ... }
</code>```

Title: what is happening in following javascript function

Body:
Function _ converts list of arguments into object

_(name1, value1, name2, value2, ...)
// returns { name1: value1, name2: value2, ... }


问:
posting list to the controller from partial view
I have a partial view, which generates rows dynamically and from where I want to submit the data to the controller. So I am binding the model properties with a list, but on httppost my list is always null.Using form collection I am able to get the data.  How can I solve this issue?</p>

```<code><td data-title="Product Name">
    <div class="row">
        <div class="col-xs-10" style="padding-right:0px;">
            <div class="form-group">
                @Html.DropDownListFor(model => model._list[Model.id].detail_prod_id, Model._Product, "Please Select Product", new { @class = "chosen-select form-control", @id = "ddlproducts" + Model.id ,@Name= "ddlproducts" +Model.id})
                @Html.ValidationMessageFor(model => model._list[Model.id].detail_prod_id, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="col-xs-2" style="padding-right:25px; padding-left:5px;"><a class="popup-sm fancybox.iframe" href="../pages/add-product.html"><u>Add</u></a></div>
    </div>
</td>
</code>```

答: Try to put code inside form tag and then try..it may work.</p>

Body:
I have a partial view, which generates rows dynamically and from where I want to submit the data to the controller. So I am binding the model properties with a list, but on httppost my list is always null.Using form collection I am able to get the data.  How can I solve this issue?

                @Html.DropDownListFor(model => model._list[Model.id].detail_prod_id, Model._Product, "Please Select Product", new { @class = "chosen-select form-control", @id = "ddlproducts" + Model.id ,@Name= "ddlproducts" +Model.id})
                @Html.ValidationMessageFor(model => model._list[Model.id].detail_prod_id, "", new { @class = "text-danger" })

Add


答:
Here's an example of the script in use with some arguments.

var _ = function() {

  var r = {};
  var a = arguments;

  for(var i=0; i<a.length; i+=2) {
     r[a[i]]=a[i+1];
  }
  console.log(r);
  return r;

}

_('a','1','b','2');```


问:
Materializecss multiple select no firing change in Angular 2
Using materializecss "multiple select" does not appear to fire change. How can you bind a method for when the select changes.

The following code does not fire change.

```<code>HTML
<select id="booger" multiple>
    <option value="1">{{articleIdLabel}}</option>
    <option value="2">{{articlePubDateLabel}}</option>
    <option value="3">{{articleTitleLabel}}</option>
    <option value="4">{{articleViewDateLabel}}</option>
</select>
</code>```

```<code>Component
ngAfterViewInit() {
    $("#booger").material_select();
}

change() {
    console.log("change");
}
</code>```

答:
Use this code. Its working for me</p>

```<code><div class="input-field col s12">
    <select formControlName="status" [(ngModel)]="selectedStatus" materialize="material_select">
        <option [ngValue]="" disabled>Select</option>
        <option [ngValue]="1">Enable</option>
        <option [ngValue]="0">Disable</option>
    </select>
    <label>Status</label>
</div>
</code>```

Body:
Using materializecss "multiple select" does not appear to fire change. How can you bind a method for when the select changes.

The following code does not fire change.

HTML
<select id="booger" multiple>
    <option value="1">{{articleIdLabel}}</option>
    <option value="2">{{articlePubDateLabel}}</option>
    <option value="3">{{articleTitleLabel}}</option>
    <option value="4">{{articleViewDateLabel}}</option>
</select>

Component
ngAfterViewInit() {
    $("#booger").material_select();
}

change() {
    console.log("change");
}

Body:
Use this code. Its working for me

<div class="input-field col s12">
    <select formControlName="status" [(ngModel)]="selectedStatus" materialize="material_select">
        <option [ngValue]="" disabled>Select</option>
        <option [ngValue]="1">Enable</option>
        <option [ngValue]="0">Disable</option>
    </select>
    <label>Status</label>
</div>


问:
Can't link file resource after updating to gradle 3.0.1
I'm getting the following error after trying to run my project.

```<code>Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
</code>```

After following what was suggested here (disabling aapt2) I got bunch of new errors.

```<code>Error:com.android.ide.common.process.ProcessException: Error while
executing process DIR/build-tools/27.0.2/aapt with arguments {package -
f --no-crunch -I DIR/platforms/android-27/android.jar -M
DIR/app/build/intermediates/manifests/full/debug/AndroidManifest.xml -S
DIR/app/build/intermediates/res/merged/debug -m -J
DIR/app/build/generated/source/r/debug -F
DIR/app/build/intermediates/res/debug/resources-debug.ap_ --custom-
package com.appname -0 apk --output-text-symbols
DIR/app/build/intermediates/symbols/debug --no-version-vectors}
</code>```

and

```<code>Error:org.gradle.process.internal.ExecException: Process 'command
'DIR/build-tools/27.0.2/aapt''
finished with non-zero exit value 1
</code>```

Gradle file:

```<code>buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.0'
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
buildscript {
    repositories {
        repositories {
            maven { url 'https://maven.google.com' }
        }
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.trynagrub.trynagrub"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/signalr-client-sdk.jar')
    compile files('libs/signalr-client-sdk-android.jar')
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
//    compile 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
//    compile 'com.github.stfalcon:chatkit:0.2.2'
//    compile 'com.hbb20:ccp:2.0.3'
    compile 'net.danlew:android.joda:2.9.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.xw.repo:bubbleseekbar:3.6'
    compile 'com.github.pavlospt:circleview:1.3'
    compile 'com.facebook.android:facebook-android-sdk:4.29.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:support-compat:27.0.1'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'
    compile 'com.snatik:storage:2.1.0'
    compile 'com.github.tamir7.contacts:contacts:1.1.7'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

I don't know why it keeps happening. But all the R references in the app cannot be resolved because of this. Before updating I had a problem with mixing versions of android support libraries, so I disable the libraries that used different version of support library, can that be the cause of this?

Please help.

答:
Try this,Go to your

```<code>gradle.properties
</code>```

Use the code below

```<code> android.enableAapt2=false
</code>```

Body:
I'm getting the following error after trying to run my project.

Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

After following what was suggested here (disabling aapt2) I got bunch of new errors.

Error:com.android.ide.common.process.ProcessException: Error while
executing process DIR/build-tools/27.0.2/aapt with arguments {package -
f --no-crunch -I DIR/platforms/android-27/android.jar -M
DIR/app/build/intermediates/manifests/full/debug/AndroidManifest.xml -S
DIR/app/build/intermediates/res/merged/debug -m -J
DIR/app/build/generated/source/r/debug -F
DIR/app/build/intermediates/res/debug/resources-debug.ap_ --custom-
package com.appname -0 apk --output-text-symbols
DIR/app/build/intermediates/symbols/debug --no-version-vectors}

and

Error:org.gradle.process.internal.ExecException: Process 'command
'DIR/build-tools/27.0.2/aapt''
finished with non-zero exit value 1

Gradle file:

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.0'
    }
}
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
buildscript {
    repositories {
        repositories {
            maven { url 'https://maven.google.com' }
        }
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.25.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.trynagrub.trynagrub"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/signalr-client-sdk.jar')
    compile files('libs/signalr-client-sdk-android.jar')
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
        transitive = true;
    }
//    compile 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
//    compile 'com.github.stfalcon:chatkit:0.2.2'
//    compile 'com.hbb20:ccp:2.0.3'
    compile 'net.danlew:android.joda:2.9.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.xw.repo:bubbleseekbar:3.6'
    compile 'com.github.pavlospt:circleview:1.3'
    compile 'com.facebook.android:facebook-android-sdk:4.29.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:support-compat:27.0.1'
    compile 'de.hdodenhof:circleimageview:2.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-gcm:11.6.2'
    compile 'com.snatik:storage:2.1.0'
    compile 'com.github.tamir7.contacts:contacts:1.1.7'
    compile 'com.google.android.gms:play-services-maps:11.6.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

I don't know why it keeps happening. But all the R references in the app cannot be resolved because of this. Before updating I had a problem with mixing versions of android support libraries, so I disable the libraries that used different version of support library, can that be the cause of this?

Please help.

Body:
Try this,Go to your

gradle.properties

Use the code below

 android.enableAapt2=false


问:
jQuery Keycode help
How could I run a simple function when a key is pressed using jQuery. So for example if a user pressed the 'Q' key which is 81 in JavaScript it would run a function.</p>

答:
Do you want to do this when you're on a particular textbox, or on a page?

You could do this for the page (Which I suspect is what you want)

```<code>$(function(){
   $(document).keypress(function(event){
     if(e.charCode==81){
        callMyFunction();
     }
   });
});
</code>```

Title: jQuery Keycode help

Body:
Do you want to do this when you're on a particular textbox, or on a page?

You could do this for the page (Which I suspect is what you want)

$(function(){
   $(document).keypress(function(event){
     if(e.charCode==81){
        callMyFunction();
     }
   });
});


问:
Allowing user to input into a text file
How can I create a program that allows a user to input some numbers into a text file, then from the text file randomly selects the numbers in Python 3.0

So far I've tried this:

```<code>input1 = input("Input: ")
input2 = input("Input: ")
file = open("text file", "w")
file.write("\n".join((input1,input2,)))
file.close()
</code>```

That is what I have so far but I am looking for a possible way for the user to be able to input an unlimited amount of inputs.

答:
```<code>import random
# Writing part:
user_input = []
while True:
    i = input('Enter your number. For end press enter:')
    if not i:
        break
    else:
        user_input.append(i)

f = open('user.txt', 'w')

for number in user_input:
    f.write(number+'\n')

f.close()

# Reading part:
numbers = []
f = open('user.txt', 'r')

for line in f:
    numbers.append(line)

f.close()

print(random.choice(numbers))
</code>```

Title: Allowing user to input into a text file

Body:
How can I create a program that allows a user to input some numbers into a text file, then from the text file randomly selects the numbers in Python 3.0

So far I've tried this:

input1 = input("Input: ")
input2 = input("Input: ")
file = open("text file", "w")
file.write("\n".join((input1,input2,)))
file.close()

That is what I have so far but I am looking for a possible way for the user to be able to input an unlimited amount of inputs.


问:
Django with Celery - existing object not found
I am having problem with executing celery task from another celery task.

Here is the problematic snippet (data object already exists in database, its attributes are just updated inside finalize_data function):

```<code>def finalize_data(data):
    data = update_statistics(data)
    data.save()
    from apps.datas.tasks import optimize_data
    optimize_data.delay(data.pk)

@shared_task
def optimize_data(data_pk):
    data = Data.objects.get(pk=data_pk)
    #Do something with data
</code>```

Get call in optimize_data function fails with "Data matching query does not exist."

If I call the retrieve by pk function in finalize_data function it works fine. It also works fine if I delay the celery task call for some time.

This line:

```<code>optimize_data.apply_async((data.pk,), countdown=10)
</code>```

instead of

```<code>optimize_data.delay(data.pk)
</code>```

works fine. But I don't want to use hacks in my code. Is it possible that .save() call is asynchronously blocking access to that row/object?

答:
I know that this is an old post but I stumbled on this problem today. Lee's answer pointed me to the correct direction but I think a better solution exists today.

Using the on_commit handler provided by Django this problem can be solved without a hackish way of countdowns in the code which might not be intuitive to the user about why it exsits.

I'm not sure if this existed when the question was posted but I'm just posting the answer so that people who come here in the future know about the alternative.

Body:
I am having problem with executing celery task from another celery task.

Here is the problematic snippet (data object already exists in database, its attributes are just updated inside finalize_data function):

def finalize_data(data):
    data = update_statistics(data)
    data.save()
    from apps.datas.tasks import optimize_data
    optimize_data.delay(data.pk)

@shared_task
def optimize_data(data_pk):
    data = Data.objects.get(pk=data_pk)
    #Do something with data

Get call in optimize_data function fails with "Data matching query does not exist."

If I call the retrieve by pk function in finalize_data function it works fine. It also works fine if I delay the celery task call for some time.

This line:

optimize_data.apply_async((data.pk,), countdown=10)

instead of

optimize_data.delay(data.pk)

works fine. But I don't want to use hacks in my code. Is it possible that .save() call is asynchronously blocking access to that row/object?


问:
webpack not copying images
I trying to import local package, that already bundled in webpack. When I build an app everything looks good, except webpack not copying images, fonts, etc. from that internal package. Any ideas what's going wrong?

When I try to reference my custom library, that is already bundled:

```<code>- dist
-- asdfjlsjdflasdjflsdaf.ttf
-- sdjflsjdfasjdflsjdfsd.eot
-- mylibrary.js
</code>```

only mylibrary.js is copied. So parent app looks like:

```<code>- dist
-- mylibrary.js
-- parentapp.js
- packages
-- mylibrary
--- src...
--- dist...
</code>```

Problem could be solved:

by increasing the loader limit and everything that converted to
base64 and included in mylibrary.js is available in my parent app

copy plugin, which copy fonts from mylibrary, but this solution looks ugly, since everyone who using mylibrary should care about copying fonts, images, etc.

答:
A work around for copying images and fonts using webpack would be the use of GlobCopyWebpackPlugin.

How it works (I am not quite sure how your current webpack configuration looks like) but let`s go with a blank slate and see if this might help you. So, you can keep separate webpack files for different environments - say for now a prod and dev. Once you have created webpack.config.dev.js, inside the "plugins" property you can use GlobCopyWebpackPlugin. It would look something like below:

```<code>    new GlobCopyWebpackPlugin({
        "patterns": [
            "Assets"
        ],
        "globOptions": {
            "cwd": path.join(process.cwd(), "src"),
            "dot": true,
            "ignore": "**/.gitkeep"
        }
    }),
</code>```

"Assets" is the folder where you have kept fonts, icons, multimedia etc.

And then you can configure your tasks inside package.json

```<code>"scripts": {
    "serve": "npm run -s generatelocalefiles && node --max_old_space_size=4096 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config webpack.config.dev.js --port=4300",
    }
</code>```

And the folder structure looks like this (just in case you are wondering)

```<code>-src
  -app
  -assets
-package.json
-webpack.config.dev.js
-webpack.config.prod.js
</code>```

Hope this helps!

Title: webpack not copying images

Body:
I trying to import local package, that already bundled in webpack. When I build an app everything looks good, except webpack not copying images, fonts, etc. from that internal package. Any ideas what's going wrong?

When I try to reference my custom library, that is already bundled:

- dist
-- asdfjlsjdflasdjflsdaf.ttf
-- sdjflsjdfasjdflsjdfsd.eot
-- mylibrary.js

only mylibrary.js is copied. So parent app looks like:

- dist
-- mylibrary.js
-- parentapp.js
- packages
-- mylibrary
--- src...
--- dist...

Problem could be solved:

by increasing the loader limit and everything that converted to
base64 and included in mylibrary.js is available in my parent app

copy plugin, which copy fonts from mylibrary, but this solution looks ugly, since everyone who using mylibrary should care about copying fonts, images, etc.

Body:
A work around for copying images and fonts using webpack would be the use of GlobCopyWebpackPlugin.

How it works (I am not quite sure how your current webpack configuration looks like) but let`s go with a blank slate and see if this might help you. So, you can keep separate webpack files for different environments - say for now a prod and dev. Once you have created webpack.config.dev.js, inside the "plugins" property you can use GlobCopyWebpackPlugin. It would look something like below:

    new GlobCopyWebpackPlugin({
        "patterns": [
            "Assets"
        ],
        "globOptions": {
            "cwd": path.join(process.cwd(), "src"),
            "dot": true,
            "ignore": "**/.gitkeep"
        }
    }),

"Assets" is the folder where you have kept fonts, icons, multimedia etc.

And then you can configure your tasks inside package.json

"scripts": {
    "serve": "npm run -s generatelocalefiles && node --max_old_space_size=4096 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config webpack.config.dev.js --port=4300",
    }

And the folder structure looks like this (just in case you are wondering)

-src
  -app
  -assets
-package.json
-webpack.config.dev.js
-webpack.config.prod.js

Hope this helps!


问:
How can I update a small field in a big SQL table if another field in the same row is changed by an external process?
I'd like to call Update ... Set ... Where ... to update a field as soon as that evil ERP process is changing the value of another.

I'm running MS SQL.

答: You want to use a trigger but I would be very wary of the bug in the selected answer. See Brent Ozar's well written post http://www.brentozar.com/archive/2009/01/triggers-need-to-handle-multiple-records/ on Multiple Records.</p>

OwnerDisplayName: secr

LastEditorDisplayName: Cade Roux

OwnerDisplayName: Josef


问:
OCaml syntax error in type declaration
I'm new to OCaml and I have no clue why this is giving me a syntax error:

```<code>type ('nonterminal, 'terminal) pe =
| Empty
| T of t
| N of n
| Seq of list
| Choose of list
| Star of e
| Not of e;;

type ('nonterminal, 'terminal) pe_tree =
| Is_empty
| Leaf of t
| Node of (n,tree)
| Sequence of list
| Repeat of list
| Is_not of e;;
</code>```

All it's saying is that there's a syntax error on line 14 characters 0-1 (which is where | Sequence of list is) and I can't figure out why!

答:
```<code>type ('nonterminal, 'terminal) pe_tree =
  | Is_empty
  | Leaf of t
  | Node of (n * tree)
  | Sequence of list
  | Repeat of list
  | Is_not of e;;
</code>```

You use * to define product types, as in 'a * 'b. Although probably not too important now, you should know that Node of 'a * 'b and Node of ('a * 'b) are different. You can think of them as a variant type with two parameters, and the other a variant type with one parameter (a tuple), respectively.

There are a few other things,

you need to define what Sequence and Repeat are a list of.

'nonterminal and 'terminal aren't used; unless they are for phantom types, which i doubt it, they probably should be used in part of the signature.

Title: OCaml syntax error in type declaration

Body:
I'm new to OCaml and I have no clue why this is giving me a syntax error:

type ('nonterminal, 'terminal) pe =
| Empty
| T of t
| N of n
| Seq of list
| Choose of list
| Star of e
| Not of e;;

type ('nonterminal, 'terminal) pe_tree =
| Is_empty
| Leaf of t
| Node of (n,tree)
| Sequence of list
| Repeat of list
| Is_not of e;;

All it's saying is that there's a syntax error on line 14 characters 0-1 (which is where | Sequence of list is) and I can't figure out why!

Body:
type ('nonterminal, 'terminal) pe_tree =
  | Is_empty
  | Leaf of t
  | Node of (n * tree)
  | Sequence of list
  | Repeat of list
  | Is_not of e;;

You use * to define product types, as in 'a * 'b. Although probably not too important now, you should know that Node of 'a * 'b and Node of ('a * 'b) are different. You can think of them as a variant type with two parameters, and the other a variant type with one parameter (a tuple), respectively.

There are a few other things,

you need to define what Sequence and Repeat are a list of.

'nonterminal and 'terminal aren't used; unless they are for phantom types, which i doubt it, they probably should be used in part of the signature.