问:
How to configure Jetty in spring-boot (easily?)
By following the tutorial, I could bring up the spring-boot with Jetty running using the following dependencies.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</code>```

However, how could I configure the Jetty server such as:

Server threads (Queue thread pool)

Server connectors

Https configurations.

all those configuration available in Jetty...?

Is there an easy way to do in

application.yml?

Configuration class?

Any example would be greatly appreciated.

Many thanks!!

答:
If anyone is using Spring Boot - you can easily configure this in you application.properties thusly:

```<code>server.max-http-post-size=n
</code>```

where n is the maximum size to which you wish to set this property. For example I use:

```<code>server.max-http-post-size=5000000
</code>```

Body:
By following the tutorial, I could bring up the spring-boot with Jetty running using the following dependencies.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>

However, how could I configure the Jetty server such as:

Server threads (Queue thread pool)

Server connectors

Https configurations.

all those configuration available in Jetty...?

Is there an easy way to do in

application.yml?

Configuration class?

Any example would be greatly appreciated.

Many thanks!!

Body:
If anyone is using Spring Boot - you can easily configure this in you application.properties thusly:

server.max-http-post-size=n

where n is the maximum size to which you wish to set this property. For example I use:

server.max-http-post-size=5000000


来源: stackexchange

问:
get selected id of kendo drop down value
how to get id of selected name from dropdown.

whene select Apples then got id 1and select Oranges then 2.

this is simple kendo dropdown example.

```<code><body>
            <input id="dropdownlist" />

            <script>
                $("#dropdownlist").kendoDropDownList({
                  dataSource: [
                    { id: 1, name: "Apples" },
                    { id: 2, name: "Oranges" }
                  ],
                  dataTextField: "name",
                  dataValueField: "id",
                  index: 1,
                  select: onSelect
                });

                function onSelect(e) {
                console.log(e);
                  };
            </script>
</body>
</code>```

thanks.

答:
Please use this.dataItem()</p>

```<code>function onSelect(e) {
    alert(this.dataItem().id);
    alert(this.dataItem().Name);
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how to get id of selected name from dropdown.

whene select Apples then got id 1and select Oranges then 2.

this is simple kendo dropdown example.

            <input id="dropdownlist" />

thanks.

Body:
Please use this.dataItem()

function onSelect(e) {
    alert(this.dataItem().id);
    alert(this.dataItem().Name);
};


问:
Where is RESTful API parameter URL-decoded?
I have a Spring-based RESTful API which is deployed to a Tomcat server. When I call this API like below (value of "para" has been URL-encoded) and debug it, value of "para" in controller method is "aaa bbb" which has already been URL-decoded.

GET http://MY-TOMCAT-SERVER/SOME-PATH?para=aaa%20bbb

However, when I run a SpringBoot-based local Test Automation case (not deployed anywhere) to test the same API, the value of "para" in controller method hasn't been URL-decoded.

Question is, what is the difference between the two scenarios and where is "para" URL-decoded in the first scenario?

答:
Hopefully I can give you a hint for the first part of your question:

The Apache Tomcat server.xml contains an tag Connector, this tag can have an optional attribute URIEncoding. Example:

```<code><Connector connectionTimeout="20000"
           port="8080"
           protocol="HTTP/1.1"
           redirectPort="8443"
           URIEncoding="UTF-8" />
</code>```

So I think that Tomcat is responsible for the URI encoding. But I do not know how this is activated in an Embedded-Spring-Boot-Tomcat.

@See: How does URIEncoding = 'UTF-8' work?

@See: Apache Tomcat 8 Configuration Reference / The HTTP Connector

Body:
Hopefully I can give you a hint for the first part of your question:

The Apache Tomcat server.xml contains an tag Connector, this tag can have an optional attribute URIEncoding. Example:

<Connector connectionTimeout="20000"
           port="8080"
           protocol="HTTP/1.1"
           redirectPort="8443"
           URIEncoding="UTF-8" />

So I think that Tomcat is responsible for the URI encoding. But I do not know how this is activated in an Embedded-Spring-Boot-Tomcat.

@See: How does URIEncoding = 'UTF-8' work?

@See: Apache Tomcat 8 Configuration Reference / The HTTP Connector


问:
Is it possible to get the java bean value in jsp that has no action mapping in struts config?
I would like to know if there is any way I can retrieve the Java bean value in JSP page that has no mapping in struts config.

I tried to set the variable using bean and retrieve it using property attribute, but of no use.

```<code><s:bean var="item" name="com.store.items"> <s:set property value= "%{item.getuniqueID}"/> </s:bean>
</code>```

答:
Yes, there is! You can simply add an instance of the bean and its getters and setters in your action class. The bean will be created from the fields that you have in the JSP. In fact, if you have a multitude of properties to be added in the action class, it is advisable to use a bean instance instead of native properties. This will result in less complex action classes.

```<code>UserBean bean = new UserBean();
//Getters and setters
</code>```

You can fetch the value of these properties by using . with the name of the instance. e.g. <s:property value="bean.name"/>

Body:
I would like to know if there is any way I can retrieve the Java bean value in JSP page that has no mapping in struts config.

I tried to set the variable using bean and retrieve it using property attribute, but of no use.

<s:bean var="item" name="com.store.items"> <s:set property value= "%{item.getuniqueID}"/> </s:bean>

Body:
Yes, there is! You can simply add an instance of the bean and its getters and setters in your action class. The bean will be created from the fields that you have in the JSP. In fact, if you have a multitude of properties to be added in the action class, it is advisable to use a bean instance instead of native properties. This will result in less complex action classes.

UserBean bean = new UserBean();
//Getters and setters

You can fetch the value of these properties by using . with the name of the instance. e.g. <s:property value="bean.name"/>


问:
Twitter4j reply to tweet not working
I'm trying to reply to a tweet (that i post 10 seconds before) using twitter4j but it is only posting it to the timeline and not as a reply.

```<code>post = mainTwitter.updateStatus(...); //1st twitter account
StatusUpdate reply = new StatusUpdate(...);
try {
   reply.setInReplyToStatusId(post.getId());
   contextTwitter.updateStatus(reply); //2nd twitter account
} catch (TwitterException e) {
   System.err.println("Couldn't post context");
   e.printStackTrace();
}
</code>```

The id is not -1, it is the right long value. No exception thrown.

答:
You can use the following code to make your snippet working

```<code>public void init() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
      .setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
      .setOAuthAccessToken(TWITTER_ACCESS_TOKEN)
      .setOAuthAccessTokenSecret(TWITTER_ACCESS_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

/***
 *
 * @param tweetId : tweet Id
 * @param messgae : Reply message
 * @return
 * @throws TwitterException
 */
public String reply(String tweetId, String messgae ) throws TwitterException {
        Status status = twitter.showStatus(Long.parseLong(tweetId));
        Status reply = twitter.updateStatus(new StatusUpdate(" @" + status.getUser().getScreenName() + " "+ messgae).inReplyToStatusId(status.getId()));
    return Long.toString(reply.getId());
}
</code>```

Usage :

```<code>reply("930497966443454464", " Hello Eva")
</code>```

Title: Twitter4j reply to tweet not working

Body:
I'm trying to reply to a tweet (that i post 10 seconds before) using twitter4j but it is only posting it to the timeline and not as a reply.

post = mainTwitter.updateStatus(...); //1st twitter account
StatusUpdate reply = new StatusUpdate(...);
try {
   reply.setInReplyToStatusId(post.getId());
   contextTwitter.updateStatus(reply); //2nd twitter account
} catch (TwitterException e) {
   System.err.println("Couldn't post context");
   e.printStackTrace();
}

The id is not -1, it is the right long value. No exception thrown.

Body:
You can use the following code to make your snippet working

public void init() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
      .setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
      .setOAuthAccessToken(TWITTER_ACCESS_TOKEN)
      .setOAuthAccessTokenSecret(TWITTER_ACCESS_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

/***
 *
 * @param tweetId : tweet Id
 * @param messgae : Reply message
 * @return
 * @throws TwitterException
 */
public String reply(String tweetId, String messgae ) throws TwitterException {
        Status status = twitter.showStatus(Long.parseLong(tweetId));
        Status reply = twitter.updateStatus(new StatusUpdate(" @" + status.getUser().getScreenName() + " "+ messgae).inReplyToStatusId(status.getId()));
    return Long.toString(reply.getId());
}

Usage :

reply("930497966443454464", " Hello Eva")


问:
Problem with large number of markers on the map
I am working on an Android app that already exists on iPhone.

In the app, there is a Map activity that has (I counted) around 800 markers in four groups marked by drawable in four different colors. Each group can be turned on or off. Information about markers I have inside List. I create a mapOverlay for each group, then I attach that overlay to the map. I strongly believe that coding part I did properly. But I will attach my code anyway...

The thing is, my Nexus One can't handle map with all those markers. It takes around 15 seconds just to draw 500 markers. Then when all drawn, map is not quite smooth. It is sort of hard to zoom and navigate around. It can be done, but experience is bad and I would like to see if something can be done there. I know if I avoid String > Double conversion, I could save some time, but I doubt that would be significant.

iPhone seems doesn't have problems showing all these markers. It takes roughly about 1-2 seconds to show all of them and zooming and panning is not that bad. Slow down is noticeable but still acceptable. I personally think it is no good to draw all those markers, but app is designed by somebody else and I am not supposed to make any drastic changes.

I am not sure what to do here. It seems I will have to come up with different functionality, maybe use GPS location, if known, and draw only markers within some radius, or, if location not known, use center of the screen(map) and draw markers around that. I will have to have reasonable explanation for my bosses in case I make these changes.

I appreciate if anybody has any idas.

And the code:

```<code>    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.pin_blue);
    drawable = this.getResources().getDrawable(R.drawable.pin_blue);
    ArrList = appState.GetSleepArrList();
    ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable, this);
    ...
    ...
       for (int m = 0; m < ArrList.size(); m++) {
            tName = ArrList.get(m).get("name").toString();
            tId = ArrList.get(m).get("id").toString();
            tLat = ArrList.get(m).get("lat").toString();;
            tLng = ArrList.get(m).get("lng").toString();;
            try {
                lat = Double.parseDouble(tLat);
                lng = Double.parseDouble(tLng);
                p1 = new GeoPoint(
                        (int) (lat * 1E6),
                        (int) (lng * 1E6));
                OverlayItem overlayitem = new OverlayItem(p1, tName, tId);
                itemizedoverlay.addOverlay(overlayitem);
            } catch (NumberFormatException e) {
                Log.d(TAG, "NumberFormatException" + e);
            }
        }
        mapOverlays.add(itemizedoverlay);
        mapView.postInvalidate();
</code>```

................................

```<code>public class ItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;
    public HelloItemizedOverlay(Drawable defaultMarker, Context context)
    {
        super(boundCenterBottom(defaultMarker));
        mContext = context;
    }

    public void addOverlay(OverlayItem overlay)
    {
        mOverlays.add(overlay);
        populate();
    }
    @Override
    protected OverlayItem createItem(int i)
    {
        return mOverlays.get(i);
    }
    @Override
    public int size()
    {
        return mOverlays.size();
    }
    @Override
    protected boolean onTap(int index)
    {
        final OverlayItem item = mOverlays.get(index);
                    ... EACH MARKER WILL HAVE ONCLICK EVENT THAT WILL PRODUCE CLICABLE
                    ... BALOON WITH MARKER'S NAME.
        return true;
    }
}
</code>```

答: Well. It turned out I call populate() every time after adding an marker. I took populate() out of addOverlay() method and I am calling it after loop finishes. All markers now show almost instantaneously. The only problem now is that the map is very unresponsive when at lower zoom (showing a lot of markers at once). I don't see solution for this unless I figure out how to decrease number of markers on the map when map is zoomed out... thinking to group them somehow.... currently working on this... </p>

ContentLicense: CC BY-SA 2.5

Body:
I am working on an Android app that already exists on iPhone.

In the app, there is a Map activity that has (I counted) around 800 markers in four groups marked by drawable in four different colors. Each group can be turned on or off. Information about markers I have inside List. I create a mapOverlay for each group, then I attach that overlay to the map. I strongly believe that coding part I did properly. But I will attach my code anyway...

The thing is, my Nexus One can't handle map with all those markers. It takes around 15 seconds just to draw 500 markers. Then when all drawn, map is not quite smooth. It is sort of hard to zoom and navigate around. It can be done, but experience is bad and I would like to see if something can be done there. I know if I avoid String > Double conversion, I could save some time, but I doubt that would be significant.

iPhone seems doesn't have problems showing all these markers. It takes roughly about 1-2 seconds to show all of them and zooming and panning is not that bad. Slow down is noticeable but still acceptable. I personally think it is no good to draw all those markers, but app is designed by somebody else and I am not supposed to make any drastic changes.

I am not sure what to do here. It seems I will have to come up with different functionality, maybe use GPS location, if known, and draw only markers within some radius, or, if location not known, use center of the screen(map) and draw markers around that. I will have to have reasonable explanation for my bosses in case I make these changes.

I appreciate if anybody has any idas.

And the code:

    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.pin_blue);
    drawable = this.getResources().getDrawable(R.drawable.pin_blue);
    ArrList = appState.GetSleepArrList();
    ItemizedOverlay itemizedoverlay = new ItemizedOverlay(drawable, this);
    ...
    ...
       for (int m = 0; m < ArrList.size(); m++) {
            tName = ArrList.get(m).get("name").toString();
            tId = ArrList.get(m).get("id").toString();
            tLat = ArrList.get(m).get("lat").toString();;
            tLng = ArrList.get(m).get("lng").toString();;
            try {
                lat = Double.parseDouble(tLat);
                lng = Double.parseDouble(tLng);
                p1 = new GeoPoint(
                        (int) (lat * 1E6),
                        (int) (lng * 1E6));
                OverlayItem overlayitem = new OverlayItem(p1, tName, tId);
                itemizedoverlay.addOverlay(overlayitem);
            } catch (NumberFormatException e) {
                Log.d(TAG, "NumberFormatException" + e);
            }
        }
        mapOverlays.add(itemizedoverlay);
        mapView.postInvalidate();

................................

public class ItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;
    public HelloItemizedOverlay(Drawable defaultMarker, Context context)
    {
        super(boundCenterBottom(defaultMarker));
        mContext = context;
    }

    public void addOverlay(OverlayItem overlay)
    {
        mOverlays.add(overlay);
        populate();
    }
    @Override
    protected OverlayItem createItem(int i)
    {
        return mOverlays.get(i);
    }
    @Override
    public int size()
    {
        return mOverlays.size();
    }
    @Override
    protected boolean onTap(int index)
    {
        final OverlayItem item = mOverlays.get(index);
                    ... EACH MARKER WILL HAVE ONCLICK EVENT THAT WILL PRODUCE CLICABLE
                    ... BALOON WITH MARKER'S NAME.
        return true;
    }
}


