问:
How do I unload a externally loaded SWF file from a SWFLoader component in Adobe Flex?
I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the SWFLoader Flex component. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:

```<code>swfLoader.source = ""; // Removes the external link to the SWF.
swfLoader.load(null); // Forces the loader to try to load nothing.
// Note: At this point sound from the SWF is still playing, and
// seems to still be playing in memory.
flash.media.SoundMixer.stopAll();
// Stops the sound. This works on my development machine, but not
// on the client's.
</code>```

If the SWFs are closed (hidden) this way, eventually the program crashes.

Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!

Edit 1:  I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?

答:
I'd generally stay away from SWFLoader and use the classes in the mx.modules package. </p>

<p>Flex has a module system that enables this type of behavior. You can check it out here : http://livedocs.adobe.com/flex/3/html/help.html?content=modular_3.html . In general, dynamically loading and unloading swf components is tricky, especially if those modules modify any global state in the application (styles, etc..). But if you create an interface for your modules, and then each class you load/unload implement that interface as well as extend the flex module class, you can load and unload them cleanly. </p>

OwnerDisplayName: Shawn

Body:
I have an application that loads external SWF files and plays them inside a Adobe Flex / Air application via the SWFLoader Flex component. I have been trying to find a way to unload them from a button click event. I have Google'd far and wide and no one seems to have been able to do it without a hack. The combination of code I see people use is:

swfLoader.source = ""; // Removes the external link to the SWF.
swfLoader.load(null); // Forces the loader to try to load nothing.
// Note: At this point sound from the SWF is still playing, and
// seems to still be playing in memory.
flash.media.SoundMixer.stopAll();
// Stops the sound. This works on my development machine, but not
// on the client's.

If the SWFs are closed (hidden) this way, eventually the program crashes.

Any ideas? I have found tons of posts in various forums with people having the same problem. I assume I will get one wrong/incomplete answer here, and than my post will sink into nothingness as usual, but either way, thanks in advance!

Edit 1:  I can't edit the actual SWF movies, they're created by the client. If I can't close any SWF opened through Flex, isn't that a problem with the Flex architecture? Is my only option sending the SWFs to the web browser?

LastEditorDisplayName: Shawn

Body:
I'd generally stay away from SWFLoader and use the classes in the mx.modules package.

Flex has a module system that enables this type of behavior. You can check it out here : http://livedocs.adobe.com/flex/3/html/help.html?content=modular_3.html . In general, dynamically loading and unloading swf components is tricky, especially if those modules modify any global state in the application (styles, etc..). But if you create an interface for your modules, and then each class you load/unload implement that interface as well as extend the flex module class, you can load and unload them cleanly.

OwnerDisplayName: Michael Hoisie


来源: stackexchange

问:
How to make interface in TypeScript?
For example I have this class property:

```<code>public messages : Array<{session: string, messages: [{profile_picture ? : string, type: string, text: string}]}> = []
</code>```

I want to make something like this public messages : MessagesInterface in order to be able to use that interface in different places.

I know that is should like something like this:

```<code>export interface MessagesInterface {
    session: string,
    messages: [{profile_picture ? : string, type: string, text: string}]
}
</code>```

But how to specify that it is array of messages?

答:
You have a couple of options. You can specify an indexable interface as:

```<code>export interface MessagesInterface {
    [key:number]: {
        session: string,
        messages: [{profile_picture ? : string, type: string, text: string}]
    }
}
</code>```

Or instead export a type

```<code>export type MessagesInterface = {
    session: string,
    messages: [{profile_picture ? : string, type: string, text: string}]
}[]
</code>```

I'd still encourage breaking it into multiple interfaces to help readability whichever path you choose.

ContentLicense: CC BY-SA 3.0

Title: How to make interface in TypeScript?

Body:
For example I have this class property:

public messages : Array<{session: string, messages: [{profile_picture ? : string, type: string, text: string}]}> = []

I want to make something like this public messages : MessagesInterface in order to be able to use that interface in different places.

I know that is should like something like this:

export interface MessagesInterface {
    session: string,
    messages: [{profile_picture ? : string, type: string, text: string}]
}

But how to specify that it is array of messages?

Body:
You have a couple of options. You can specify an indexable interface as:

export interface MessagesInterface {
    [key:number]: {
        session: string,
        messages: [{profile_picture ? : string, type: string, text: string}]
    }
}

Or instead export a type

export type MessagesInterface = {
    session: string,
    messages: [{profile_picture ? : string, type: string, text: string}]
}[]

I'd still encourage breaking it into multiple interfaces to help readability whichever path you choose.


问:
Android SQlite: Querying table rows by date range from today backwards?
I get a date from the server in "MM/dd/yyy" form, then I convert it into milliseconds using the following function:

```<code>public static long getSimpleDateToMillis(String simpleDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date date = formatter.parse(simpleDate);
        return date.getTime();
}
</code>```

Then afterwards I save the result into the database as int.

Right now I'm stucked in what seems like a dead-end for me. I can't find a way through searching and from my stock knowledge on how I would be able to filter my cursorloader by project_date column which is saved as integer in the database.

In what way would I be able to query such that it would:
Select all row from projects table where the project_date is today and backwards (yesterday and so on).

I tried this one but seems to be really not the answer.

```<code>String [] projection = new String []{};
        String selection = "datetime("+ ProjectsEntry.COLUMN_PROJECT_DATE + "/1000, 'unixepoch') =? ";
        String [] selectionArgs = new String[]{" date('now')"};
        return new CursorLoader(this,
                JobsContract.JobsEntry.CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                null);
</code>```

I haven't found any other reference that would point me, so I'm hoping someone might also have encountered this perhaps.

答:
This is how I do something quite similar, but using full timesteamp i.e. long rather than int.

First I have this method to get the TimeStamp, to get today's date/time as of midnight (bar 1 millisecond):-

```<code>/**
 *
 * @return  1 millsecond before midnight today
 */
private long getDateTimeOfAllofToday() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH,1); // tomorrow
    cal.set(Calendar.MILLISECOND,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.HOUR_OF_DAY,0);
    cal.add(Calendar.MILLISECOND,-1);
    return cal.getTimeInMillis();
}
</code>```

Then I create the respective where clause e.g. :-

```<code>filter = DBRulesTableConstants.RULES_ACTON_COL +
        " <= " +
        Long.toString(getDateTimeOfAllofToday());
</code>```

This is used via a rawQuery so not exactly what you want but easy enough to to change " <= " to " <=?" and then use
 String [] selectionArgs = new String[]{Long.toString(getDateTimeOfAllofToday())}; or a modified version to get integer.

Body:
I get a date from the server in "MM/dd/yyy" form, then I convert it into milliseconds using the following function:

public static long getSimpleDateToMillis(String simpleDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date date = formatter.parse(simpleDate);
        return date.getTime();
}

Then afterwards I save the result into the database as int.

Right now I'm stucked in what seems like a dead-end for me. I can't find a way through searching and from my stock knowledge on how I would be able to filter my cursorloader by project_date column which is saved as integer in the database.

In what way would I be able to query such that it would:
Select all row from projects table where the project_date is today and backwards (yesterday and so on).

I tried this one but seems to be really not the answer.

String [] projection = new String []{};
        String selection = "datetime("+ ProjectsEntry.COLUMN_PROJECT_DATE + "/1000, 'unixepoch') =? ";
        String [] selectionArgs = new String[]{" date('now')"};
        return new CursorLoader(this,
                JobsContract.JobsEntry.CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                null);

I haven't found any other reference that would point me, so I'm hoping someone might also have encountered this perhaps.

Body:
This is how I do something quite similar, but using full timesteamp i.e. long rather than int.

First I have this method to get the TimeStamp, to get today's date/time as of midnight (bar 1 millisecond):-

/**
 *
 * @return  1 millsecond before midnight today
 */
private long getDateTimeOfAllofToday() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH,1); // tomorrow
    cal.set(Calendar.MILLISECOND,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.HOUR_OF_DAY,0);
    cal.add(Calendar.MILLISECOND,-1);
    return cal.getTimeInMillis();
}

Then I create the respective where clause e.g. :-

filter = DBRulesTableConstants.RULES_ACTON_COL +
        " <= " +
        Long.toString(getDateTimeOfAllofToday());

This is used via a rawQuery so not exactly what you want but easy enough to to change " <= " to " <=?" and then use
 String [] selectionArgs = new String[]{Long.toString(getDateTimeOfAllofToday())}; or a modified version to get integer.


问:
How to draw/Form circle with two points?
I need to draw a circle and i have only two points.Now i need to find center point and radius of the circle?  You can form the circle in clock wise direction.

Thanks in advance

答:
No that is impossible.

Create two circles with the same radius at centerpoints A + B. At the intersection of these two circles create an circle with the same radius....

Then make the same with an other radius....


问:
Customizing Zuul Exception
I have a scenario in Zuul where the service that the URL is routed too might be down . So the reponse body gets thrown with 500 HTTP Status and ZuulException in the JSON body response.

```<code>{
  "timestamp": 1459973637928,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "com.netflix.zuul.exception.ZuulException",
  "message": "Forwarding error"
}
</code>```