问:
Run stored procedure in SQL Developer
I have procedure with params:

```<code>procedure GetReceipt(iPaymentID    in number
                    ,oReceipt      out sys_refcursor
                    ,oReceiptItems out sys_refcursor);
</code>```

I try to run this my anonymous block:

```<code>SET serveroutput on;
DECLARE
  oReceipt sys_refcursor;
  oReceiptItems sys_refcursor;
BEGIN
  API.MOD.GetReceipt(4209735, oReceipt, oReceiptItems);
  dbms_output.put_line('oReceipt: ' || oReceipt);
  dbms_output.put_line('oReceiptItems: ' || oReceiptItems);
END;
</code>```

I get this error:

```<code>Error report:
ORA-06550: Строка 6, столбец 24:
PLS-00306: wrong number or types of arguments in call to '||'
ORA-06550: Строка 6, столбец 3:
PL/SQL: Statement ignored
ORA-06550: Строка 7, столбец 24:
PLS-00306: wrong number or types of arguments in call to '||'
ORA-06550: Строка 7, столбец 3:
PL/SQL: Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:
</code>```

How call this procedure? Where my mistake?

答:
You can use bind variables to store the cursors and PRINT to print them:

```<code>VARIABLE receipt REFCURSOR;
VARIABLE receiptitems REFCURSOR;

BEGIN
  API.MOD.GetReceipt(4209735, :receipt, :receiptitems);
END;
/

PRINT receipt;
PRINT receiptitems;
</code>```

Where my mistake?

A cursor is a named pointer to a private SQL area that stores information for processing a specific query. It does not make sense to concatenate a pointer to something internal to the database with a string.

If you want to display the values in your PL/SQL block then you will need to loop through each record of the cursor and get the individual column values for that record and then use DBMS_OUTPUT to display them:

```<code>SET serveroutput on;
DECLARE
  oReceipt      sys_refcursor;
  oReceiptItems sys_refcursor;

  col1 RECEIPT_TABLE.COL1%TYPE;     -- Same data type as COL1 of the RECEIPT_TABLE table
  col2 RECEIPT_TABLE.COL2%TYPE;     -- Same data type as COL2 of the RECEIPT_TABLE table
  col3 RECEIPT_TABLE.COL3%TYPE;     -- Same data type as COL3 of the RECEIPT_TABLE table

  rec  RECEIPT_ITEMS_TABLE%ROWTYPE; -- Assumes the cursor is returning all the columns from
                                    -- the RECEIPT_ITEMS_TABLE table
BEGIN
  API.MOD.GetReceipt(4209735, oReceipt, oReceiptItems);

  dbms_output.put_line('oReceipt:');
  LOOP
    FETCH oReceipt INTO col1, col2, col3; -- Store the values from the current record
    EXIT WHEN oReceipt%NOTFOUND;          -- Stop if the end of the cursor has been reached
    DBMS_OUTPUT.PUT_LINE( col1 || ' ' || col2 || ' ' || col3 );
                                          -- Output the values
  END LOOP;

  dbms_output.put_line('oReceiptItems:');
  LOOP
    FETCH oReceiptItems INTO rec;         -- Fetch the current row into a record
    EXIT WHEN oReceipt%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE( rec.colA || ' ' || rec.colB || ' ' || rec.colC );
  END LOOP;
END;
/
</code>```

Title: Run stored procedure in SQL Developer

Body:
I have procedure with params:

procedure GetReceipt(iPaymentID    in number
                    ,oReceipt      out sys_refcursor
                    ,oReceiptItems out sys_refcursor);

I try to run this my anonymous block:

SET serveroutput on;
DECLARE
  oReceipt sys_refcursor;
  oReceiptItems sys_refcursor;
BEGIN
  API.MOD.GetReceipt(4209735, oReceipt, oReceiptItems);
  dbms_output.put_line('oReceipt: ' || oReceipt);
  dbms_output.put_line('oReceiptItems: ' || oReceiptItems);
END;

I get this error:

Error report:
ORA-06550: Строка 6, столбец 24:
PLS-00306: wrong number or types of arguments in call to '||'
ORA-06550: Строка 6, столбец 3:
PL/SQL: Statement ignored
ORA-06550: Строка 7, столбец 24:
PLS-00306: wrong number or types of arguments in call to '||'
ORA-06550: Строка 7, столбец 3:
PL/SQL: Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

How call this procedure? Where my mistake?

Body:
You can use bind variables to store the cursors and PRINT to print them:

VARIABLE receipt REFCURSOR;
VARIABLE receiptitems REFCURSOR;

BEGIN
  API.MOD.GetReceipt(4209735, :receipt, :receiptitems);
END;
/

PRINT receipt;
PRINT receiptitems;

Where my mistake?

A cursor is a named pointer to a private SQL area that stores information for processing a specific query. It does not make sense to concatenate a pointer to something internal to the database with a string.

If you want to display the values in your PL/SQL block then you will need to loop through each record of the cursor and get the individual column values for that record and then use DBMS_OUTPUT to display them:

SET serveroutput on;
DECLARE
  oReceipt      sys_refcursor;
  oReceiptItems sys_refcursor;

  col1 RECEIPT_TABLE.COL1%TYPE;     -- Same data type as COL1 of the RECEIPT_TABLE table
  col2 RECEIPT_TABLE.COL2%TYPE;     -- Same data type as COL2 of the RECEIPT_TABLE table
  col3 RECEIPT_TABLE.COL3%TYPE;     -- Same data type as COL3 of the RECEIPT_TABLE table

  rec  RECEIPT_ITEMS_TABLE%ROWTYPE; -- Assumes the cursor is returning all the columns from
                                    -- the RECEIPT_ITEMS_TABLE table
BEGIN
  API.MOD.GetReceipt(4209735, oReceipt, oReceiptItems);

  dbms_output.put_line('oReceipt:');
  LOOP
    FETCH oReceipt INTO col1, col2, col3; -- Store the values from the current record
    EXIT WHEN oReceipt%NOTFOUND;          -- Stop if the end of the cursor has been reached
    DBMS_OUTPUT.PUT_LINE( col1 || ' ' || col2 || ' ' || col3 );
                                          -- Output the values
  END LOOP;

  dbms_output.put_line('oReceiptItems:');
  LOOP
    FETCH oReceiptItems INTO rec;         -- Fetch the current row into a record
    EXIT WHEN oReceipt%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE( rec.colA || ' ' || rec.colB || ' ' || rec.colC );
  END LOOP;
END;
/


问:
How can I reference the IntelliJ project path in my code?
I have a text file in my project and need to read its contents:

```<code>private final static String SOURCE_FILE = "C:/Project/resources/Source.txt";
</code>```

Is it possible to use an IntelliJ variable?

```<code>private final static String SOURCE_FILE = "${ProjectDir}/resources/Source.txt";
</code>```

I want to avoid hardcoding a path in my code.

答:
For example if you added a folder audio to your project structure then you could acces it like this:

```<code>new File(".\\Audio\\MyAudioFile.mp3")
</code>```

Good luck, if you have any questions feel free to shoot 'em in comments :)

Body:
I have a text file in my project and need to read its contents:

private final static String SOURCE_FILE = "C:/Project/resources/Source.txt";

Is it possible to use an IntelliJ variable?

private final static String SOURCE_FILE = "${ProjectDir}/resources/Source.txt";

I want to avoid hardcoding a path in my code.

Body:
For example if you added a folder audio to your project structure then you could acces it like this:

new File(".\\Audio\\MyAudioFile.mp3")

Good luck, if you have any questions feel free to shoot 'em in comments :)


问:
jQuery deferred: Nesting promises in methods, last callback too early
I have a problem with deferreds/promises. I have a main function that calls two functions that have to be executed serially. The first one contains a bunch of asynchronous web service calls that have to be executed serially first. But actually my second function is called before every asynchronous feedback in the first function is there.

I built a small example that shows my problem: https://fiddle.jshell.net/qLf1c0uq/

Here is the code for reference:

function first() {
  $('ul').append("
first started
");
  let deferred = $.Deferred();
  setTimeout(function() { // Any async function.
    $('ul').append("
first ended
");
    deferred.resolve();
  }, 2000);
  return deferred.promise();
}

function second(da) {
  $('ul').append("
second started
");
  let deferred = $.Deferred();
  $('ul').append("
second ended
");
  deferred.resolve();
  return deferred.promise();
}

function third(da) {
  $('ul').append('
third started
')
  let deferred = $.Deferred();
  setTimeout(function() {
    $('ul').append("
third ended
");
    deferred.resolve();
  }, 2000);

  return deferred.promise();
}

function GroupFunction1() {
  let deferred = $.Deferred();
  $('ul').append("
Group 1 started
");
  var data = "test2";
  $.when(first()).then(function() {
    second(data);
  }).then(function() {
    third("test2");
  }).then(function() {
    $('ul').append("
Group 1 ended
");
    deferred.resolve();
  });

  return deferred.promise();
}

function GroupFunction2() {
  $('ul').append("
Group 2 started
");

  $('ul').append("
Group 2 ended
");
}

$(function() {
  $.when(GroupFunction1()).then(GroupFunction2);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul></code>```

The GroupFunction2 is started before the third function ends. I was expecting it vice versa.

Anyone can help?

Thanks!

答:
You need to return the promises inside your callback functions. That's the only way the promise chain can wait on them.

Also, you're abusing the Explicit Promise Creation Antipattern.

.then() returns a promise. You can just return that. And there's no point in passing a single promise into $.when() because all $.when() is going to do is spit it right back out:

function first() {
  $('ul').append("
first started
");
  let deferred = $.Deferred();
  setTimeout(function() { // Any async function.
    $('ul').append("
first ended
");
    deferred.resolve();
  }, 2000);
  return deferred.promise();
}

function second(da) {
  $('ul').append("
second started
");
  let deferred = $.Deferred();
  $('ul').append("
second ended
");
  deferred.resolve();
  return deferred.promise();
}

function third(da) {
  $('ul').append('
third started
')
  let deferred = $.Deferred();
  setTimeout(function() {
    $('ul').append("
third ended
");
    deferred.resolve();
  }, 2000);

  return deferred.promise();
}

function GroupFunction1() {
  let deferred = $.Deferred();
  $('ul').append("
Group 1 started
");
  var data = "test2";

  // v-- here
  return first()      // v-- here
    .then(function() { return second(data); })
    .then(function() { return third("test2"); })
    .then(function() { $('ul').append("
Group 1 ended
"); });
}

function GroupFunction2() {
  $('ul').append("
Group 2 started
");

  $('ul').append("
Group 2 ended
");
}

$(function() {
  GroupFunction1().then(GroupFunction2);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul></code>```

Body:
I have a problem with deferreds/promises. I have a main function that calls two functions that have to be executed serially. The first one contains a bunch of asynchronous web service calls that have to be executed serially first. But actually my second function is called before every asynchronous feedback in the first function is there.

I built a small example that shows my problem: https://fiddle.jshell.net/qLf1c0uq/

Here is the code for reference:

function first() {
  $('ul').append("
first started
");
  let deferred = $.Deferred();
  setTimeout(function() { // Any async function.
    $('ul').append("
first ended
");
    deferred.resolve();
  }, 2000);
  return deferred.promise();
}

function second(da) {
  $('ul').append("
second started
");
  let deferred = $.Deferred();
  $('ul').append("
second ended
");
  deferred.resolve();
  return deferred.promise();
}

function third(da) {
  $('ul').append('
third started
')
  let deferred = $.Deferred();
  setTimeout(function() {
    $('ul').append("
third ended
");
    deferred.resolve();
  }, 2000);

  return deferred.promise();
}

function GroupFunction1() {
  let deferred = $.Deferred();
  $('ul').append("
Group 1 started
");
  var data = "test2";
  $.when(first()).then(function() {
    second(data);
  }).then(function() {
    third("test2");
  }).then(function() {
    $('ul').append("
Group 1 ended
");
    deferred.resolve();
  });

  return deferred.promise();
}

function GroupFunction2() {
  $('ul').append("
Group 2 started
");

  $('ul').append("
Group 2 ended
");
}

$(function() {
  $.when(GroupFunction1()).then(GroupFunction2);
})

The GroupFunction2 is started before the third function ends. I was expecting it vice versa.

Anyone can help?

Thanks!

Body:
You need to return the promises inside your callback functions. That's the only way the promise chain can wait on them.

Also, you're abusing the Explicit Promise Creation Antipattern.

.then() returns a promise. You can just return that. And there's no point in passing a single promise into $.when() because all $.when() is going to do is spit it right back out:

function first() {
  $('ul').append("<li>first started</li>");
  let deferred = $.Deferred();
  setTimeout(function() { // Any async function.
    $('ul').append("<li>first ended</li>");
    deferred.resolve();
  }, 2000);
  return deferred.promise();
}

function second(da) {
  $('ul').append("<li>second started</li>");
  let deferred = $.Deferred();
  $('ul').append("<li>second ended</li>");
  deferred.resolve();
  return deferred.promise();
}

function third(da) {
  $('ul').append('<li>third started</li>')
  let deferred = $.Deferred();
  setTimeout(function() {
    $('ul').append("<li>third ended</li>");
    deferred.resolve();
  }, 2000);

  return deferred.promise();
}

function GroupFunction1() {
  let deferred = $.Deferred();
  $('ul').append("<li>Group 1 started</li>");
  var data = "test2";

  // v-- here
  return first()      // v-- here
    .then(function() { return second(data); })
    .then(function() { return third("test2"); })
    .then(function() { $('ul').append("<li>Group 1 ended</li>"); });
}

function GroupFunction2() {
  $('ul').append("<li>Group 2 started</li>");

  $('ul').append("<li>Group 2 ended</li>");
}

$(function() {
  GroupFunction1().then(GroupFunction2);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>


问:
Specifiying start time and end time for playing audio file in javascript
I am trying to use JavaScript to play an audio file on a webpage.

I have an article that I want to be read out from the mp3 file. As the article is being read out by the audio I want to highlight the text of the article that is being read out by the audio.

Also I want to be able to provide each sentence as a link where the user can simply click a particular sentence and the mp3 file starts where that sentence begins and ends when that sentence ends.

答:
Maybe it's late but I have to do this right now. I'm using this https://github.com/westonruter/html5-audio-read-along

It is very easy to use. Here you can listen to the mp3 and reading the text with the current word highlighted. You can perform various actions as clicking on a specific word or playing with audio controls and it works fine.
But if you are using mp3 files remember not to have a variable bitrate because it does not work with the currentTime audio value.
Hope it helps!


问:
Obtaining mean of certain columns with specific names
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

```<code>qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"
</code>```

Here's an example data table:

```<code>        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48
</code>```

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

```<code>        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15
</code>```

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

```<code>sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})
</code>```

答:
Using dplyr and assuming df as your data table, you can do:

```<code>select(df,c(201701,201702)) %>% summarise_all(mean)
</code>```

dplyr gives you added flexibility for selecting groups columns as you can use helpers like matches, starts_with,contains etc.

Body:
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"

Here's an example data table:

        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})

Body:
Using dplyr and assuming df as your data table, you can do:

select(df,c(201701,201702)) %>% summarise_all(mean)

dplyr gives you added flexibility for selecting groups columns as you can use helpers like matches, starts_with,contains etc.


问:
Php check if my date from db is today echo with today and if tomorrow then echo tomorrow
How to make a check if datetime from my db is today and then echo with "today" and if my datetime is tomorrow echo with tomorrow. I want to make this for a date reminder for fullcalendar.

My Php code is not working or is messed:

```<code>$reminder = date('d-M-Y',strtotime(date("d-m-Y", strtotime($row['start'])) . " +0 days"));
$tomorrow = strtotime("+1 day");
$tomorrow = getdate($tomorrow);

if($reminder = "0 Days") {
    echo "Today";
} else if($reminder = "1 Days" ) {
    echo "Tomorrow";
} else {
    echo (strtotime($reminder) - strtotime(date('d-M-Y'))) / (60 * 60 * 24).' Days';
}
</code>```

答:
You can try it like this:</p>

```<code>$diff = date_diff(date('d-M-Y'), date('d-M-Y', strtotime($row['start'])));

if($diff == 0) {
    echo "Today";
} else if($diff == 1) {
    echo "Tomorrow";
}
</code>```

Body:
How to make a check if datetime from my db is today and then echo with "today" and if my datetime is tomorrow echo with tomorrow. I want to make this for a date reminder for fullcalendar.

My Php code is not working or is messed:

$reminder = date('d-M-Y',strtotime(date("d-m-Y", strtotime($row['start'])) . " +0 days"));
$tomorrow = strtotime("+1 day");
$tomorrow = getdate($tomorrow);

if($reminder = "0 Days") {
    echo "Today";
} else if($reminder = "1 Days" ) {
    echo "Tomorrow";
} else {
    echo (strtotime($reminder) - strtotime(date('d-M-Y'))) / (60 * 60 * 24).' Days';
}

Body:
You can try it like this:

$diff = date_diff(date('d-M-Y'), date('d-M-Y', strtotime($row['start'])));

if($diff == 0) {
    echo "Today";
} else if($diff == 1) {
    echo "Tomorrow";
}


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
The key issue is that a glyph in a string takes 32 bits (16 bits for a character code) but a byte only has 8 bits to spare.  A one-to-one mapping doesn't exist unless you restrict yourself to strings that only contain ASCII characters.  System.Text.Encoding has lots of ways to map a string to byte[], you need to pick one that avoids loss of information and that is easy to use by your client when she needs to map the byte[] back to a string.

Utf8 is a popular encoding, it is compact and not lossy.

OwnerDisplayName: Vulcan Eager

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Dale Ragan

OwnerDisplayName: nobugz


问:
linking issue - trying to build a library and use another archive with it
Is it possible to build a library that uses another, already compiled library?

I have some make files that are used to normally build an executable. When making the executable, I use -L ../include/lib1.a to include the original library.

Now, I am building a separate program that is calling the classes from the executable, which was never built into a library, just compiled to the executable with a link like

```<code>${CPP} -c ${INC} ${CFLAGS} MyFile.cpp ${OBJ} ${LIB2} -lm
</code>```

Where LIB2 includes the reference to lib1.a

Now I want to access the class MyFile.cpp directly, and when I build it to its own library lib2.a, and try to call it from the new program, I get a bunch of errors that the classes it references are missing. This is in spite of the fact that when building the new program I am linking in both lib1.a and lib2.a

答:
Yes, you should be able to do it. It would be helpful to see the exact errors you are getting.

If you compile your sources into a library and supply the libraries they use on the command line, the compiler is liable to put the other library(s) into your new one. If that happens, and then someone tries to build a program against your library and those others, they will get a whole mess of "doubly-defined symbol" errors.

Body:
Is it possible to build a library that uses another, already compiled library?

I have some make files that are used to normally build an executable. When making the executable, I use -L ../include/lib1.a to include the original library.

Now, I am building a separate program that is calling the classes from the executable, which was never built into a library, just compiled to the executable with a link like

${CPP} -c ${INC} ${CFLAGS} MyFile.cpp ${OBJ} ${LIB2} -lm

Where LIB2 includes the reference to lib1.a

Now I want to access the class MyFile.cpp directly, and when I build it to its own library lib2.a, and try to call it from the new program, I get a bunch of errors that the classes it references are missing. This is in spite of the fact that when building the new program I am linking in both lib1.a and lib2.a


问:
extract data from a json file in python
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly. </p>

```<code>    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}
</code>```

<p>if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?  </p>

答:
You can first iterate kids and apply condition

```<code>import json
js = '''your json text data'''
j = json.loads(js)

for items in j['family']['kids']:
    if '1234' in items['ssn']:
        print(items['name'])
</code>```

Output

```<code>'jim'
</code>```

Title: extract data from a json file in python

Body:
I have been try to find the best way to search a particular value and extract the data. I am new and hope i have worded this correctly.

    {"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}

if i needed to search "ssn" containing "1234" and return the "name" "jim" what would be the best way to go about achieving this?

Body:
You can first iterate kids and apply condition

import json
js = '''your json text data'''
j = json.loads(js)

for items in j['family']['kids']:
    if '1234' in items['ssn']:
        print(items['name'])

Output

'jim'


问:
How to create a group in WSO2 Store
I have some APIs in WSO2 store, and some of them are grouped.

How can I create a new group and put APIs in it?

The project has been given to me without much info, and I've searched a lot about creating new groups, but with no success. My version is 2011-2013.

答:
In WSO2 API Manager, APIs are grouped by tags. When you create an API from publisher, you can assign tags for your APIs. Then you can filter APIs by those tags in store.

There is a special set of tags which are called groups.

See https://docs.wso2.com/display/AM210/Customizing+the+API+Store#CustomizingtheAPIStore-CategorizingandgroupingAPIs

Title: How to create a group in WSO2 Store


答:
use json package like below

```<code>ans =     '{"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}'
temp = json.loads(ans)
for kid in  temp['family']['kids']:
     print kid['name'],kid['ssn']
</code>```

hope this is what you look for .

Title: extract data from a json file in python

Body:
use json package like below

ans =     '{"family": {
    "name": "Mary",
    "age": "32",
    "sex": "female",
    "kids": [
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }]}}'
temp = json.loads(ans)
for kid in  temp['family']['kids']:
     print kid['name'],kid['ssn']

hope this is what you look for .


问:
Lifecycle of items - android memory leak
I'm pretty new in developing android apps and I have a hard time to understand the app/activity/class lifecycle.

I have two activities: MainActivity and DetailActivity. Each one has it's own Fragments.
There is a StatusController singleton between them, which implements the observer pattern.

I read about that android kills apps when it needs memory. So here are my questsions:

Does it only kill the whole app or is it killing activities one by one?

Is it possible that the activity behind a fragment gets killed but
the fragment survives?

Is there anywhere a documentation about what gets killed on memory
leak?

When do singleton classes get killed?

答:
Here are your answers:

Does it only kill the whole app or is it killing activities one by
one?

Android OS kills whole process rather killing an individual activity. Process kills mean your app will not running any more

Is it possible that the activity behind a fragment gets killed but
the fragment survives?

No it is not possible that acitivity is called but fragments survive because fragments are loaded over activity and fragment lifecycle is dependents on fragment.Once activity is destroyed fragment will no longer be visible anymore

Is there anywhere a documentation about what gets killed on memory
leak? When do singleton classes get killed?

When you kill your app singleton classes will be killed. NOTE: If OS kills the process in which your app is running in that case all Singleton classes will be killed

NOTE: For memory leak documentation you may refer below mentioned link.
    https://mindorks.com/blog/detecting-and-fixing-memory-leaks-in-android


问:
Django - I am unable to post data in db through a form. Why?
forms.py :

```<code>from django import forms
from django.forms import ModelForm
from django.utils import timezone

from .models import Book

class BookCreateForm(forms.Form):
   title = forms.CharField(required=True)
   author = forms.CharField(required=True)
   description = forms.CharField(widget=forms.Textarea)
   genre = forms.CharField(required=True)
   book_image = forms.ImageField(required=True)
   publishedDate =
   forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y"))
   price =forms.DecimalField(decimal_places=2,max_digits=8)
   stock = forms.DecimalField(decimal_places=2, max_digits=8)
</code>```

models.py:

```<code>from django.db import models
from django.utils import timezone

# Create your models here.

class Book(models.Model):
    title         = models.CharField(max_length=250)
    author        = models.CharField(max_length=250)
    description   = models.TextField()
    genre         = models.CharField(max_length=60)
    book_image    = models.ImageField()
    publishedDate = models.DateField(default=timezone.now)
    price         = models.DecimalField(decimal_places=2, max_digits=8)
    stock         = models.DecimalField(decimal_places=2, max_digits=8)

class Quote(models.Model):
    quote_name = models.TextField()
    quote_author = models.CharField(max_length=250)
</code>```

views.py:

```<code>from django.shortcuts import render, get_object_or_404
from django.http import  HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView
from .models import Book
from .forms import BookCreateForm

# Create your views here.

def book_createview(request):
    template_name='bookstores/addbook.html'
    # print (request.GET)
    # print (request.POST)
    if request.method == "GET":
         print ("Get ")
         print(request.GET)
    if request.method == "POST":
         print("post data")
         print (request.POST)
    formed=BookCreateForm()
    form = BookCreateForm(request.POST)

if form.is_valid():
    obj =Book.objects.create(
        title=form.cleaned_data.get('title'),
        author=form.cleaned_data.get('author'),
        description=form.cleaned_data.get('description'),
        genre=form.cleaned_data.get('genre'),
        book_image = form.cleaned_data.get('book_image'),
        publishedDate = form.cleaned_data.get('publishedData'),
        price = form.cleaned_data.get('price'),
        stock = form.cleaned_data.get('stock')
    )
if form.errors:
    print (form.errors)

    #return  HttpResponseRedirect("/store/")

context ={}
return render(request,template_name,context)
</code>```

TemplateView:

```<code>{% extends "home.html" %}
{% block head_title %}Adding book || {{ block.super }} {% endblock
 head_title %}
{% block content %}
<p><i>tell us about the book you liked</i></p>
<div class ="form-group">
<form method="POST"> {% csrf_token %}
<input type="text" name ='title' placeholder="Title"><br>
<input type="text" name ='author' placeholder="author"><br>
<input type="text" name ='description' placeholder="description"><br>
<input type="text" name ='genre' placeholder="genre"><br>
<input type="text" name ='book_image' placeholder="book_image"><br>
<input type="text" name ='price' placeholder="price"><br>
<input type="text" name ='stockk' placeholder="stock"><br>

<button type="submit">Save</button>
</form>
</div>
{% endblock  %}
</code>```

The error that I am getting is :

Get
title
This field is
  required.

author
This field
  is required.

description
This field is
  required.

genre
This field
  is required.

book_image
This field is
  required.

publishedDate
This field is
  required.

price
This field
  is required.

stock
This
  field is required.

 [15/Nov/2017 12:38:27] "GET
  /addbook/ HTTP/1.1" 200 2375 post data https://images.gr-assets.com/books/1506565784l/30835567.jpg'],
  'price': ['1045.36'], 'stockk': ['40']}>
book_image
This field
  is required.

publishedDate
This field is
  required.

stock

答:
There are two problems:

when you are making GET request you are creating Book object. you should not do that.

when you are making POST request.

a. book_image key is not coming which you can seen in post data.

b. from form stockk is coming for stock. There is typing mistake.

c. publishedDate will not come via form.

Body:
forms.py :

from django import forms
from django.forms import ModelForm
from django.utils import timezone

from .models import Book

class BookCreateForm(forms.Form):
   title = forms.CharField(required=True)
   author = forms.CharField(required=True)
   description = forms.CharField(widget=forms.Textarea)
   genre = forms.CharField(required=True)
   book_image = forms.ImageField(required=True)
   publishedDate =
   forms.DateField(widget=forms.widgets.DateInput(format="%m/%d/%Y"))
   price =forms.DecimalField(decimal_places=2,max_digits=8)
   stock = forms.DecimalField(decimal_places=2, max_digits=8)

models.py:

from django.db import models
from django.utils import timezone

# Create your models here.

class Book(models.Model):
    title         = models.CharField(max_length=250)
    author        = models.CharField(max_length=250)
    description   = models.TextField()
    genre         = models.CharField(max_length=60)
    book_image    = models.ImageField()
    publishedDate = models.DateField(default=timezone.now)
    price         = models.DecimalField(decimal_places=2, max_digits=8)
    stock         = models.DecimalField(decimal_places=2, max_digits=8)

class Quote(models.Model):
    quote_name = models.TextField()
    quote_author = models.CharField(max_length=250)

views.py:

from django.shortcuts import render, get_object_or_404
from django.http import  HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView
from .models import Book
from .forms import BookCreateForm

# Create your views here.

def book_createview(request):
    template_name='bookstores/addbook.html'
    # print (request.GET)
    # print (request.POST)
    if request.method == "GET":
         print ("Get ")
         print(request.GET)
    if request.method == "POST":
         print("post data")
         print (request.POST)
    formed=BookCreateForm()
    form = BookCreateForm(request.POST)

if form.is_valid():
    obj =Book.objects.create(
        title=form.cleaned_data.get('title'),
        author=form.cleaned_data.get('author'),
        description=form.cleaned_data.get('description'),
        genre=form.cleaned_data.get('genre'),
        book_image = form.cleaned_data.get('book_image'),
        publishedDate = form.cleaned_data.get('publishedData'),
        price = form.cleaned_data.get('price'),
        stock = form.cleaned_data.get('stock')
    )
if form.errors:
    print (form.errors)

    #return  HttpResponseRedirect("/store/")

context ={}
return render(request,template_name,context)

TemplateView:

{% extends "home.html" %}
{% block head_title %}Adding book || {{ block.super }} {% endblock
 head_title %}
{% block content %}

tell us about the book you liked

<form method="POST"> {% csrf_token %}
<input type="text" name ='title' placeholder="Title">

<input type="text" name ='author' placeholder="author">

<input type="text" name ='description' placeholder="description">

<input type="text" name ='genre' placeholder="genre">

<input type="text" name ='book_image' placeholder="book_image">

<input type="text" name ='price' placeholder="price">

<input type="text" name ='stockk' placeholder="stock">

<button type="submit">Save</button>
</form>

{% endblock  %}

The error that I am getting is :

Get
title
This field is
  required.

author
This field
  is required.

description
This field is
  required.

genre
This field
  is required.

book_image
This field is
  required.

publishedDate
This field is
  required.

price
This field
  is required.

stock
This
  field is required.

 [15/Nov/2017 12:38:27] "GET
  /addbook/ HTTP/1.1" 200 2375 post data https://images.gr-assets.com/books/1506565784l/30835567.jpg'],
  'price': ['1045.36'], 'stockk': ['40']}>
book_image
This field
  is required.

publishedDate
This field is
  required.

stock


问:
Android Action Bar SearchView Menu Icon Size
I have implemented a SearchView into the action bar of an activity and it works fine and will display as expected on a Galaxy Nexus and most emulators. However on a Galaxy Note 10.1 and emulators with tablet-sized screens it looks like this:

As you can see the search icon is much smaller than the other icons. How can I get the icon size of the search icon to match the other icons? Or how can I uniform the icon sizes on large screens?

At first I thought perhaps the problem could be related to the size of the drawable, but after checking them I can confirm the icons consistently exist in the projects drawable-hdpi, drawable-mdpi and drawable-xhdpi resource folders and are the same size as the other menu icons. I used this tool to generate the drawables and there are no irregularities in sizes of any of the drawables. I've even tried using the same drawable as one of the other menu icons and the resulting size difference is the same.

The icon remains the same size with the SearchView open (which is fine because otherwise it might overlap the underline of the EditText view), but when the SearchView is closed again the icon is the same size and still much smaller than the rest of the icons and this may be a clue as to why this is happening.

Activity code:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.example, menu);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
        final MenuItem item = menu.findItem(R.id.search);
        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
} else {
    menu.removeItem(R.id.search); // API < 11
    }
    return true;
}
</code>```

res/menu/example.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/search"
        android:showAsAction="ifRoom"
        android:actionViewClass="android.widget.SearchView" />

</menu>
</code>```

res/xml/searchable.xml

```<code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search"
    android:hint="@string/search" >
</searchable>
</code>```

AndroidManifest.xml

```<code><intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

<meta-data
    android:name="android.app.default_searchable"
    android:value="com.example.ExampleActivity" />
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />
</code>```

UPDATE:

Apologies this problem was in fact related to drawables. Specifically the size ratio of the menu icons. The hdpi-drawable menu icons were all 64x64 (x2) when they should have been 48x48 (x1.5).

So this problem can be solved by re-sizing all of the mdpi-drawable menu icons to 32x32 and hdpi-drawable to 48x48 and xhdpi-drawable to 64x64 (thanks to @rekire for suggesting this).

The problem was caused by using an older version of this tool to generate the menu icons. So if you have the same problem you could try using the latest version to generate new icons.

答:
use drawable as bitmap
size it
use the bitmap xml

How to Resize a Bitmap in Android?

```<code>SearchView searchView = ((SearchView) searchMenuItem.getActionView());
            int searchImgId = android.support.v7.appcompat.R.id.search_button;
            Drawable searchIcon = scaled drawable .....
searchView.findViewById(searchImgId)).setImageDrawable(searchIcon);
</code>```

Body:
I have implemented a SearchView into the action bar of an activity and it works fine and will display as expected on a Galaxy Nexus and most emulators. However on a Galaxy Note 10.1 and emulators with tablet-sized screens it looks like this:

As you can see the search icon is much smaller than the other icons. How can I get the icon size of the search icon to match the other icons? Or how can I uniform the icon sizes on large screens?

At first I thought perhaps the problem could be related to the size of the drawable, but after checking them I can confirm the icons consistently exist in the projects drawable-hdpi, drawable-mdpi and drawable-xhdpi resource folders and are the same size as the other menu icons. I used this tool to generate the drawables and there are no irregularities in sizes of any of the drawables. I've even tried using the same drawable as one of the other menu icons and the resulting size difference is the same.

The icon remains the same size with the SearchView open (which is fine because otherwise it might overlap the underline of the EditText view), but when the SearchView is closed again the icon is the same size and still much smaller than the rest of the icons and this may be a clue as to why this is happening.

Activity code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.example, menu);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
        final MenuItem item = menu.findItem(R.id.search);
        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
} else {
    menu.removeItem(R.id.search); // API < 11
    }
    return true;
}

res/menu/example.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/search"
        android:title="@string/search"
        android:icon="@drawable/search"
        android:showAsAction="ifRoom"
        android:actionViewClass="android.widget.SearchView" />

</menu>

res/xml/searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search"
    android:hint="@string/search" >
</searchable>

AndroidManifest.xml

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

<meta-data
    android:name="android.app.default_searchable"
    android:value="com.example.ExampleActivity" />
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

UPDATE:

Apologies this problem was in fact related to drawables. Specifically the size ratio of the menu icons. The hdpi-drawable menu icons were all 64x64 (x2) when they should have been 48x48 (x1.5).

So this problem can be solved by re-sizing all of the mdpi-drawable menu icons to 32x32 and hdpi-drawable to 48x48 and xhdpi-drawable to 64x64 (thanks to @rekire for suggesting this).

The problem was caused by using an older version of this tool to generate the menu icons. So if you have the same problem you could try using the latest version to generate new icons.

Body:
use drawable as bitmap
size it
use the bitmap xml

How to Resize a Bitmap in Android?

SearchView searchView = ((SearchView) searchMenuItem.getActionView());
            int searchImgId = android.support.v7.appcompat.R.id.search_button;
            Drawable searchIcon = scaled drawable .....
searchView.findViewById(searchImgId)).setImageDrawable(searchIcon);


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
Honestly, I consider that kind of weird advice.

I can't speak to every specific case, but in general what x + "" will do in C# (which should depend on the existence of an overloaded + operator for either the type of x or string) is call something like string.Concat(x, "") which in turn will invoke x.ToString anyway.

In the typical case, this just means that x + "" has the overhead of one more method call than x.ToString. When x is a variable of some value type, however, this can also cause the value of x to be boxed unless an overload for + exists specifically for the type of x (this might be considered a useless point to make, as x will also be boxed in a call to ToString if its type has not overridden that method; this strikes me a a bit rarer, but it most assuredly does happen).

These are fairly trivial differences, of course. The real difference between these two approaches is that of readability; in my experience, x + "" is not very idiomatic in .NET and so I would be inclined to avoid it. That said, it could just be that it isn't common in the slice of the .NET world I inhabit, while there could be plenty of .NET developers out there who do it.

I will point out that while in Java, perhaps you had to write the unwieldy Integer.toString(x) for variables x of primitive types like int, in C# and in .NET in general all types (including so-called "primitive" ones) inherit from object and so have the method ToString (along with GetType and GetHashCode) available to them.


问:
Allow PHP in Contact Form 7 editor
I need a form to be able to get dynamic date values from php

My current form looks like the following:

```<code>[radio date default:1 "1" "2017-11-16" "2017-11-17" "2017-11-18" "2017-11-20" "2017-11-21"]
</code>```

Is there any way to use php values instead?

Ideally, I would be able to put something like this in the editor itself

```<code>[radio date default:1 "1" "<?php echo date('Y-m-d'); ?>"]
</code>```

Is this possible?

答:
Here is the simple way to change the value of radio button,

What you need to do is, give an ID to radio button,

For example,

```<code>[radio field_name id:date_radio default:1 "1" "2" "3" "4"]
</code>```

Where I have given ID "date_radio".

Now, in your page, you need to add following jQuery code:

```<code><script>
jQuery(document).ready(function(){
        jQuery('#date_radio').find("input[type='radio']").attr('value','<?php echo date('Y-m-d');?>'); // if you are going to put this code in .js file, then you need to get value from hidden field where you need to give date as value.
});
</script>
</code>```

Make sure, Above code will change the value of all the radio option for given ID.

Please let me know if you need any further help in this.

Thanks!

Title: Allow PHP in Contact Form 7 editor

Body:
I need a form to be able to get dynamic date values from php

My current form looks like the following:

[radio date default:1 "1" "2017-11-16" "2017-11-17" "2017-11-18" "2017-11-20" "2017-11-21"]

Is there any way to use php values instead?

Ideally, I would be able to put something like this in the editor itself

[radio date default:1 "1" "<?php echo date('Y-m-d'); ?>"]

Is this possible?

Body:
Here is the simple way to change the value of radio button,

What you need to do is, give an ID to radio button,

For example,

[radio field_name id:date_radio default:1 "1" "2" "3" "4"]

Where I have given ID "date_radio".

Now, in your page, you need to add following jQuery code:

<script>
jQuery(document).ready(function(){
        jQuery('#date_radio').find("input[type='radio']").attr('value','<?php echo date('Y-m-d');?>'); // if you are going to put this code in .js file, then you need to get value from hidden field where you need to give date as value.
});
</script>

Make sure, Above code will change the value of all the radio option for given ID.

Please let me know if you need any further help in this.

Thanks!


问:
passing numpy array to tensorflow queue
I have a tensorflow model which works fine, I was using feed_dict but I'm trying to change that to a queuing operations to increase the performance.

old code

```<code>            p_boxes = self.graph.get_tensor_by_name("con:0")
            p_confs = self.graph.get_tensor_by_name("sha:0")
            x = self.graph.get_tensor_by_name("x_in:0")
            feed_dict_testing = {x: x_batch}
            np_pred_confs, np_pred_boxes = sess.run([pred_confs,
            pred_boxes], feed_dict=feed_dict_testing)
</code>```

Above is my old code where I pass a numpy array object of shape - (1024,1024,3) and the predictions worked fine.

With the new code Im trying to simulate a simple code passing a numpy array of the same size but I get this following error.

```<code>ValueError: Fetch argument <tf.Tensor 'sha:0' shape=(1024, 1, 2) dtype=float32> cannot be interpreted as a Tensor. (Tensor Tensor("sha_4:0", shape=(1024, 1, 2), dtype=float32) is not an element of this graph.)
</code>```

New code:-

```<code>a  = np.zeros((1024, 1024, 3))
dtypes=[tf.float32]
print len(dtypes)
shapes=[1024, 1024, 3]
print len(shapes)
q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shapes)

enqueue_op = q.enqueue(a)
qr = tf.train.QueueRunner(q, [enqueue_op] * 1)
tf.train.add_queue_runner(qr)
data = q.dequeue()
p_boxes = graph.get_tensor_by_name("con:0")
p_confs = graph.get_tensor_by_name("sha:0")
x = graph.get_tensor_by_name("x_in:0")

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    confs, boxes = sess.run([p_confs, p_boxes])
    print boxes, confs
</code>```

答:
Try to call graph.get_tensor_by_name(..) inside a with graph.as_default(): then you should be able to have access to the element.

Or it might be the name of your tensor that is wrong. You can check the name of your operations in your graph with :

```<code>sess = tf.Session()
op = sess.graph.get_operations()
print [m.values() for m in op][1]
</code>```

Title: passing numpy array to tensorflow queue

Body:
I have a tensorflow model which works fine, I was using feed_dict but I'm trying to change that to a queuing operations to increase the performance.

old code

            p_boxes = self.graph.get_tensor_by_name("con:0")
            p_confs = self.graph.get_tensor_by_name("sha:0")
            x = self.graph.get_tensor_by_name("x_in:0")
            feed_dict_testing = {x: x_batch}
            np_pred_confs, np_pred_boxes = sess.run([pred_confs,
            pred_boxes], feed_dict=feed_dict_testing)

Above is my old code where I pass a numpy array object of shape - (1024,1024,3) and the predictions worked fine.

With the new code Im trying to simulate a simple code passing a numpy array of the same size but I get this following error.

ValueError: Fetch argument <tf.Tensor 'sha:0' shape=(1024, 1, 2) dtype=float32> cannot be interpreted as a Tensor. (Tensor Tensor("sha_4:0", shape=(1024, 1, 2), dtype=float32) is not an element of this graph.)

New code:-

a  = np.zeros((1024, 1024, 3))
dtypes=[tf.float32]
print len(dtypes)
shapes=[1024, 1024, 3]
print len(shapes)
q = tf.FIFOQueue(capacity=200,dtypes=dtypes,shapes=shapes)

enqueue_op = q.enqueue(a)
qr = tf.train.QueueRunner(q, [enqueue_op] * 1)
tf.train.add_queue_runner(qr)
data = q.dequeue()
p_boxes = graph.get_tensor_by_name("con:0")
p_confs = graph.get_tensor_by_name("sha:0")
x = graph.get_tensor_by_name("x_in:0")

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    confs, boxes = sess.run([p_confs, p_boxes])
    print boxes, confs

Body:
Try to call graph.get_tensor_by_name(..) inside a with graph.as_default(): then you should be able to have access to the element.

Or it might be the name of your tensor that is wrong. You can check the name of your operations in your graph with :

sess = tf.Session()
op = sess.graph.get_operations()
print [m.values() for m in op][1]


问:
How do you seed images using Shrine
I can't seed my images using shrine, unlike carrierwave the below code doesn't work.

```<code>Profile.create! id: 2,
                user_id: 2,
                brand: "The Revengers",
                location: "Azgaurd",
                phone_number: "send a raven",
                image_data: File.open(Rails.root+"app/assets/images/seed/thor.png")
</code>```

i've also tried

```<code>image_data: ImageUploader.new(:store).upload(File.open(Rails.root+"app/assets/images/seed/thor.png"))
</code>```

but it returns

```<code>JSON::ParserError in Profiles#show
743: unexpected token at '#<ImageUploader::UploadedFile:0x007fd8bc3142e0>'
</code>```

Is there a shrine way? I can't seem to find it anywhere.

shrine.rb

```<code>require "cloudinary"
require "shrine/storage/cloudinary"

Cloudinary.config(
  cloud_name: ENV['CLOUD_NAME'],
  api_key:ENV['API_KEY'],
  api_secret:ENV['API_SECRET'],
)

Shrine.storages = {
  cache: Shrine::Storage::Cloudinary.new(prefix: "cache"), # for direct
uploads
  store: Shrine::Storage::Cloudinary.new(prefix: "store"),
}
</code>```

profile.rb

```<code>class Profile < ApplicationRecord
  include ImageUploader[:image]
  belongs_to :user
  has_and_belongs_to_many :genres
  scoped_search on: [:brand]
end
</code>```

image_uploader.rb

```<code>class ImageUploader < Shrine
end
</code>```

答:
Using Shrine, the attachment attribute (e.g. image_data) on the model (e.g. Profile) is a text column in the database (you can define it as json or jsonb too). Now it should be clear that this column cannot accept a File object (which you are trying to do).

First you need to use an uploader (e.g. ImageUploader) to upload the target file in one of your configured Shrine storages (e.g. :cache or :store):

```<code>uploader = ImageUploader.new(:store)
file = File.new(Rails.root.join('app/assets/images/seed/thor.png'))
uploaded_file = uploader.upload(file)
</code>```

Here the main method of the uploader is #upload, which takes an IO-like object on the input, and returns a representation of the uploaded file (ImageUploader::UploadedFile) on the output.

At this point, you have the uploaded file in hand. Now the model (Profile) will only need the json representation of the uploaded file in its attachment attribute column (image_data) like so:

```<code>Profile.create! id: 2,
                user_id: 2,
                brand: "The Revengers",
                location: "Azgaurd",
                phone_number: "send a raven",
                image_data: uploaded_file.to_json
</code>```

Title: How do you seed images using Shrine

Body:
I can't seed my images using shrine, unlike carrierwave the below code doesn't work.

Profile.create! id: 2,
                user_id: 2,
                brand: "The Revengers",
                location: "Azgaurd",
                phone_number: "send a raven",
                image_data: File.open(Rails.root+"app/assets/images/seed/thor.png")

i've also tried

image_data: ImageUploader.new(:store).upload(File.open(Rails.root+"app/assets/images/seed/thor.png"))

but it returns

JSON::ParserError in Profiles#show
743: unexpected token at '#<ImageUploader::UploadedFile:0x007fd8bc3142e0>'

Is there a shrine way? I can't seem to find it anywhere.

shrine.rb

require "cloudinary"
require "shrine/storage/cloudinary"

Cloudinary.config(
  cloud_name: ENV['CLOUD_NAME'],
  api_key:ENV['API_KEY'],
  api_secret:ENV['API_SECRET'],
)

Shrine.storages = {
  cache: Shrine::Storage::Cloudinary.new(prefix: "cache"), # for direct
uploads
  store: Shrine::Storage::Cloudinary.new(prefix: "store"),
}

profile.rb

class Profile < ApplicationRecord
  include ImageUploader[:image]
  belongs_to :user
  has_and_belongs_to_many :genres
  scoped_search on: [:brand]
end

image_uploader.rb

class ImageUploader < Shrine
end

Body:
Using Shrine, the attachment attribute (e.g. image_data) on the model (e.g. Profile) is a text column in the database (you can define it as json or jsonb too). Now it should be clear that this column cannot accept a File object (which you are trying to do).

First you need to use an uploader (e.g. ImageUploader) to upload the target file in one of your configured Shrine storages (e.g. :cache or :store):

uploader = ImageUploader.new(:store)
file = File.new(Rails.root.join('app/assets/images/seed/thor.png'))
uploaded_file = uploader.upload(file)

Here the main method of the uploader is #upload, which takes an IO-like object on the input, and returns a representation of the uploaded file (ImageUploader::UploadedFile) on the output.

At this point, you have the uploaded file in hand. Now the model (Profile) will only need the json representation of the uploaded file in its attachment attribute column (image_data) like so:

Profile.create! id: 2,
                user_id: 2,
                brand: "The Revengers",
                location: "Azgaurd",
                phone_number: "send a raven",
                image_data: uploaded_file.to_json


问:
XML serialization library interoperability between Java and Python
I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream that would have done it for me. Thrift or such other libraries is not going to work unless they allow the data format to be xml. I am looking for suggestion for any library that can do it. - Thanks</p>

答:
Since Java and Python objects are so different in themselves, it's almost impossible to do this, unless you on both sides restrict the types allowed and such things.

And in that case, I'd recommend you use JSON, which is a nice interoperability format, even though it's not XML.

Otherwise you could easily write a library that takes XStream XML and loads it into Python objects, but it will always be limited to whatever is similar between Java and Python.


问:
CSS Selector issue with list items
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li class="child">
This need to be Red Color
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul></code>```

答:
CSS

```<code>ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}
</code>```

HTML

```<code><ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li class="child">
This need to be Red Color
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
</code>```

I got solution for red color for specified text below.fiddle

```<code><li class="child">
This need to be Red Color
  </li>
</code>```

Title: CSS Selector issue with list items

Body:
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}

hellow

hellow

hellow

hellow

hellow

hellow

hellow

This need to be Red Color

sub text

sub text

sub text

Body:
CSS

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}

HTML

<ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li class="child">
This need to be Red Color
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

I got solution for red color for specified text below.fiddle

<li class="child">
This need to be Red Color
  </li>


问:
PayPal payment to issue activation code
I have just created my first PayPal button and it is working correctly within sand box.  I would like to know the best way (if possible) to issue a unique  activation code on my return url ensuring that the user has definitely paid before they receive the code.  I could manually email the code but wondered if the was any way of automating this using some sort of return value? Possibly returning to an aspx page which then reads from my database to get the next activation key and displays it?

Thanks
Garry

答:
As you already know that PayPal doesn't provide such facility for delivering activation instantly but it does offer the Instant Payment Notification API (PayPal IPN) which can be used to build such a platform.
Here is a great article for that purpose only. https://www.codeproject.com/Articles/383207/Selling-software-using-PayPal-IPN-as-an-eCommerceenter link description here</p>

Title: PayPal payment to issue activation code


答:
I don't think you're likely to find an automated way to serialise Java objects and deserialise into Python objects. They're different things, so if you want to translate, you'll have to write some code at one or both ends.

If it's really simple stuff - strings, numbers, booleans, and so on, then you might want to look into json, a very simple format with bindings for just about every language. Deserialising a json object in Python is as simple as:

```<code>json.loads('{"test":false}')
</code>```

Another way to approach the problem might be to use Jython, an implementation of Python in Java, so you can use Java objects directly.

Title: XML serialization library interoperability between Java and Python

Body: I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream that would have done it for me. Thrift or such other libraries is not going to work unless they allow the data format to be xml. I am looking for suggestion for any library that can do it. - Thanks

Body:
I don't think you're likely to find an automated way to serialise Java objects and deserialise into Python objects. They're different things, so if you want to translate, you'll have to write some code at one or both ends.

If it's really simple stuff - strings, numbers, booleans, and so on, then you might want to look into json, a very simple format with bindings for just about every language. Deserialising a json object in Python is as simple as:

json.loads('{"test":false}')

Another way to approach the problem might be to use Jython, an implementation of Python in Java, so you can use Java objects directly.


问:
How to automatically redirect HTTP to HTTPS on Apache servers?
Environment Centos with apache

Trying to setup automatic redirection from http to https

```<code>From manage.mydomain.com --- To ---> https://manage.mydomain.com
</code>```

I have tried adding the following to my httpd.conf but it didn't work

```<code> RewriteEngine on
    ReWriteCond %{SERVER_PORT} !^443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</code>```

Any ideas?

答:
Using mod_rewrite is not the recommended way instead use virtual host and redirect.

In case, if you are inclined to do using mod_rewrite:

```<code>RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same
location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in
# httpd.conf or .htaccess context
</code>```

Reference: Httpd Wiki - RewriteHTTPToHTTPS

If you are looking for a 301 Permanent Redirect, then redirect flag should be as,

```<code> R=301
</code>```

so the RewriteRule will be like,

```<code>RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
</code>```

Body:
Environment Centos with apache

Trying to setup automatic redirection from http to https

From manage.mydomain.com --- To ---> https://manage.mydomain.com

I have tried adding the following to my httpd.conf but it didn't work

 RewriteEngine on
    ReWriteCond %{SERVER_PORT} !^443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

Any ideas?

Body:
Using mod_rewrite is not the recommended way instead use virtual host and redirect.

In case, if you are inclined to do using mod_rewrite:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same
location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in
# httpd.conf or .htaccess context

Reference: Httpd Wiki - RewriteHTTPToHTTPS

If you are looking for a 301 Permanent Redirect, then redirect flag should be as,

 R=301

so the RewriteRule will be like,

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]


问:
Android google maps,google places, northern latitude exceeds southern latitude
I am using google maps and use JSON to parse cafe around my location from google places. When I start navigation to the chosen a cafe from my current location 95% cafe I get a polyline but on some I get error like northern latitude exceeds southern latitude and app crashes.

Here is my logcat:

```<code>07-07 18:11:46.037: E/AndroidRuntime(25854): FATAL EXCEPTION: main
07-07 18:11:46.037: E/AndroidRuntime(25854): java.lang.IllegalArgumentException: southern latitude exceeds northern latitude (30.7223365 > 30.722303)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.internal.fq.a(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.maps.model.LatLngBounds.<init>(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.maps.model.LatLngBounds.<init>(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.example.google_map_ex.MainActivity.findDirections(MainActivity.java:285)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.example.google_map_ex.MainActivity$JSONParse$1.onItemClick(MainActivity.java:366)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AdapterView.performItemClick(AdapterView.java:301)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView.performItemClick(AbsListView.java:1490)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3275)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView$1.run(AbsListView.java:4518)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Handler.handleCallback(Handler.java:725)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Looper.loop(Looper.java:137)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.app.ActivityThread.main(ActivityThread.java:5283)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at java.lang.reflect.Method.invokeNative(Native Method)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at java.lang.reflect.Method.invoke(Method.java:511)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
This exception basically happens while creating LatLngBounds object with wrong LatLng points. southwest Latlong should be first and northwest should be 2nd parameter.
check this link</p>

Body:
I am using google maps and use JSON to parse cafe around my location from google places. When I start navigation to the chosen a cafe from my current location 95% cafe I get a polyline but on some I get error like northern latitude exceeds southern latitude and app crashes.

Here is my logcat:

07-07 18:11:46.037: E/AndroidRuntime(25854): FATAL EXCEPTION: main
07-07 18:11:46.037: E/AndroidRuntime(25854): java.lang.IllegalArgumentException: southern latitude exceeds northern latitude (30.7223365 > 30.722303)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.internal.fq.a(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.maps.model.LatLngBounds.<init>(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.google.android.gms.maps.model.LatLngBounds.<init>(Unknown Source)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.example.google_map_ex.MainActivity.findDirections(MainActivity.java:285)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.example.google_map_ex.MainActivity$JSONParse$1.onItemClick(MainActivity.java:366)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AdapterView.performItemClick(AdapterView.java:301)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView.performItemClick(AbsListView.java:1490)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3275)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.widget.AbsListView$1.run(AbsListView.java:4518)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Handler.handleCallback(Handler.java:725)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.os.Looper.loop(Looper.java:137)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at android.app.ActivityThread.main(ActivityThread.java:5283)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at java.lang.reflect.Method.invokeNative(Native Method)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at java.lang.reflect.Method.invoke(Method.java:511)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-07 18:11:46.037: E/AndroidRuntime(25854):    at dalvik.system.NativeStart.main(Native Method)


问:
location.reload() not working properly in mobile devices
location.reload() not working properly in mobile devices...

location.reload() is working fine on desktop browsers but not working on mobile browsers (android)...

i work in Django selected fileds that come from  ajax selections of modelchoicefields querysets  are lost after window.location.reload().  everthing works fine in desktops but not in mobile devices.

what should i change or add???

you can see the difference in added image...difference between desktop and mobile device working..

code is a standart ajax call for Django to dynamically select fields that are related to the previous selection...

```<code><script>
    function prosecFunction() {
        var response = '';
        var selected = document.getElementById("id_proje").value;
        console.log(selected);
        $.ajax({
          url : "demirbas_ariza_listesi/",
          type : "GET",
          dataType: "text",
          data : {
            'selected' : selected,
              },
          success: function() {
              window.location.reload();
               },
          failure: function() {
              alert("hata var....veri aktarılamadı...");
              }
          });  /* ajax kapa...*/
    }
  </script>

 <script>
</code>```

答:
Try document.location.reload(true); instead of window.location.reload();

```<code>success: function(data){

    document.location.reload(true);

}
</code>```

Body:
Try document.location.reload(true); instead of window.location.reload();

success: function(data){

    document.location.reload(true);

}


问:
Extract dates with javascript and regExp
I have a string  txt='2017-04-01 and 2017-04-04' and i need to get the dates from the string.
I've tried with txt.match(/(\d{4})-(\d{2})-(\d{2})\s+/) but i get:

```<code>[
  "2017-04-01 ",
  "2017",
  "04",
  "01"
]
</code>```

off course that i need

```<code>[
      "2017-04-01",
      "2017-04-04"
    ]
</code>```

Thanks.

答:
The last \s+ requires 1+ whitespaces but the last date is at the end of the string. You may remove \s+ or require a word boundary \b (may be both at the start and end of the pattern). To get all matches, add /g (global) modifier:

txt='2017-04-01 and 2017-04-04';
console.log(txt.match(/\b\d{4}-\d{2}-\d{2}\b/g));```

I removed the capturing groups since you are not expecting those details in your output. If you do, you will need to add them back and use a RegExp#exec in a loop to get all the necessary substrings.

Body:
I have a string  txt='2017-04-01 and 2017-04-04' and i need to get the dates from the string.
I've tried with txt.match(/(\d{4})-(\d{2})-(\d{2})\s+/) but i get:

[
  "2017-04-01 ",
  "2017",
  "04",
  "01"
]

off course that i need

[
      "2017-04-01",
      "2017-04-04"
    ]

Thanks.

Body:
The last \s+ requires 1+ whitespaces but the last date is at the end of the string. You may remove \s+ or require a word boundary \b (may be both at the start and end of the pattern). To get all matches, add /g (global) modifier:

txt='2017-04-01 and 2017-04-04';
console.log(txt.match(/\b\d{4}-\d{2}-\d{2}\b/g));

I removed the capturing groups since you are not expecting those details in your output. If you do, you will need to add them back and use a RegExp#exec in a loop to get all the necessary substrings.


问:
more elegant xpath solution?
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

```<code><ul class="ipsDataItem_stats">
<li>
    <span class="ipsDataItem_stats_number">61</span>
    <span class="ipsDataItem_stats_type"> replies</span>
</li>
<li class="ipsType_light">
    <span class="ipsDataItem_stats_number">6,106</span>
    <span class="ipsDataItem_stats_type"> views</span>
</li>
</code>```

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

```<code>Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text
</code>```

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

```<code>Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})
</code>```

答:
I would tackle this with a 2-step pipeline. The first step would be to transform to a cleaner XML format using XSLT, the second would query that clean XML. The cleaned-up XML for this fragment might look like this:

```<code><ipsDataItem_stats>
  <replies>61</replies>
  <views>6106</views>
</ipsDataItem_stats>
</code>```

The benefit of this approach is that the clean-up phase is completely reusable and independent of the actual queries you want to run; once written, it makes any subsequent queries very much easier to write.

Title: more elegant xpath solution?

Body:
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

    61
     replies

    6,106
     views

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})

Body:
I would tackle this with a 2-step pipeline. The first step would be to transform to a cleaner XML format using XSLT, the second would query that clean XML. The cleaned-up XML for this fragment might look like this:

<ipsDataItem_stats>
  <replies>61</replies>
  <views>6106</views>
</ipsDataItem_stats>

The benefit of this approach is that the clean-up phase is completely reusable and independent of the actual queries you want to run; once written, it makes any subsequent queries very much easier to write.