All I want to do is to customise or remove the JSON response and maybe change the HTTP status Code.

I tried to create a exception Handler with @ControllerAdvice but the exception is not grabbed by the handler.

UPDATES:

So I extended the Zuul Filter I can see it getting into the run method after the error has been executed how do i change the response then. Below is what i got so far. I read somewhere about SendErrorFilter but how do i implement that and what does it do?

```<code>public class CustomFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {

        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        final RequestContext ctx = RequestContext.getCurrentContext();
        final HttpServletResponse response = ctx.getResponse();
        if (HttpStatus.INTERNAL_SERVER_ERROR.value() == ctx.getResponse().getStatus()) {
            try {
                response.sendError(404, "Error Error"); //trying to change the response will need to throw a JSON body.
            } catch (final IOException e) {
                e.printStackTrace();
            } ;
        }

        return null;
    }
</code>```

Added this to the class that has @EnableZuulProxy

```<code>@Bean
public CustomFilter customFilter() {
    return new CustomFilter();
}
</code>```

答:
I had the same problem and was able to solve it in simpler way

Just put this into you Filter run() method

```<code>    if (<your condition>) {
        ZuulException zuulException = new ZuulException("User message", statusCode, "Error Details message");
        throw new ZuulRuntimeException(zuulException);
    }
</code>```

and SendErrorFilter will deliver to the user the message with the desired statusCode.

This Exception in an Exception pattern does not look exactly nice, but it works here.

Title: Customizing Zuul Exception

Body:
I have a scenario in Zuul where the service that the URL is routed too might be down . So the reponse body gets thrown with 500 HTTP Status and ZuulException in the JSON body response.

{
  "timestamp": 1459973637928,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "com.netflix.zuul.exception.ZuulException",
  "message": "Forwarding error"
}

All I want to do is to customise or remove the JSON response and maybe change the HTTP status Code.

I tried to create a exception Handler with @ControllerAdvice but the exception is not grabbed by the handler.

UPDATES:

So I extended the Zuul Filter I can see it getting into the run method after the error has been executed how do i change the response then. Below is what i got so far. I read somewhere about SendErrorFilter but how do i implement that and what does it do?

public class CustomFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {

        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        final RequestContext ctx = RequestContext.getCurrentContext();
        final HttpServletResponse response = ctx.getResponse();
        if (HttpStatus.INTERNAL_SERVER_ERROR.value() == ctx.getResponse().getStatus()) {
            try {
                response.sendError(404, "Error Error"); //trying to change the response will need to throw a JSON body.
            } catch (final IOException e) {
                e.printStackTrace();
            } ;
        }

        return null;
    }

Added this to the class that has @EnableZuulProxy

@Bean
public CustomFilter customFilter() {
    return new CustomFilter();
}

Body:
I had the same problem and was able to solve it in simpler way

Just put this into you Filter run() method

    if (<your condition>) {
        ZuulException zuulException = new ZuulException("User message", statusCode, "Error Details message");
        throw new ZuulRuntimeException(zuulException);
    }

and SendErrorFilter will deliver to the user the message with the desired statusCode.

This Exception in an Exception pattern does not look exactly nice, but it works here.


问:
Android- How to create 4 square buttons in one row with icons on top of them?
Im trying to create an app which will have 4 square buttons in one row with an icon on top of these buttons. Which is the best way to approach this? I'm trying to do something like this as shown in the image

Thank You

答:
Set your drawable image on place of <strong>@mipmap/ic_launcher_round</strong> </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="4sp"
        android:orientation="horizontal"
        android:weightSum="4">

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

    </LinearLayout>

</LinearLayout>
</code>```

Body:
Set your drawable image on place of @mipmap/ic_launcher_round

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="4sp"
        android:orientation="horizontal"
        android:weightSum="4">

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4sp"
            android:layout_weight="1"
            android:src="@mipmap/ic_launcher_round" />

    </LinearLayout>

</LinearLayout>


问:
Specify generic type parameter in Scala
I'm new to Scala and have generic method written in Java:

```<code>public interface Context{
    <T> Optional<T> get(String parameterName);
}
</code>```

and Scala class:

```<code>class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}
</code>```

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

答:
asInstanceOf[Optional[String]] is just incorrect in this case, even though it happens to work due to type erasure. To specify the parameter directly you'd write

```<code>ctx.get[String]("str")
</code>```

which is the direct equivalent to ctx.<String> get("str") in Java.

Title: Specify generic type parameter in Scala

Body:
I'm new to Scala and have generic method written in Java:

public interface Context{
    <T> Optional<T> get(String parameterName);
}

and Scala class:

class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

Body:
asInstanceOf[Optional[String]] is just incorrect in this case, even though it happens to work due to type erasure. To specify the parameter directly you'd write

ctx.get[String]("str")

which is the direct equivalent to ctx.<String> get("str") in Java.


问:
Javascript error "Cannot set property 'value' of null'
```<code><body onload="UserAction()">

<form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo"  id="rollNo"><br>
    Name: <input type="text" name="name" id="name"><br>
    <br>

<script type="text/javascript" language="javascript">
        function UserAction() {

            var rollNo = parseInt(localStorage.getItem("rollNo"));
            document.write(rollNo);
            document.getElementById("rollNo").value = rollNo;
        }
</script>
</code>```

The rollNo value gets printed but while assigning it to the textbox it gives me an error.

答:
You have replaced the entire HTML from the page when you do

document.write(rollNo);

If your rollNo is say, 10 then you will get

```<code><body>10</body>
</code>```

rendered in the browser when your UserAction() function is invoked. So you need to remove this line document.write(rollNo); so that the next line document.getElementById("rollNo") can find the element with id as rollNo. So you UserAction() becomes,

function UserAction() {
  //get roll no from localstorage
  var rollNo = 10;
  document.getElementById("rollNo").value = rollNo;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="UserAction()">

  <form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo" id="rollNo"><br> Name: <input type="text" name="name" id="name"><br>
    <br>
  </form>

</body></code>```

And in this way when the element is detected by document.getElementById("rollNo") you will not get the error "Cannot set property 'value' of null'

Body:
<form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo"  id="rollNo">

    Name: <input type="text" name="name" id="name">

The rollNo value gets printed but while assigning it to the textbox it gives me an error.

Body:
You have replaced the entire HTML from the page when you do

document.write(rollNo);

If your rollNo is say, 10 then you will get

<body>10</body>

rendered in the browser when your UserAction() function is invoked. So you need to remove this line document.write(rollNo); so that the next line document.getElementById("rollNo") can find the element with id as rollNo. So you UserAction() becomes,

function UserAction() {
  //get roll no from localstorage
  var rollNo = 10;
  document.getElementById("rollNo").value = rollNo;
}

<body onload="UserAction()">

  <form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo" id="rollNo"><br> Name: <input type="text" name="name" id="name"><br>
    <br>
  </form>

</body>

And in this way when the element is detected by document.getElementById("rollNo") you will not get the error "Cannot set property 'value' of null'

ContentLicense: CC BY-SA 4.0


问:
Mediawiki won't work because of httpd start error
My mediawiki install in httpd server for more than two years，today I get the following error when i restart httpd

```<code>    Unable to verify certificate 'Server-Cert'. Add "NSSEnforceValidCerts off" to nss.conf so the server can start until the problem can be resolved.
</code>```

I solve this by add NSSEnforceValidCerts off in nss.conf in the conf.d folder.But   httpd still won't start with  following error:

```<code>   [warn] _default_ VirtualHost overlap on port 8443, the first has precedence (98)Address already in use: make_sock: could not bind to address 8443
</code>```

how to solve it? thanks

答:
Solution in my case was to comment the following lines out of the /etc/httpd/conf.d/nss.conf file:

```<code>#LoadModule nss_module modules/libmodnss.so
#Listen 8443
</code>```

service httpd start
and it works again!
thanks for all!

Body:
My mediawiki install in httpd server for more than two years，today I get the following error when i restart httpd

    Unable to verify certificate 'Server-Cert'. Add "NSSEnforceValidCerts off" to nss.conf so the server can start until the problem can be resolved.

I solve this by add NSSEnforceValidCerts off in nss.conf in the conf.d folder.But   httpd still won't start with  following error:

   [warn] _default_ VirtualHost overlap on port 8443, the first has precedence (98)Address already in use: make_sock: could not bind to address 8443

how to solve it? thanks

Body:
Solution in my case was to comment the following lines out of the /etc/httpd/conf.d/nss.conf file:

#LoadModule nss_module modules/libmodnss.so
#Listen 8443

service httpd start
and it works again!
thanks for all!


问:
Why to use websocket and what is the advantage of using it?
I tried reading some articles, but not so clear on this topic.

Would someone like to explain me below points:

Why use websocket over http

what is full duplex communication

what do you mean by lower latency interaction

答:
Why use websocket over http?

A webSocket is a continuous connection between client and server.  That continuous connection allows the following:

Data can be sent from server to client at any time, without the client even requesting it.  This is often called server-push and is very valuable for applications where the client needs to know fairly quickly when something happens on the server (like a new chat messages has been received or a new price has been udpated).  A client cannot be pushed data over http.  The client would have to regularly poll by making an http request every few seconds in order to get timely new data.  Client polling is not efficient.

Data can be sent either way very efficiently.  Because the connection is already established and a webSocket data frame is very efficiently organized (mostly 6 extra bytes, 2 bytes for header and 4 bytes for Mask), one can send data a lot more efficiently than via a HTTP request that necessarily contains headers, cookies etc...

what is full duplex communication?

Full duplex means that data can be sent either way on the connection at any time.

what do you mean by lower latency interaction

Low latency means that there is very little delay between the time you request something and the time you get a response.  As it applies to webSockets, it just means that data can be sent quicker (particularly over slow links) because the connection has already been established so no extra packet roundtrips are required to establish the TCP connection.

For a comparison in what's involved to send some data via an http request vs. an already established webSocket connection see the steps listed in this answer: websocket vs rest API for real time data?

These other references may also be useful:

Server-push whenever a function is called: Ajax or WebSockets

For a push notification, is a websocket mandatory?

HTML5 WebSocket: A Quantum Leap in Scalability for the Web


问:
issue with calculating percentage in postgresql
This is my query. which each query (counter,denominator) works good alone. when I'm trying to devide these 2 queries I'm getting this
 ERROR: syntax error at or near "/"
I'm trying to get % of total price in the first 3 months of 2016 (SPORT & MUSIC) from total price of all 2016 in the same departments

```<code>(SELECT "Total Price"
FROM "Sales"
WHERE "Department" IN('SPORT','MUSIC')
AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31')/(SELECT "Total Price"
FROM "Sales"
WHERE "Department" IN('SPORT','MUSIC')
AND "DATE" BETWEEN '2016-01-01' AND '2016-12-31') AS percentage
</code>```

答:
I guess you mean something like

```<code>SELECT
   "Total Price"/(sum("Total Price") OVER ()) * 100.0 AS percentage
FROM "Sales"
WHERE "Department" IN ('SPORT','MUSIC')
  AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31';
</code>```

Do yourself a favour and avoid names with upper or mixed case and non-alphanumeric characters.

Body:
This is my query. which each query (counter,denominator) works good alone. when I'm trying to devide these 2 queries I'm getting this
 ERROR: syntax error at or near "/"
I'm trying to get % of total price in the first 3 months of 2016 (SPORT & MUSIC) from total price of all 2016 in the same departments

(SELECT "Total Price"
FROM "Sales"
WHERE "Department" IN('SPORT','MUSIC')
AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31')/(SELECT "Total Price"
FROM "Sales"
WHERE "Department" IN('SPORT','MUSIC')
AND "DATE" BETWEEN '2016-01-01' AND '2016-12-31') AS percentage

Body:
I guess you mean something like

SELECT
   "Total Price"/(sum("Total Price") OVER ()) * 100.0 AS percentage
FROM "Sales"
WHERE "Department" IN ('SPORT','MUSIC')
  AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31';

Do yourself a favour and avoid names with upper or mixed case and non-alphanumeric characters.


问:
Summernote airmode: Trigger airmode on click, not on select
I'm using summernote airmode to create inline editor, but currently its only shows the editor when user select/highlight the text (see pict). What I want is to trigger the airmode editor when on focus/click then text (not selecting it). I don't know how to do this, please help.

This is my current summernote airmode: here

HTML

```<code><div id="test">
   <h1>Hello, I'm calvanery</h1>
   <h4>Select me</h4>
</div>
</code>```

Javascript

```<code><script>
  $('#test').summernote({
    airMode: true,
    callbacks: {
             onFocus: function () {
             console.log('Editable area is focused');

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

Thanks in advance

答:
Try this,

Add onFocus in Summernote options:

```<code>callbacks: {
   onFocus: function () {
       $(this).next().find(".note-editable").selectText();
   }
}
</code>```

Jquery selectText addon:

```<code>jQuery.fn.selectText = function () {
    var doc = document;
    var element = this[0];
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    }
    else if (window.getSelection) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};
</code>```

This will select the text on click, and it will open the popover.

Body:
I'm using summernote airmode to create inline editor, but currently its only shows the editor when user select/highlight the text (see pict). What I want is to trigger the airmode editor when on focus/click then text (not selecting it). I don't know how to do this, please help.

This is my current summernote airmode: here

HTML

Hello, I'm calvanery

Select me

Javascript

Thanks in advance

Body:
Try this,

Add onFocus in Summernote options:

callbacks: {
   onFocus: function () {
       $(this).next().find(".note-editable").selectText();
   }
}

Jquery selectText addon:

jQuery.fn.selectText = function () {
    var doc = document;
    var element = this[0];
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    }
    else if (window.getSelection) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

This will select the text on click, and it will open the popover.


问:
Is there any alternate to acquire dependencies without using POM.xml?
My question is, I don't want to write XML code for dependencies in the POM.xml again and again.
For example, I want to use the log4j JAR in my project. instead of writing XML code is there any option to download the related JAR files?

答: You do not need to write them again and again. You can define and install a parent pom with the common dependencies you use and refer to it in each project pom. </p>


问:
How to return a value of a register from ARM assembly to a C function?
for example

```<code>extern int addfunction(int,int);
main() {
  int a = 5, b = 6, z;
  z = addfunction(a, b);
  printf("%d", c);
}
</code>```

addfunction()'s defintion in another .s file like

```<code>.global addfunction
addfunction:
    @ value a will be in R0 & R1 respectively
    add r2, r0, r1    @ r2=r0+r1
</code>```

Now how to return value stored r2 so that variable z in the C program will get correct the value? I am able to do with pointer from C and update the address in asm. I don't want this way. Help!

答:
Look here

The standard 32-bit ARM calling convention allocates the 16 ARM registers as:

r0 to r3: used to hold argument values passed to a subroutine, and also hold results returned from a subroutine.

So set r0 to the return value

```<code>.global addfunction
addfunction:
    @ value a will be in R0 & R1 respectively
    add r0, r0, r1    @ r0=r0+r1
</code>```

Body:
for example

extern int addfunction(int,int);
main() {
  int a = 5, b = 6, z;
  z = addfunction(a, b);
  printf("%d", c);
}

addfunction()'s defintion in another .s file like

.global addfunction
addfunction:
    @ value a will be in R0 & R1 respectively
    add r2, r0, r1    @ r2=r0+r1

Now how to return value stored r2 so that variable z in the C program will get correct the value? I am able to do with pointer from C and update the address in asm. I don't want this way. Help!

Body:
Look here

The standard 32-bit ARM calling convention allocates the 16 ARM registers as:

r0 to r3: used to hold argument values passed to a subroutine, and also hold results returned from a subroutine.

So set r0 to the return value

.global addfunction
addfunction:
    @ value a will be in R0 & R1 respectively
    add r0, r0, r1    @ r0=r0+r1


问:
Beginner Java - Changing String from First Middle Last to Last, First Middle
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -7
</code>```

and

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -1
</code>```

when the name is Sarah

This is my code, but I'm not sure how to fix it:

```<code>public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}
</code>```

Thanks in advance!!

答:
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.

```<code>public static String lastNameFirst(String name)
{
  int firstIndex = name.indexOf(" ");
  if ( firstIndex >= 0 )
  {
    int secondIndex = name.indexOf(" ", firstIndex + 1 );
    String firstName = name.substring(0, firstIndex);
    if ( secondIndex >= 0 ) // we have 3 names
    {
      String middleName = name.substring(firstIndex + 1, secondIndex);
      String lastName = name.substring(secondIndex + 1);
      return lastName + ", " + firstName + " " + middleName;
    }
    else // we have 2 names
    {
      String lastName = name.substring(firstIndex + 1);
      return lastName + ", " + firstName;
    }
  }
  else // have only one name
    return name;
}
</code>```

Should worth trying lastIndexOf(), too:

```<code>public static String lastNameFirst(String name)
{
  int lastIndex = name.lastIndexOf(" ");
  if ( lastIndex >= 0 ) // have at least 2 names
  {
      String firstNames = name.substring(0,lastIndex);
      String lastName = name.substring(lastIndex + 1);
      return lastName + ", " + firstNames;
    }
  }
  else // have only one name
    return name;
}
</code>```

Also, could try a different approach, split the name into an array, something like this:

```<code>public static String lastNameFirst(String name)
{
  String[] parts = name.split(" ");
  switch ( parts.length )
  {
    case 1:
      return name;
    case 2:
      return parts[1] + ", " + parts[0];
    case 3:
      return parts[2] + ", " + parts[0] + " " + parts[1];
  }
}
</code>```

Body:
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

java.lang.StringIndexOutOfBoundsException: String index out of range: -7

and

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

when the name is Sarah

This is my code, but I'm not sure how to fix it:

public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}

Thanks in advance!!

Body:
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.

public static String lastNameFirst(String name)
{
  int firstIndex = name.indexOf(" ");
  if ( firstIndex >= 0 )
  {
    int secondIndex = name.indexOf(" ", firstIndex + 1 );
    String firstName = name.substring(0, firstIndex);
    if ( secondIndex >= 0 ) // we have 3 names
    {
      String middleName = name.substring(firstIndex + 1, secondIndex);
      String lastName = name.substring(secondIndex + 1);
      return lastName + ", " + firstName + " " + middleName;
    }
    else // we have 2 names
    {
      String lastName = name.substring(firstIndex + 1);
      return lastName + ", " + firstName;
    }
  }
  else // have only one name
    return name;
}

Should worth trying lastIndexOf(), too:

public static String lastNameFirst(String name)
{
  int lastIndex = name.lastIndexOf(" ");
  if ( lastIndex >= 0 ) // have at least 2 names
  {
      String firstNames = name.substring(0,lastIndex);
      String lastName = name.substring(lastIndex + 1);
      return lastName + ", " + firstNames;
    }
  }
  else // have only one name
    return name;
}

Also, could try a different approach, split the name into an array, something like this:

public static String lastNameFirst(String name)
{
  String[] parts = name.split(" ");
  switch ( parts.length )
  {
    case 1:
      return name;
    case 2:
      return parts[1] + ", " + parts[0];
    case 3:
      return parts[2] + ", " + parts[0] + " " + parts[1];
  }
}


问:
Google Dagger com.android.support:support-v4 dependency versions
In an app compiling against Api 23 (6.0), I get a warning in the build.gradle file that "All com.android.support libraries must use the exact same version specification" and that versions 24.2.0 & 23.1.1 were found.

My com.android.support dependencies all specify 23.1.1 but running:

```<code>gradlew -q dependencies app:dependencies --configuration compile
</code>```

shows that these are all upgraded to 24.2.0.

The only exception to this is

```<code>com.google.dagger:dagger-android:2.9
</code>```

which appears to be dependent on

```<code>com.android.support:support-v4:24.2.0
</code>```

Excerpts from gradlew dependency report:

```<code>+--- project :AppCommon
|    +--- com.android.support:appcompat-v7:23.1.1
|    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0
|    |         +--- com.android.support:support-compat:24.2.0
|    |         |    \--- com.android.support:support-annotations:24.2.0
|    |         +--- com.android.support:support-core-utils:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         +--- com.android.support:support-media-compat:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         +--- com.android.support:support-core-ui:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         \--- com.android.support:support-fragment:24.2.0
|    |              +--- com.android.support:support-compat:24.2.0 (*)
|    |              +--- com.android.support:support-core-utils:24.2.0 (*)
|    |              +--- com.android.support:support-media-compat:24.2.0 (*)
|    |              \--- com.android.support:support-core-ui:24.2.0 (*)
|    +--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)
|    +--- com.android.support:design:23.1.1
|    |    +--- com.android.support:appcompat-v7:23.1.1 (*)
|    |    +--- com.android.support:recyclerview-v7:23.1.1
|    |    |    +--- com.android.support:support-annotations:23.1.1 -> 24.2.0
|    |    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)
|    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)

|    \--- com.google.dagger:dagger-android:2.9
|         +--- com.google.dagger:dagger:2.9 (*)
|         +--- com.android.support:support-v4:24.2.0 (*)
|         \--- com.android.support:support-annotations:24.2.0
</code>```

How can I resolve this dependency clash other than by changing compiling against api 24 (and changing all my com.android.support versions to 24.2.0)?

答:
Update Gradle plugin to

```<code>classpath 'com.android.tools.build:gradle:2.3.3'
</code>```

Change the gradle compile sdk version, buildtool version and target sdk version to a updated one.

For sample,

```<code>compileSdkVersion 25
buildToolsVersion "25.0.3"
targetSdkVersion 25
</code>```

And change the gradle dependency to the same version of builtoolversion

```<code>compile 'com.android.support:support-compat:25.3.1'
compile 'com.android.support:support-media-compat:25.3.1'
compile 'com.android.support:support-core-ui:25.3.1'
compile 'com.android.support:support-fragment:25.3.1'
compile 'com.android.support:support-core-utils:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.google.dagger:dagger:2.0.2'
compile 'com.google.dagger:dagger-compiler:2.0.2'
</code>```

You must use the dagger dependency as

```<code>compile 'com.google.dagger:dagger:2.0.2'
compile 'com.google.dagger:dagger-compiler:2.0.2'
</code>```

instead of

```<code>com.google.dagger:dagger-android:2.9
com.google.dagger:dagger:2.9
</code>```

Body:
In an app compiling against Api 23 (6.0), I get a warning in the build.gradle file that "All com.android.support libraries must use the exact same version specification" and that versions 24.2.0 & 23.1.1 were found.

My com.android.support dependencies all specify 23.1.1 but running:

gradlew -q dependencies app:dependencies --configuration compile

shows that these are all upgraded to 24.2.0.

The only exception to this is

com.google.dagger:dagger-android:2.9

which appears to be dependent on

com.android.support:support-v4:24.2.0

Excerpts from gradlew dependency report:

+--- project :AppCommon
|    +--- com.android.support:appcompat-v7:23.1.1
|    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0
|    |         +--- com.android.support:support-compat:24.2.0
|    |         |    \--- com.android.support:support-annotations:24.2.0
|    |         +--- com.android.support:support-core-utils:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         +--- com.android.support:support-media-compat:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         +--- com.android.support:support-core-ui:24.2.0
|    |         |    \--- com.android.support:support-compat:24.2.0 (*)
|    |         \--- com.android.support:support-fragment:24.2.0
|    |              +--- com.android.support:support-compat:24.2.0 (*)
|    |              +--- com.android.support:support-core-utils:24.2.0 (*)
|    |              +--- com.android.support:support-media-compat:24.2.0 (*)
|    |              \--- com.android.support:support-core-ui:24.2.0 (*)
|    +--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)
|    +--- com.android.support:design:23.1.1
|    |    +--- com.android.support:appcompat-v7:23.1.1 (*)
|    |    +--- com.android.support:recyclerview-v7:23.1.1
|    |    |    +--- com.android.support:support-annotations:23.1.1 -> 24.2.0
|    |    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)
|    |    \--- com.android.support:support-v4:23.1.1 -> 24.2.0 (*)

|    \--- com.google.dagger:dagger-android:2.9
|         +--- com.google.dagger:dagger:2.9 (*)
|         +--- com.android.support:support-v4:24.2.0 (*)
|         \--- com.android.support:support-annotations:24.2.0

How can I resolve this dependency clash other than by changing compiling against api 24 (and changing all my com.android.support versions to 24.2.0)?

Body:
Update Gradle plugin to

classpath 'com.android.tools.build:gradle:2.3.3'

Change the gradle compile sdk version, buildtool version and target sdk version to a updated one.

For sample,

compileSdkVersion 25
buildToolsVersion "25.0.3"
targetSdkVersion 25

And change the gradle dependency to the same version of builtoolversion

compile 'com.android.support:support-compat:25.3.1'
compile 'com.android.support:support-media-compat:25.3.1'
compile 'com.android.support:support-core-ui:25.3.1'
compile 'com.android.support:support-fragment:25.3.1'
compile 'com.android.support:support-core-utils:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-annotations:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.google.dagger:dagger:2.0.2'
compile 'com.google.dagger:dagger-compiler:2.0.2'

You must use the dagger dependency as

compile 'com.google.dagger:dagger:2.0.2'
compile 'com.google.dagger:dagger-compiler:2.0.2'

instead of

com.google.dagger:dagger-android:2.9
com.google.dagger:dagger:2.9


问:
How to save IP of user after submitting the django custom form
I wrote my own form for editing of profile and need to save ip of user, who edit profile, but not really understand how to do this. I know, that ip we can get from request.META['REMORE_ADDR'] but where to put this and how to save to my db... Will be very glad if you could help.

models.py

```<code>class Profile(models.Model):
   user = models.OneToOneField(User, unique=True)
   first_name = models.CharField(max_length=200)
   last_name = models.CharField(max_length=200)
   date_of_birth = models.DateField()
   biography = models.TextField()
   contacts = models.CharField(max_length=200)
   ip_address = models.GenericIPAddressField(null=True)
</code>```

forms.py

```<code>class UserEditProfile(forms.ModelForm):
    first_name = forms.CharField( max_length=30)
    last_name = forms.CharField( max_length=30)
    date_of_birth =
    forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    biography = forms.Textarea()
    contacts = forms.CharField()

    def __init__(self, *args, **kw):
        super(UserEditProfile, self).__init__(*args, **kw)
        self.fields['first_name'].initial = self.instance.first_name
        self.fields['last_name'].initial = self.instance.last_name
        self.fields['date_of_birth'].initial =
        self.instance.date_of_birth
        self.fields['biography'].initial = self.instance.biography
        self.fields['contacts'].initial = self.instance.contacts

        self.fields.keyOrder = [
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
            ]

    def save(self, *args, **kw):
        super(UserEditProfile, self).save(*args, **kw)
        self.instance.first_name = self.cleaned_data.get('first_name')
        self.instance.last_name = self.cleaned_data.get('last_name')
        self.instance.date_of_birth =
        self.cleaned_data.get('date_of_birth')
        self.instance.biography = self.cleaned_data.get('biography')
        self.instance.contacts = self.cleaned_data.get('contacts')
        self.instance.save()

    class Meta:
        model = Profile
        fields = (
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
        )
        exclude = ['user', 'ip_address']
</code>```

view.py

```<code>def edit_profile(request):
    user = Profile.objects.get(id=request.user.id)

    if request.method == "POST":
        form = UserEditProfile(request.POST, instance=user)

        if form.is_valid():
            form.save(commit=False)
            return redirect('profile')
    else:
        form = UserEditProfile(instance=user)
        args = {'form': form}
        return render(request, 'edit.html', args)
</code>```

答:
You cannot pass request object into form directly. That's not the way it works. If you need to associate any request attributes to your model instances, you should do it in the views.

You could collect the request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to yourinstance` in the view itself.

You could do this in your form.is_valid() method,

```<code>if form.is_valid():
    profile = form.save(commit=False)
    profile.ip_address = request.META['REMOTE_ADDR']
    profile.user = request.user
    profile.save()
    return redirect('profile')
</code>```

Body:
I wrote my own form for editing of profile and need to save ip of user, who edit profile, but not really understand how to do this. I know, that ip we can get from request.META['REMORE_ADDR'] but where to put this and how to save to my db... Will be very glad if you could help.

models.py

class Profile(models.Model):
   user = models.OneToOneField(User, unique=True)
   first_name = models.CharField(max_length=200)
   last_name = models.CharField(max_length=200)
   date_of_birth = models.DateField()
   biography = models.TextField()
   contacts = models.CharField(max_length=200)
   ip_address = models.GenericIPAddressField(null=True)

forms.py

class UserEditProfile(forms.ModelForm):
    first_name = forms.CharField( max_length=30)
    last_name = forms.CharField( max_length=30)
    date_of_birth =
    forms.DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES))
    biography = forms.Textarea()
    contacts = forms.CharField()

    def __init__(self, *args, **kw):
        super(UserEditProfile, self).__init__(*args, **kw)
        self.fields['first_name'].initial = self.instance.first_name
        self.fields['last_name'].initial = self.instance.last_name
        self.fields['date_of_birth'].initial =
        self.instance.date_of_birth
        self.fields['biography'].initial = self.instance.biography
        self.fields['contacts'].initial = self.instance.contacts

        self.fields.keyOrder = [
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
            ]

    def save(self, *args, **kw):
        super(UserEditProfile, self).save(*args, **kw)
        self.instance.first_name = self.cleaned_data.get('first_name')
        self.instance.last_name = self.cleaned_data.get('last_name')
        self.instance.date_of_birth =
        self.cleaned_data.get('date_of_birth')
        self.instance.biography = self.cleaned_data.get('biography')
        self.instance.contacts = self.cleaned_data.get('contacts')
        self.instance.save()

    class Meta:
        model = Profile
        fields = (
            'first_name',
            'last_name',
            'date_of_birth',
            'biography',
            'contacts'
        )
        exclude = ['user', 'ip_address']

view.py

def edit_profile(request):
    user = Profile.objects.get(id=request.user.id)

    if request.method == "POST":
        form = UserEditProfile(request.POST, instance=user)

        if form.is_valid():
            form.save(commit=False)
            return redirect('profile')
    else:
        form = UserEditProfile(instance=user)
        args = {'form': form}
        return render(request, 'edit.html', args)

Body:
You cannot pass request object into form directly. That's not the way it works. If you need to associate any request attributes to your model instances, you should do it in the views.

You could collect the request.META['REMOTE_ADDR'] which gives the IP info of the logged in user in the view and associate it to yourinstance` in the view itself.

You could do this in your form.is_valid() method,

if form.is_valid():
    profile = form.save(commit=False)
    profile.ip_address = request.META['REMOTE_ADDR']
    profile.user = request.user
    profile.save()
    return redirect('profile')


问:
Bootstrap Scroll Spy highlights wrong id
i need help with my bootstrap scrollspy setting. It is highlighting the wrong div id (always the last one). Anyone can help me, please?

Code:

content:

```<code><body style="heigt: 100%" data-spy="scroll" data-target="#side-menu">
    <div class="container-fluid">
      <div class="row">
        <nav id="side-menu" class="col-xs-3 bs-docs-sidebar" data-gumshoe-header>
            <ul class="nav nav-stacked fixed" data-gumshoe>
                <li>
                    <a href="#GroupA">Group A</a>
                </li>
                <li>
                    <a href="#GroupB">Group B</a>
                </li>
                <li>
                    <a href="#GroupC">Group C</a>
                </li>
            </ul>
        </nav>
        <div class="col-md-9">
          <div id="GroupA">
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <br><br><br><br><br><br><br><br><br>
    <div id="GroupB">
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <br><br><br><br><br><br><br><br><br>
    <div id="GroupC">
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
        </div>
      </div>
    </div>
</body>
</code>```

// Edit: Picture of page

I am using Bootstrap 3.3.7 and JQuery 2.2.4.

Regards

答:
Scrolled element should be position: relative style.

Ref: http://getbootstrap.com/javascript/#requires-relative-positioning

Edit

Your divs height are too small. Scroll area is to short for scroll-spy.

Working fiddle: https://jsfiddle.net/o93q4maf/

Edit2

As @Lars mentioned the problem was a typo: style="heigt: 100%" instead of style="height: 100%" in body element.

Body:
i need help with my bootstrap scrollspy setting. It is highlighting the wrong div id (always the last one). Anyone can help me, please?

Code:

content:

                    Group A

                    Group B

                    Group C

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

// Edit: Picture of page

I am using Bootstrap 3.3.7 and JQuery 2.2.4.

Regards


问:
How do I pass value from Jquery to PHP ? HTML is a hidden input form field
I have a form:

```<code><form action="post.php" method="POST">
 <p class="select1">Northern Cape</p>
 <p class="select1">Eastern Cape</p>

 <p class="select2" >New Goods</p>
 <p class="select2" >Used Goods</p>

<input id="submt" type="submit" name="submit" value="Submit">
</form>
</code>```

JQUERY .... appends input/value to the selected items:

```<code>$(document).ready(function() {
    $('.select1').click(function() {
      if ($(this).text() == "Northern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Northern Cape' />");
          $("#firstloc").val('Northern Cape');
     }; // end of if statement

      if ($(this).text() == "Eastern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Eastern Cape' />");
          $("#firstloc").val('Eastern Cape');
     }; // end of if statement
}); // end of click function
}); // end of document ready

 $(document).ready(function() {
    $('.select2').click(function() {
        if ($(this).text() == "New Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='New Goods' />");
            $(this).val('New Goods');
         };

        if ($(this).text() == "Used Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='Used Goods' />");
            $("#category").val('Used Goods');
         };

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

How do I pass the values to PHP ie. first value Province second value Category?

```<code><?php

$province = $_POST['province'];
$category = $_POST['cat'];
echo $province;
echo $category;
?>
</code>```

I get a message Undefined index:cat when passing to PHP.
User must select 2 items and values must be passed to PHP,I do not want to use a drop down menu with "options"

答:
Here is the solution.

You made a several mistakes in your code.

You are using ; after if statement

You didnot close $document.ready tag properly

You have to check in your post.php if data posted or not

And you only appends input type hidden you weren't remove it.

post.php

```<code><?php
$province = '';
$category = '';
if(isset($_POST['province'])):
    $province = $_POST['province'];
endif;
if(isset($_POST['cat'])):
    $category = $_POST['cat'];
endif;
echo $province;
echo $category;
?>
</code>```

$(document).ready(function() {
    $('.select1').click(function() {
    if ($(this).text() == "Northern Cape"){
      $("#firstloc").remove();
      $(this).append("<input id='firstloc' type='hidden' name='province' value='Northern Cape' />");
    } // end of if statement

    if ($(this).text() == "Eastern Cape"){
      $("#firstloc").remove();
      $(this).append("<input id='firstloc' type='hidden' name='province' value='Eastern Cape' />");
    } // end of if statement
  });
  $('.select2').click(function() {
    if ($(this).text() == "New Goods"){
      $("#category").remove();
      $(this).append("<input id='category' type='hidden' name='cat' value='New Goods' />");
    }
    if ($(this).text() == "Used Goods"){
      $("#category").remove();
      $(this).append("<input id='category' type='hidden' name='cat' value='Used Goods' />");
    }
  }); // end of click function
}); // end of document ready

    ```
<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>
<html>
<form action="post.php" method="POST">
   <p class="select1">Northern Cape</p>
   <p class="select1">Eastern Cape</p>
   <p class="select2" >New Goods</p>
   <p class="select2" >Used Goods</p>
   <input id="submt" type="submit" name="submit" value="Submit">
</form>
</html></code>```

Try this code hope it will helps you.

Body:
I have a form:

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

Northern Cape

Eastern Cape

New Goods

Used Goods

<input id="submt" type="submit" name="submit" value="Submit">
</form>

JQUERY .... appends input/value to the selected items:

$(document).ready(function() {
    $('.select1').click(function() {
      if ($(this).text() == "Northern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Northern Cape' />");
          $("#firstloc").val('Northern Cape');
     }; // end of if statement

      if ($(this).text() == "Eastern Cape"){
          $(this).append("<input id='firstloc' type='hidden' name='province'
          value='Eastern Cape' />");
          $("#firstloc").val('Eastern Cape');
     }; // end of if statement
}); // end of click function
}); // end of document ready

 $(document).ready(function() {
    $('.select2').click(function() {
        if ($(this).text() == "New Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='New Goods' />");
            $(this).val('New Goods');
         };

        if ($(this).text() == "Used Goods"){
            $(this).append("<input id='category' type='hidden' name='cat'
            value='Used Goods' />");
            $("#category").val('Used Goods');
         };

});
});

How do I pass the values to PHP ie. first value Province second value Category?

<?php

$province = $_POST['province'];
$category = $_POST['cat'];
echo $province;
echo $category;
?>

I get a message Undefined index:cat when passing to PHP.
User must select 2 items and values must be passed to PHP,I do not want to use a drop down menu with "options"

Body:
Here is the solution.

You made a several mistakes in your code.

You are using ; after if statement

You didnot close $document.ready tag properly

You have to check in your post.php if data posted or not

And you only appends input type hidden you weren't remove it.

post.php

<?php
$province = '';
$category = '';
if(isset($_POST['province'])):
    $province = $_POST['province'];
endif;
if(isset($_POST['cat'])):
    $category = $_POST['cat'];
endif;
echo $province;
echo $category;
?>

$(document).ready(function() {
    $('.select1').click(function() {
    if ($(this).text() == "Northern Cape"){
      $("#firstloc").remove();
      $(this).append("<input id='firstloc' type='hidden' name='province' value='Northern Cape' />");
    } // end of if statement

    if ($(this).text() == "Eastern Cape"){
      $("#firstloc").remove();
      $(this).append("<input id='firstloc' type='hidden' name='province' value='Eastern Cape' />");
    } // end of if statement
  });
  $('.select2').click(function() {
    if ($(this).text() == "New Goods"){
      $("#category").remove();
      $(this).append("<input id='category' type='hidden' name='cat' value='New Goods' />");
    }
    if ($(this).text() == "Used Goods"){
      $("#category").remove();
      $(this).append("<input id='category' type='hidden' name='cat' value='Used Goods' />");
    }
  }); // end of click function
}); // end of document ready

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<form action="post.php" method="POST">
   <p class="select1">Northern Cape</p>
   <p class="select1">Eastern Cape</p>
   <p class="select2" >New Goods</p>
   <p class="select2" >Used Goods</p>
   <input id="submt" type="submit" name="submit" value="Submit">
</form>
</html>

Try this code hope it will helps you.


问:
Input Type Number, no negative sign or decimals allowed?
I have two edittext views that I using for a calculation and both need to be limited to numbers only so I'm using the InputType to do this, but now I cannot enter a negative number or any numbers containing decimals!

Any ideas or solutions?

Thanks!

答:
Simply use the below and even the device input keyboard will contain numbers only:</p>

```<code>myTextView.setInputType(
  InputType.TYPE_CLASS_NUMBER);
</code>```

Body:
Simply use the below and even the device input keyboard will contain numbers only:

myTextView.setInputType(
  InputType.TYPE_CLASS_NUMBER);


问:
Knex to join tables from two databases
I am new to Node.js. I am using Knex for querying. I need to join two tables from two different databases. Could anyone tell me how this is possible?</p>

```<code>knex.select('id', 'full_name','email', 'mobile_country_code', 'mobile', knex.raw('1 as active_status')).from('users').where(whereData).union(function() {
        this.select('id','full_name', 'email', 'mobile_country_code', 'mobile', knex.raw('0 as active_status')).from('users_temp').where(whereData);
    }).then(function(data) {
        next(null, data);
    }).catch(function(err) {
        next(err.toString());
    });
</code>```

答:
```<code>knex
  .select(
    'users.id','users.full_name', 'users.email',
    'users.mobile_country_code', 'users.mobile',
    'loc.user_profile_pic', 'loc.user_timeline_pic'
  )
  .from('users')
  .leftJoin(config.project_db + '.users as loc', 'loc.id', '=', 'users.id')
  .where(whereData).union(function() {
    this.select(
      'id','full_name',
      knex.raw('\''+constants.images.default_user_profile_pic+'\' as user_profile_pic, \''+constants.images.default_user_timleline_pic+'\' as user_timeline_pic'),
      'email', 'mobile_country_code', 'mobile'
    )
    .from('users_temp').where(whereData);
  });
</code>```

Title: Knex to join tables from two databases

Body:
I am new to Node.js. I am using Knex for querying. I need to join two tables from two different databases. Could anyone tell me how this is possible?

knex.select('id', 'full_name','email', 'mobile_country_code', 'mobile', knex.raw('1 as active_status')).from('users').where(whereData).union(function() {
        this.select('id','full_name', 'email', 'mobile_country_code', 'mobile', knex.raw('0 as active_status')).from('users_temp').where(whereData);
    }).then(function(data) {
        next(null, data);
    }).catch(function(err) {
        next(err.toString());
    });


问:
Elements are overlapping each other even though I use twitter bootstrap
I am using twitter bootstrap on my site, I noticed that elements are overlapping if I make my window smaller. This does not look nice and I thought twitter bootstrap should make my website full responsive on all sizes.

```<code><div class="main row">
    <div class="col-sm-6">
        <center><h3>Firmware Download</h3></center>

<!-- Main Buttons -->
        <div class="row">
            <div class="col-sm-6">
                <button class="mainButtons" id="downloadFW">Download newest firmware to the server</button>
                <button class="mainButtons" id="reboot">Reboot server</button>
            </div>
            <div class="col-sm-6">
                <button class="mainButtons" id="deleteLogfile">Delete logfile</button>
                <button class="mainButtons" id="deleteTemplateStatusFile">Delete status file</button>
            </div>
        </div>

<!-- Template Generierung -->
        <div class="templateButtons col-sm-12">
            <h4>Create Template</h4>
            <select id="firmwareTemplate">
                <option value="mb">MB</option>
                <option value="bm">BM</option>
            </select>
            <select id="fileType">
                <option value="ova">OVA</option>
                <option value="vhd">VHD</option>
            </select>
            <button id="generateTemplate">Template erstellen</button>
        </div>
    </div>

    <div class="codeBox col-sm-6">
        <h5>Ausgabe:</h5>
        <pre id="codeOutput">-```

```

<p>CSS:</p>

```body {
    margin: 20px;
}

.codeBox {
    border: 1px solid black;
    overflow-y: scroll;
}
.codeBox code {
    /* Styles in here affect the text of the codebox */
    font-size:0.9em;
    /* You could also put all sorts of styling here, like different font, color, underline, etc. for the code. */
}
.lineTop {
    height: 1px;
    background-color: #D8D8D8;
    margin-top: 20px;
}
.lineBottom {
    height: 1px;
    background-color: #D8D8D8;
    margin-bottom: 20px;
}
.lineNoMargin {
    height: 2px;
    background-color: #D8D8D8;
}
.main {
    height: 350px;
    margin-left: 20px;
}
.mainButtons {
    min-width: 300px;
    text-align:left;
}
.templateButtons {
    margin-top: 50px;
    margin-left: 12px;
}

#templateStatusOutput {
    min-height: 240px;
}
#deleteTemplateStatusFile {
    visibility: hidden;
}
.statusBarContainer {
    border: 1px solid #D8D8D8;
    padding-right: 0;
    padding-left: 0;
}
.statusBar {
    height: 20px;
    background-color: #5cb85c;
    width: 0;
    color: white;
}
#statusBarTemplateStatus {
    background-color: green;
}
#statusBarCopyStatus {
    background-color: orangered;
}
.makeSpace50 {
    height: 50px;
}
#statusBar1 {
    visibility: hidden;
}
#statusBar2 {
    visibility: hidden;
}
```

Is this my fault?

答:
you use absolute value in your css, for example:

```<code>.mainButtons {
    min-width: 300px;
    text-align:left;
}
</code>```

Try using relative value like percentage for example, so that the element can keep the bootstrap's responsiveness:

```<code>.mainButtons {
    min-width: 100%;
    text-align:left;
}
</code>```

-------------- UPDATE -------------------

looking at your code here:

```<code><div class="main row">
<div class="col-sm-6">
    <center><h3>Firmware Download</h3></center>

    <!-- Main Buttons -->
    <div class="row">
        <div class="col-sm-6">
            <button class="mainButtons" id="downloadFW">Download newest firmware to the server</button>
            <button class="mainButtons" id="reboot">Reboot server</button>
        </div>
        <div class="col-sm-6">
            <button class="mainButtons" id="deleteLogfile">Delete logfile</button>
            <button class="mainButtons" id="deleteTemplateStatusFile">Delete status file</button>
        </div>
    </div>
    // ......
</code>```

First you divide the screen into two part,

 ...., then you divide again the first part of the screen into two again

..., this mean the button only has 1/4 of your screen as its space. If that 1/4 space is less than 300px, as it is the min-width of your mainButtons, then your problem occured.

Body:
I am using twitter bootstrap on my site, I noticed that elements are overlapping if I make my window smaller. This does not look nice and I thought twitter bootstrap should make my website full responsive on all sizes.

Firmware Download

                <button class="mainButtons" id="downloadFW">Download newest firmware to the server</button>
                <button class="mainButtons" id="reboot">Reboot server</button>

                <button class="mainButtons" id="deleteLogfile">Delete logfile</button>
                <button class="mainButtons" id="deleteTemplateStatusFile">Delete status file</button>

Create Template

            <select id="firmwareTemplate">
                <option value="mb">MB</option>
                <option value="bm">BM</option>
            </select>
            <select id="fileType">
                <option value="ova">OVA</option>
                <option value="vhd">VHD</option>
            </select>
            <button id="generateTemplate">Template erstellen</button>

Ausgabe:

-

CSS:

body {
    margin: 20px;
}

.codeBox {
    border: 1px solid black;
    overflow-y: scroll;
}
.codeBox code {
    /* Styles in here affect the text of the codebox */
    font-size:0.9em;
    /* You could also put all sorts of styling here, like different font, color, underline, etc. for the code. */
}
.lineTop {
    height: 1px;
    background-color: #D8D8D8;
    margin-top: 20px;
}
.lineBottom {
    height: 1px;
    background-color: #D8D8D8;
    margin-bottom: 20px;
}
.lineNoMargin {
    height: 2px;
    background-color: #D8D8D8;
}
.main {
    height: 350px;
    margin-left: 20px;
}
.mainButtons {
    min-width: 300px;
    text-align:left;
}
.templateButtons {
    margin-top: 50px;
    margin-left: 12px;
}

#templateStatusOutput {
    min-height: 240px;
}
#deleteTemplateStatusFile {
    visibility: hidden;
}
.statusBarContainer {
    border: 1px solid #D8D8D8;
    padding-right: 0;
    padding-left: 0;
}
.statusBar {
    height: 20px;
    background-color: #5cb85c;
    width: 0;
    color: white;
}
#statusBarTemplateStatus {
    background-color: green;
}
#statusBarCopyStatus {
    background-color: orangered;
}
.makeSpace50 {
    height: 50px;
}
#statusBar1 {
    visibility: hidden;
}
#statusBar2 {
    visibility: hidden;
}

Is this my fault?

Body:
you use absolute value in your css, for example:

.mainButtons {
    min-width: 300px;
    text-align:left;
}

Try using relative value like percentage for example, so that the element can keep the bootstrap's responsiveness:

.mainButtons {
    min-width: 100%;
    text-align:left;
}

-------------- UPDATE -------------------

looking at your code here:

<div class="main row">
<div class="col-sm-6">
    <center><h3>Firmware Download</h3></center>

    <!-- Main Buttons -->
    <div class="row">
        <div class="col-sm-6">
            <button class="mainButtons" id="downloadFW">Download newest firmware to the server</button>
            <button class="mainButtons" id="reboot">Reboot server</button>
        </div>
        <div class="col-sm-6">
            <button class="mainButtons" id="deleteLogfile">Delete logfile</button>
            <button class="mainButtons" id="deleteTemplateStatusFile">Delete status file</button>
        </div>
    </div>
    // ......

First you divide the screen into two part, <div class="main row"><div class="col-sm-6"> ...., then you divide again the first part of the screen into two again <!-- Main Buttons --><div class="row"><div class="col-sm-6">..., this mean the button only has 1/4 of your screen as its space. If that 1/4 space is less than 300px, as it is the min-width of your mainButtons, then your problem occured.


问:
How to move an image inside the imageview to the upper end of the imageView?
I have an imageView with contentMode UIViewContentModeScaleAspectFit. So it resizes the image without changing the aspect ratio. But the image inside the imageview is horizontally and vertically centred.

I don't want it to be vertically centred. How can I move this image to the upper end of imageview?

答:
I think you should make a custom UIView in which you can have UIImage property (just like UIImageView has) and you need to over ride 'drawRect' method of UIView and draw the image at appropriate position using [image drawInRect:rect]; method, check the documentation you will find stuff about aspect ratio as well while drawing...

In UIImageView, image's x,y position can't be changed..

ContentLicense: CC BY-SA 2.5


问:
confused with mobile friendly websites or related
I read somewhere that once you log in here (http://skweezer.com/) and put the website url, we can get the way the site will appear on mobile browsers. I tried getting this url (http://sachindra149.wordpress.com/) and was baffled to see he way it looked.

1) Can anyone please let me know why is that so ??

2) Why such a major difference???

3) And also what needs to be done ...

keeping one thing in mind that I dont have the control over the web codes for the page as it is a blog....
Hope I am clear enough !!!!!!!!

答:
I prefer checking them on real devices.

Chrome extension like this will help you vew your website on different screen sizes if there is a limit on devices.


问:
Get a String out of Try-Catch
I have a little issue with try-catch.

My Target is to get the test and test2 values out of the try block that I can use it later.

How to handle it?

```<code>public class MyApplication {
    public static void main(String[] args) {
        try {
            int test = Integer.parseInt("123");
            String test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}
</code>```

答:
Just declare them in the external scope :</p>

```<code>public class MyApplication {

    public static void main(String[] args) {
        int test = Integer.MAX_VALUE; // setting to max value to check if it was set later
        String test2 = null;

        try {
            test = Integer.parseInt("123");
            test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}
</code>```

Title: Get a String out of Try-Catch

Body:
I have a little issue with try-catch.

My Target is to get the test and test2 values out of the try block that I can use it later.

How to handle it?

public class MyApplication {
    public static void main(String[] args) {
        try {
            int test = Integer.parseInt("123");
            String test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}

Body:
Just declare them in the external scope :

public class MyApplication {

    public static void main(String[] args) {
        int test = Integer.MAX_VALUE; // setting to max value to check if it was set later
        String test2 = null;

        try {
            test = Integer.parseInt("123");
            test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}


问:
Loading Lots Of Images From Server In Android
Edit 2: Even after the bounty, no one could give a full solution. So I solved it myself. I have posted my solution below.

I searched about it on Google and also found various good results. But since I'm not expert in server and backend kind of terms, I would like to ask it in a separate question. I have a website hosting which helps me run an institution's website.

In my android app, there should be an option such as "Photo Gallery" which shows images from my website (where I upload images in a folder). I think it can be done by managing some JSON files.

Let there be a folder \public_html\MyApp\Images which consists of folders like "Event1", "Event2", and so on. I upload images to these different folders and my Android app should load them (maybe separately giving users a choice to pick a folder).

Is it possible? If any advanced database system is required, please give me some intro links for that. Is there any way a JSON is automatically generated containing the links to images?

Edit: I had recently bought website hosting for backend kind of things and I haven't done any server-side scripting or anything. That's why a detailed answer is required. I don't know how to manage those images, simply upload images and put links in JSON or use some MySQL, SQL or whatever terms which I've never used.

答:
I advise you to consider these two options for serving and storage of files:

Overview of Blobstore API for Java

Google Cloud Storage


问:
How to Differentiate System services from the List returned by queryUsageStats() of UsageStatsManager class in Android
Below is the code I run to get the processes that were running on the Android device. But the catch is i get it along with all the system processes. Is there a way to separate the System Servies (or) can I change the function call so that I dont get the system services altogether.</p>

```<code>   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public List<UsageStats> getUsageStats() {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getActivity()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY,0);
            cal.set(Calendar.MINUTE,1);
            List<UsageStats> queryUsageStats = mUsageStatsManager
                    .queryUsageStats(UsageStatsManager.INTERVAL_BEST, cal.getTimeInMillis(),
                            System.currentTimeMillis());

                       return queryUsageStats;
        }
</code>```

答:
What I do is to convert the each result from queryusageStats into a package name and then filter them out. If the package is a user installed package then it will have a proper name else it will be printed as null. I am also not able to find any straight way forward so had to work around this.

For example:

```<code>private String getAppNameFromPackage(String packageName, Context context) {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> pkgAppsList = context.getPackageManager()
            .queryIntentActivities(mainIntent, 0);

    for (ResolveInfo app : pkgAppsList) {
        if (app.activityInfo.packageName.equals(packageName)) {
            return app.activityInfo.loadLabel(context.getPackageManager()).toString();
        }
    }
    return null;
}

for (UsageStats u : queryUsageStats){

   String package_name = getAppNameFromPackage(u.getPackageName(), context);

   if(package_name.equals(null){

       Log.d(TAG, "Pkg:" + package_name + " is an system package/service");

   }else

       Log.d(TAG, "Pkg: " + package_name +  "\t" + "ForegroundTime: "
        + u.getTotalTimeInForeground() + " milliseconds") ;
}
</code>```

Body:
Below is the code I run to get the processes that were running on the Android device. But the catch is i get it along with all the system processes. Is there a way to separate the System Servies (or) can I change the function call so that I dont get the system services altogether.

   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public List<UsageStats> getUsageStats() {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getActivity()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY,0);
            cal.set(Calendar.MINUTE,1);
            List<UsageStats> queryUsageStats = mUsageStatsManager
                    .queryUsageStats(UsageStatsManager.INTERVAL_BEST, cal.getTimeInMillis(),
                            System.currentTimeMillis());

                       return queryUsageStats;
        }

Body:
What I do is to convert the each result from queryusageStats into a package name and then filter them out. If the package is a user installed package then it will have a proper name else it will be printed as null. I am also not able to find any straight way forward so had to work around this.

For example:

private String getAppNameFromPackage(String packageName, Context context) {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> pkgAppsList = context.getPackageManager()
            .queryIntentActivities(mainIntent, 0);

    for (ResolveInfo app : pkgAppsList) {
        if (app.activityInfo.packageName.equals(packageName)) {
            return app.activityInfo.loadLabel(context.getPackageManager()).toString();
        }
    }
    return null;
}

for (UsageStats u : queryUsageStats){

   String package_name = getAppNameFromPackage(u.getPackageName(), context);

   if(package_name.equals(null){

       Log.d(TAG, "Pkg:" + package_name + " is an system package/service");

   }else

       Log.d(TAG, "Pkg: " + package_name +  "\t" + "ForegroundTime: "
        + u.getTotalTimeInForeground() + " milliseconds") ;
}


问:
Javascript error "Cannot set property 'value' of null'
```<code><body onload="UserAction()">

<form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo"  id="rollNo"><br>
    Name: <input type="text" name="name" id="name"><br>
    <br>

<script type="text/javascript" language="javascript">
        function UserAction() {

            var rollNo = parseInt(localStorage.getItem("rollNo"));
            document.write(rollNo);
            document.getElementById("rollNo").value = rollNo;
        }
</script>
</code>```

The rollNo value gets printed but while assigning it to the textbox it gives me an error.

答:
Try replacing the function with the following lines:

```<code>function UserAction() {
        var rollNo = parseInt(localStorage.getItem("rollNo"));
        document.getElementById("rollNo").value= rollNo;
    }
</code>```

The mistake you're committing is replacing the entire body with roll number instead of that particular input field.

As the entire body is replaced with the rollnumber in localstorage, there is no element with id 'rollNo', hence the error says that it cannot set property 'value' of null.

Body:
<form action="student" id="add" align="center">
    Rollno:<input type="text" name="rollNo"  id="rollNo">

    Name: <input type="text" name="name" id="name">

The rollNo value gets printed but while assigning it to the textbox it gives me an error.

Body:
Try replacing the function with the following lines:

function UserAction() {
        var rollNo = parseInt(localStorage.getItem("rollNo"));
        document.getElementById("rollNo").value= rollNo;
    }

The mistake you're committing is replacing the entire body with roll number instead of that particular input field.

As the entire body is replaced with the rollnumber in localstorage, there is no element with id 'rollNo', hence the error says that it cannot set property 'value' of null.


问:
How can I exit a Spring Camel application when no messages are received at an endpoint for x seconds
I'm trying to configure a standalone spring-camel application so that there is a route, and if no messages are received on that route for x seconds, the whole context will shutdown.

Let's say x is 10, if no message is received for 8 seconds, but then one arrives on the route, the counter should reset to 10 seconds. Once the counter reaches 0, the whole app should exit (gracefully, finishing whatever routes are currently processing)

If messages keep coming within the 10 seconds, the app should never exit.

Does anyone know an elegant way to achieve this?

答:
If you use latest Camel release 2.19.1, you can then configure it to terminate after X messages, X time, or being idle for more than X seconds.

You can find the options in the camel spring configuration, which you can configure in application.properties for Spring, such as

https://github.com/apache/camel/blob/master/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelConfigurationProperties.java#L179

https://github.com/davsclaus/camel-profile-sample/blob/master/src/main/resources/application.properties#L24


问:
Pass dynamic value to test method parameter using TestNG class
I am automating a web page which runs in multi-threading environment, so I am exporting every test result into a file system and I wanted to maintain every test result uniquely for the future reference. So is there a way to pass file name as parameter to a test method dynamically while calling it from TestNG class.

I know we can pass parameters from .xml file but if I do that the values will more like static and can be seen by all the thread running parallel.

Test class will be called from main method as bellow

```<code>public class Test  {

    public static void main(String[] args) throws ParseException {

        try
        {
            TestNG testng = new TestNG();
            testng.setTestClasses(new Class[] { Testing.class });
            testng.run();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}
</code>```

Bellow code is my test method

public class Testing {

```<code>@Test
@Parameters("filename")
public void testMethod(String fileName){

    System.out.println("filename is: "+fileName);

   // ---- remaining test logic -----
}
</code>```

}

Or can we use TestListenerAdapter onStart() method to inject parameter values...?.

答:
If you want unique file name you can just add it a time stamp</p>

```<code>Date date = new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timeStamp = formatter.format(date);

String fileName = "TestResults-" + timeStamp;
</code>```

Body:
I am automating a web page which runs in multi-threading environment, so I am exporting every test result into a file system and I wanted to maintain every test result uniquely for the future reference. So is there a way to pass file name as parameter to a test method dynamically while calling it from TestNG class.

I know we can pass parameters from .xml file but if I do that the values will more like static and can be seen by all the thread running parallel.

Test class will be called from main method as bellow

public class Test  {

    public static void main(String[] args) throws ParseException {

        try
        {
            TestNG testng = new TestNG();
            testng.setTestClasses(new Class[] { Testing.class });
            testng.run();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

Bellow code is my test method

public class Testing {

@Test
@Parameters("filename")
public void testMethod(String fileName){

    System.out.println("filename is: "+fileName);

   // ---- remaining test logic -----
}

}

Or can we use TestListenerAdapter onStart() method to inject parameter values...?.

Body:
If you want unique file name you can just add it a time stamp

Date date = new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String timeStamp = formatter.format(date);

String fileName = "TestResults-" + timeStamp;


答:
you wrote:

....that I can use it later....

it depends what later means, if you mean later but in the same method then do something like:

```<code>public static void main(String[] args) {
    String test2 = "";
    try {
        int test = Integer.parseInt("123");
        test2 = "ABCD";
    } catch (NumberFormatException ex) {
        System.out.print(ex.getMessage());
    }
}
</code>```

then after that you can use a method like

```<code>test2.isEmpty()
</code>```

to check if the content in the string was updated to ABCD or not...

if you mean later but in another static method then do.

```<code>public class MyApplication  {
    static String test2 = "";
    public static void main(String[] args) {
        try {
            int test = Integer.parseInt("123");
            test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}
</code>```

Title: Get a String out of Try-Catch

Body:
you wrote:

....that I can use it later....

it depends what later means, if you mean later but in the same method then do something like:

public static void main(String[] args) {
    String test2 = "";
    try {
        int test = Integer.parseInt("123");
        test2 = "ABCD";
    } catch (NumberFormatException ex) {
        System.out.print(ex.getMessage());
    }
}

then after that you can use a method like

test2.isEmpty()

to check if the content in the string was updated to ABCD or not...

if you mean later but in another static method then do.

public class MyApplication  {
    static String test2 = "";
    public static void main(String[] args) {
        try {
            int test = Integer.parseInt("123");
            test2 = "ABCD";
        } catch (NumberFormatException ex) {
            System.out.print(ex.getMessage());
        }
    }
}


问:
Log4J2 not set as logger in OSGi environment
I am using commons-logging which should bridge to Log4J2 in an OSGi environment and so have added the dependencies, export-package and import-package in the pom.xml as below but the logger does not get set to Log4J2 logger. No errors are shown but when debugged I found it being set to JDK14Logger.

```<code>    <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>2.8.2</version>
        </dependency>

        <Export-Package>
            org.apache.logging.log4j.*,
            org.apache.commons.logging.*
        </Export-Package>
        <Import-Package>
            !org.apache.logging.log4j.*,
            !org.apache.commons.logging.*,
            *;resolution:=optional
        </Import-Package>
</code>```

[UPDATE]

From the log4j user mailing list I could figure out that due to the non-modular nature of ServiceLoader. I checked out a few usages of ServiceLoader in the OSGi environment to find implementations of interfaces but still couldn't get how this could be gotten to work.

I tried it using pax logging as well but the result is the same except for that the logger is now being set to JclLogger

答:
If the above is in your user bundle then this is not correct.
In your user bundle you should simply use the commons logging API and not change the settings of the maven bundle plugin.

It will then create Import-Package statements for the commons logging API but not for log4j which is what you want.

You then should install a suitable logging framework at runtime. I know that pax-logging can handle commons logging in a OSGi compatible way. Maybe plain log4j2 also works but I am not sure.

Body:
I am using commons-logging which should bridge to Log4J2 in an OSGi environment and so have added the dependencies, export-package and import-package in the pom.xml as below but the logger does not get set to Log4J2 logger. No errors are shown but when debugged I found it being set to JDK14Logger.

    <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>2.8.2</version>
        </dependency>

        <Export-Package>
            org.apache.logging.log4j.*,
            org.apache.commons.logging.*
        </Export-Package>
        <Import-Package>
            !org.apache.logging.log4j.*,
            !org.apache.commons.logging.*,
            *;resolution:=optional
        </Import-Package>

[UPDATE]

From the log4j user mailing list I could figure out that due to the non-modular nature of ServiceLoader. I checked out a few usages of ServiceLoader in the OSGi environment to find implementations of interfaces but still couldn't get how this could be gotten to work.

I tried it using pax logging as well but the result is the same except for that the logger is now being set to JclLogger