问:
How to create a Xamarin.iOS app to activate kiosk mode (Lock the Device to a Single Application )?
I need to create a Xamarin.iOS app to activate kiosk mode (Lock the Device to a Single Application )</p>

答:
If you are using MDM you can set up kiosk mode, to lock the device into a single app, via the iPhone Configuration Utility. You can refer to these cases:

How can I programatically enable Guided Access (Kiosk mode) on an iPhone?

or Guided Access/Kiosk Mode of iPad

Otherwise you have to set up guided access on the device as this article described.


来源: stackexchange

问:
Get the name of snapshot from property using zfs get
It would like to know if it's possible to get the name of snapshot from any property.

For example, I created a property called :uuid with the value c98fdd32-8a76-4bcf-a509-d298291f85f5

If it's possible to get the name of this snapshot using the property and its value?

答:
Yes, it is possible.

Short answer:

Use zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}'

Long answer/explanation:

You can query any ZFS property of any dataset (file system, volume, or snapshot):

```<code>zfs get :uuid <dataset>
</code>```

If you call it recursively with -r without a dataset, you will get all valid datasets:

```<code>zfs get -r :uuid
</code>```

To reduce it only to datasets of snapshot type, use -t:

```<code>zfs get -r -t snapshot :uuid
</code>```

Then you can only display the columns you want with -o, in this case the name and value columns:

```<code>zfs get -r -t snapshot -o name,value :uuid
</code>```

To further work with the data, you need remove the headers with -H and display numbers as exact values with -p:

```<code>zfs get -Hpr -t snapshot -o name,value :uuid
</code>```

This includes all values, even non-set ones (-), so you need to further filter the output (for example with awk):

If you just want a specific snapshot name (print every first column/name for each line where the second column/value is the specific string):

```<code> zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}'
</code>```

If you want all results except the empty ones (all without -):

```<code> zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}'
</code>```

If you want to just have the basename, you can then further split first and second column by @ (which is the delimiter between file system and snapshot name):

```<code> zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}' | awk -F"@" '{print $1}'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes, it is possible.

Short answer:

Use zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}'

Long answer/explanation:

You can query any ZFS property of any dataset (file system, volume, or snapshot):

zfs get :uuid <dataset>

If you call it recursively with -r without a dataset, you will get all valid datasets:

zfs get -r :uuid

To reduce it only to datasets of snapshot type, use -t:

zfs get -r -t snapshot :uuid

Then you can only display the columns you want with -o, in this case the name and value columns:

zfs get -r -t snapshot -o name,value :uuid

To further work with the data, you need remove the headers with -H and display numbers as exact values with -p:

zfs get -Hpr -t snapshot -o name,value :uuid

This includes all values, even non-set ones (-), so you need to further filter the output (for example with awk):

If you just want a specific snapshot name (print every first column/name for each line where the second column/value is the specific string):

 zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}'

If you want all results except the empty ones (all without -):

 zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}'

If you want to just have the basename, you can then further split first and second column by @ (which is the delimiter between file system and snapshot name):

 zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}' | awk -F"@" '{print $1}'


问:
XSLT getting the first row from a series of data
I have seen some very similar questions, but the solutions don't seem to work in my case.

I have XML that looks like this.

```<code><AdLocInfo>
            <ExternalRunSchedNumber/>
            <RunSchedule-id>280896</RunSchedule-id>
            <publication-id>181</publication-id>
            <publication>SWEB</publication>
            <publication-placement-id>10</publication-placement-id>
            <publication-placement>Legals</publication-placement>
            <publication-position-id>21</publication-position-id>
            <publication-position>Legal - Notices</publication-position>
            <import-price>0.00</import-price>
            <rundates>
                <date Insertion-id="1530082" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05042017 15:30:00">05062017</date>
                <date Insertion-id="1530083" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05052017 15:30:00">05072017</date>
                <date Insertion-id="1530084" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05052017 15:30:00">05082017</date>
                <date Insertion-id="1530085" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05082017 15:30:00">05092017</date>
                <date Insertion-id="1530086" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05092017 15:30:00">05102017</date>
                <date Insertion-id="1530087" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05102017 15:30:00">05112017</date>
                <date Insertion-id="1530088" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05112017 15:30:00">05122017</date>
                <date Insertion-id="1530089" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05112017 15:30:00">05132017</date>
                <date Insertion-id="1530090" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05122017 15:30:00">05142017</date>
                <date Insertion-id="1530091" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05122017 15:30:00">05152017</date>
</code>```

I want to pull the first and last dates from the series.

My XSL looks like this:

```<code><xsl:for-each select="AdBaseInfo">
        <ad>
            <paperId>5344</paperId>
            <paperItemId>
                <xsl:value-of select="Ad/AdNumber"/>
            </paperItemId>
            <itemDesc>
                <!--<xsl:text disable-output-escaping="yes"><![CDATA[</xsl:text>-->
                <xsl:value-of select="Ad/ad-content"/>
                <!--<xsl:text disable-output-escaping="yes">]]></xsl:text>-->
            </itemDesc>
            <startDate>
                <xsl:for-each select="//date[1]">
                   <xsl:value-of select="concat(substring(., 5, 4), '-', substring(., 1, 2), '-', substring(., 3, 2))" />
                </xsl:for-each>
            </startDate>
</code>```

But that results in the first line from each of the records in the XML file.

```<code><ad>
<paperId>5344</paperId>
<paperItemId>0000119016-01</paperItemId>
<itemDesc/>
<startDate>2017-05-062017-05-242017-06-012017-06-012017-06-082017-05-272017-06-082017-06-082017-06-072017-06-072017-06-082017-06-082017-07-012017-06-082017-06-082017-06-072017-06-082017-06-10</startDate>
<expDate/>
<categoryId>S-Main Legal ROP</categoryId>
</code>```

Any help would be greatly appreciated.

答:
You must start with creation of a sorted list of date elements (dates),
but not with just "ordinary" copying.

The content of this variable is created in a for-each loop with
sort instruction inside, processing original date elements.

The sort order is year-month-day.

Each turn of the loop adds to dates variable a new date node,
with just the date (a text node), but in the proper (target) format.

If for any reason you needed something more, copy to the newly created element
e.g. any attributes you need.

With the above in mind, I choose to create a list of nodes, not just a list of strings.

Then if you want to get the min or max date, it is enough to write:

<xsl:value-of select="$dates/date[1]"/> or

<xsl:value-of select="$dates/date[last()]"/>

Below there is a complete script, working for your sample input.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="rundates">
    <xsl:copy>
      <xsl:variable name="dates">
        <xsl:for-each select="date">
          <xsl:sort select="concat(substring(., 5, 4),
          '-', substring(., 1, 2), '-', substring(., 3, 2))"/>
          <date>
            <xsl:value-of select="concat(substring(., 5, 4),
              '-', substring(., 1, 2), '-', substring(., 3, 2))" />
          </date>
        </xsl:for-each>
      </xsl:variable>
      <minDate>
        <xsl:value-of select="$dates/date[1]"/>
      </minDate>
      <maxDate>
        <xsl:value-of select="$dates/date[last()]"/>
      </maxDate>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="AdLocInfo">
    <xsl:apply-templates select="rundates"/>
  </xsl:template>
</xsl:transform>
</code>```

Body:
I have seen some very similar questions, but the solutions don't seem to work in my case.

I have XML that looks like this.

<AdLocInfo>
            <ExternalRunSchedNumber/>
            <RunSchedule-id>280896</RunSchedule-id>
            <publication-id>181</publication-id>
            <publication>SWEB</publication>
            <publication-placement-id>10</publication-placement-id>
            <publication-placement>Legals</publication-placement>
            <publication-position-id>21</publication-position-id>
            <publication-position>Legal - Notices</publication-position>
            <import-price>0.00</import-price>
            <rundates>
                <date Insertion-id="1530082" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05042017 15:30:00">05062017</date>
                <date Insertion-id="1530083" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05052017 15:30:00">05072017</date>
                <date Insertion-id="1530084" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05052017 15:30:00">05082017</date>
                <date Insertion-id="1530085" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05082017 15:30:00">05092017</date>
                <date Insertion-id="1530086" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05092017 15:30:00">05102017</date>
                <date Insertion-id="1530087" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05102017 15:30:00">05112017</date>
                <date Insertion-id="1530088" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05112017 15:30:00">05122017</date>
                <date Insertion-id="1530089" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05112017 15:30:00">05132017</date>
                <date Insertion-id="1530090" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05122017 15:30:00">05142017</date>
                <date Insertion-id="1530091" InvoicedAlreadyFlag="true" PublishedFlag="true" Deadline="05122017 15:30:00">05152017</date>

I want to pull the first and last dates from the series.

My XSL looks like this:

<xsl:for-each select="AdBaseInfo">
        <ad>
            <paperId>5344</paperId>
            <paperItemId>
                <xsl:value-of select="Ad/AdNumber"/>
            </paperItemId>
            <itemDesc>

                <xsl:value-of select="Ad/ad-content"/>

            </itemDesc>
            <startDate>
                <xsl:for-each select="//date[1]">
                   <xsl:value-of select="concat(substring(., 5, 4), '-', substring(., 1, 2), '-', substring(., 3, 2))" />
                </xsl:for-each>
            </startDate>

But that results in the first line from each of the records in the XML file.

<ad>
<paperId>5344</paperId>
<paperItemId>0000119016-01</paperItemId>
<itemDesc/>
<startDate>2017-05-062017-05-242017-06-012017-06-012017-06-082017-05-272017-06-082017-06-082017-06-072017-06-072017-06-082017-06-082017-07-012017-06-082017-06-082017-06-072017-06-082017-06-10</startDate>
<expDate/>
<categoryId>S-Main Legal ROP</categoryId>

Any help would be greatly appreciated.

Body:
You must start with creation of a sorted list of date elements (dates),
but not with just "ordinary" copying.

The content of this variable is created in a for-each loop with
sort instruction inside, processing original date elements.

The sort order is year-month-day.

Each turn of the loop adds to dates variable a new date node,
with just the date (a text node), but in the proper (target) format.

If for any reason you needed something more, copy to the newly created element
e.g. any attributes you need.

With the above in mind, I choose to create a list of nodes, not just a list of strings.

Then if you want to get the min or max date, it is enough to write:

<xsl:value-of select="$dates/date[1]"/> or

<xsl:value-of select="$dates/date[last()]"/>

Below there is a complete script, working for your sample input.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="rundates">
    <xsl:copy>
      <xsl:variable name="dates">
        <xsl:for-each select="date">
          <xsl:sort select="concat(substring(., 5, 4),
          '-', substring(., 1, 2), '-', substring(., 3, 2))"/>
          <date>
            <xsl:value-of select="concat(substring(., 5, 4),
              '-', substring(., 1, 2), '-', substring(., 3, 2))" />
          </date>
        </xsl:for-each>
      </xsl:variable>
      <minDate>
        <xsl:value-of select="$dates/date[1]"/>
      </minDate>
      <maxDate>
        <xsl:value-of select="$dates/date[last()]"/>
      </maxDate>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="AdLocInfo">
    <xsl:apply-templates select="rundates"/>
  </xsl:template>
</xsl:transform>


问:
How to add XML drawable in Eclipse
Ok guys I'm little stacked here. According to official documentation Google says that "Once you've defined your Drawable in XML, save the file in the res/drawable/ directory of your project." is the way to add a XML drawable to the project.

But when I created the project ADT created 3 different drawable folders for mdpi, hdpi, and ldpi. So when I wanted to create my XML drawable, I right click on my drawable-hdpi folder and select "Add new Android XML file", and there I have to select what kind of XML file I want to create, but there isn't "drawable" to select.

If I create new text file and save it as button_drawable.xml Eclipse says that there is an Error in the file and that It can't build my project.

So, please tell me how do you add xml drawables in Eclipse ADT?

答:
Why cant you use BitmapDrawable heres a sample code:

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/drawable_resource"
android:gravity="center"
android:tileMode="repeat"/>
</code>```

Just replace with your drawable src name and save this as .xml file.

Store the file in res/drawable directory.

Assign the reference to android:background="@drawable/drawable_resource" and it will be tiled.

Example:

```<code><LinearLayout
android:background="@drawable/drawable_resource"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LineatLayout
</code>```

Heres a complete template of Bitmap Drawable, you can choose attribute values accourding to your need.

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />
</code>```

You can find documentation of the same here look for XML Bitmap.

ContentLicense: CC BY-SA 2.5

Title: How to add XML drawable in Eclipse

Body:
Why cant you use BitmapDrawable heres a sample code:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/drawable_resource"
android:gravity="center"
android:tileMode="repeat"/>

Just replace with your drawable src name and save this as .xml file.

Store the file in res/drawable directory.

Assign the reference to android:background="@drawable/drawable_resource" and it will be tiled.

Example:

<LinearLayout
android:background="@drawable/drawable_resource"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LineatLayout

Heres a complete template of Bitmap Drawable, you can choose attribute values accourding to your need.

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

You can find documentation of the same here look for XML Bitmap.


问:
IOS : containsObject Check for String
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

```<code>if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE
</code>```

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..

答:
You may want to use [string1 isEqualToString:string2]

In that case it will evaluate to true only if strings are equal.

You may also use containString method. You may find this link helpfull.

Title: IOS : containsObject Check for String

Body:
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..


问:
Can't hide soft keyboard in Android Studio project, why?
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise. </p>

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

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}
</code>```

答:
Try:

```<code>imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
</code>```

In my case it works.

Body:
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise.

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

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}

Body:
Try:

imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

In my case it works.


问:
Only change one viewport in Aurelia router
Good morning, I have my route setup as shown below within Aurelia CLI.

```<code>config.map([
    {
        route: [''],
        viewPorts: {
           'side': { moduleId: 'side' },
           'main': { moduleId: 'main' }
        },
        title: 'Test',
        nav: false,
        name: 'Temp'
]);
</code>```

What I would like to do is based on what I select on my side view, I just want to change the moduleId for main and load that view.

答:
I don't think there's a way to dynamically change the moduleId of a view-port. I see 2 options to solve your proble:

1 - Create another route, changing the moduleId of one of the viewports

2 - Use the layout mechanism and change its content in run time. I recommend you to read http://aurelia.io/hub.html#/doc/article/aurelia/router/latest/router-configuration/10.

I know this is not the answer you were expecting but I hope it helps.

Body:
Good morning, I have my route setup as shown below within Aurelia CLI.

config.map([
    {
        route: [''],
        viewPorts: {
           'side': { moduleId: 'side' },
           'main': { moduleId: 'main' }
        },
        title: 'Test',
        nav: false,
        name: 'Temp'
]);

What I would like to do is based on what I select on my side view, I just want to change the moduleId for main and load that view.


问:
Revert to previous point in history in GitHub on the website
I know I can do this on the command line (git revert), but I need a solution completely on the web. Here is an example of what I am looking for.

I have a repo and it currently has 9 commits.

(https://github.com/Mr-Coxall/Web-12/commits/master)

I would like to revert back the repo to say the 4th commit.

I know I can see the code at that point in history.

(https://github.com/Mr-Coxall/Web-12/tree/aebfeadc4b3fb3a7b90c98b42d24f90a5200f5e5)

Only using the website, how can I make the repo revert back to that commit?

答:
Following "Creating and deleting branches within your repository", you can at least create a branch directly from that GitHub page referencing your older commit. (type the name of the new branch in the field, and GitHub will propose to create it from your current tree)

Then you need to rename master (still on GitHub), change the default branch to oyur new branch, and rename your new branch to master: see "Renaming a branch in GitHub"


问:
Navigating pages in jquery,Ajax
I'm new in jquery and ajax, i just want to open all my navigation links in one page. I also divided my page in three division. 1st page is in html i.e. welcome.html and rest all are in jsp. simply program takes two numbers, performs arithmetic operations on server (i wrote the servlet for each operation) side and send result back to jsp. At first it opens on same page but when i click on calculate button it goes on next page. if anybody have this solution using ajax or jquery plz let me know .

答:
Keep it like this(Using javascript, though you can use jquery also):

Say the id of first number relaed input field is val1 and that of second value is val2,
Keep this javascript function code in your jsp at bottom:

```<code><script>
function calculate(operation){
var value1, value2, result;
value1=document.getElementById("val1").value;
value2=document.getElementById("val2").value;
if(operation=='add')
result=value1+value2;
else if(operation=='subtract')
result=value1-value2;
else if(operation=='multiply')
result=value1*value2;
else if(operation=='divide')
result=value1/value2;
else
result="invalid choice!";
return result;
}
</script>

Each time on calculate button(like add, subtract, multiply, divide) keep:
for add button-> onclick=calculate('add')
for subtract button-> onclick=calculate('subtract')
for multiply button-> onclick=calculate('multiply')
for divide button-> onclick=calculate('divide')
</code>```

inside calculate button onclick event.

Note: If you really want to use servlets, use ajax call for that with your existing code, you can see an example here and here

Title: Navigating pages in jquery,Ajax

Body:
Keep it like this(Using javascript, though you can use jquery also):

Say the id of first number relaed input field is val1 and that of second value is val2,
Keep this javascript function code in your jsp at bottom:

<script>
function calculate(operation){
var value1, value2, result;
value1=document.getElementById("val1").value;
value2=document.getElementById("val2").value;
if(operation=='add')
result=value1+value2;
else if(operation=='subtract')
result=value1-value2;
else if(operation=='multiply')
result=value1*value2;
else if(operation=='divide')
result=value1/value2;
else
result="invalid choice!";
return result;
}
</script>

Each time on calculate button(like add, subtract, multiply, divide) keep:
for add button-> onclick=calculate('add')
for subtract button-> onclick=calculate('subtract')
for multiply button-> onclick=calculate('multiply')
for divide button-> onclick=calculate('divide')

inside calculate button onclick event.

Note: If you really want to use servlets, use ajax call for that with your existing code, you can see an example here and here


问:
Fetching from Database: Property or Method?
I've got a class that I'd like to let it get a record from a database. I need to make sure that there's at most one record. The record should be a single match to the class, based on the OrderId.

I feel like a property getter would make more sense than a method, but I know that property getters should avoid throwing Exceptions and .Single()/.SingleOrDefault() could end up throwing one. I feel like the method might make people think that it was fetching from the database each time. Either way, I'd have the result cached in a local field.

What is the best practice for something like this? I have an example of what my code is like below.

N.B.: I know that ideally we'd have a unique index on the DB column to make sure it's unique, it's not possible to do with the vendor database we're using.

```<code>class OrderDetails
{
    DbOrder _order;
    string OrderId { get; set; }

    DbOrder Order // property way
    {
        get{
            if (this._order == null)
                this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
            return _order;
        }
    }

    DbOrder GetOrder() // method way
    {
        if (this._order == null)
            this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
        return _order;
    }
}
</code>```

答:
Take some time to think by yourself what your class OrderDetails represents:

It represents the details of an order.

or: it represents some access to some storage where order details can be fetched (and possibly changed).

If OrderDetails would represent the first, then it would simply be some POCO with only get and set properties.

Clearly, your OrderDetails represent the 2nd. Your class is meant to ease the access to the storage of the order details. It also hides the storage, so if the storage changes (database changes structure, or not a database anymore but in-memory data), users of your class won't have to change.

The function of your OrderDetails is also more an access to order details, because two objects of class OrderDetails would not mean two order details, but two methods to access the same order details.

If you didn't mean this, but you wanted every order detail object to represent its own order details, consider changing the class such that it contains the fetched data of the order details, not some access to fetch the data. Also make some functions that fetches the data and returns an object with the fetched data.

Consider making static functions like OrderDetails.Create(...) or even better, create an order detail factory class that creates OrderDetail objects for you filled with the desired data.

If you have separated the data from the methods to fetch the data your question will be answered: the methods to fetch the data will be raising exceptions if fetching the data does not succeed. The POCO object that contains the fetched data won't have to raise exceptions: the data itself is not wrong

If you really meant, that your OrderDetail is not the detail of the order, but some access to get the order details, then getting the details of the order is clearly not a property of the access object, but some functionality of this access object.

Another reason to separate the order details from the access to the storage of the order details would be consistency if data. if your Order Detail has some related properties, and you would get them from the storage in separate calls, how would you guarantee that your related data does not change between the first and the second call?

For instance: Get Postcode and City of the address of a person in separate calls. If the data of the person you are querying is changing between your first and second call, because the person is moving, then you could get the old Postcode and the new City

Summarized: make sure that it is clear to you what parts of your design represents the data itself, or some access to get the data, and design your classes accordingly. Data classes will be filled with property get/set, Access classes will be filled with Functions that return the data classes

Body:
I've got a class that I'd like to let it get a record from a database. I need to make sure that there's at most one record. The record should be a single match to the class, based on the OrderId.

I feel like a property getter would make more sense than a method, but I know that property getters should avoid throwing Exceptions and .Single()/.SingleOrDefault() could end up throwing one. I feel like the method might make people think that it was fetching from the database each time. Either way, I'd have the result cached in a local field.

What is the best practice for something like this? I have an example of what my code is like below.

N.B.: I know that ideally we'd have a unique index on the DB column to make sure it's unique, it's not possible to do with the vendor database we're using.

class OrderDetails
{
    DbOrder _order;
    string OrderId { get; set; }

    DbOrder Order // property way
    {
        get{
            if (this._order == null)
                this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
            return _order;
        }
    }

    DbOrder GetOrder() // method way
    {
        if (this._order == null)
            this._order = dbContext.Where(x => x.OrderId == this.OrderId).SingleOrDefault();
        return _order;
    }
}


问:
In revel.Controller, How to get port set in app.conf
Using revel framework (golang), how can I get port I set in app.conf?

```<code>// in app.conf
http.port=9090
</code>```

And I have to use my server's port number in controllers (for example OAuth coding) such as

```<code>requestToken, url, err := TWITTER.GetRequestTokenAndUrl(
    "http://127.0.0.1:9090/Application/Authenticate",
)
</code>```

I don't want to write port number by hard coding.
Using revel, is there any good way to get port number (or any other conf values) set in app.conf?

Thank you in advance

答:
Updated Answer

In your file app/init.go you must retrieve config values within a custom-made function.

This custom made function must be registered in func init() with revel.OnAppStart(MyFunc).

If you attempt to retrieve config values directly from the init() func, you will recieve an error that looks something like this:

```<code>panic: runtime error: invalid memory address or nil pointer dereference
</code>```

Body:
Using revel framework (golang), how can I get port I set in app.conf?

// in app.conf
http.port=9090

And I have to use my server's port number in controllers (for example OAuth coding) such as

requestToken, url, err := TWITTER.GetRequestTokenAndUrl(
    "http://127.0.0.1:9090/Application/Authenticate",
)

I don't want to write port number by hard coding.
Using revel, is there any good way to get port number (or any other conf values) set in app.conf?

Thank you in advance

Body:
Updated Answer

In your file app/init.go you must retrieve config values within a custom-made function.

This custom made function must be registered in func init() with revel.OnAppStart(MyFunc).

If you attempt to retrieve config values directly from the init() func, you will recieve an error that looks something like this:

panic: runtime error: invalid memory address or nil pointer dereference


问:
Twitter atom don't retrieving old tweets
I have an application that consumes a twitter xml (obtained in http://search.twitter.com/) and shows the last 5 tweets posted by an account. But now it's only retrieving tweets posted in last 7 days.

The request made by me is something like:

http://search.twitter.com/search.atom?q=from:twitter&rpp=5&show_user=true

Anyone that passed for the same problem can give me an idea?

Thank you.

答:
rpp=5 means "do not return more than 5 tweets". Your query returns the 5 least recent tweets of the user no matter how old they are.

The only way to restrict the age of the tweets in the result is the parameter since_id.

Edit: The search API seems to be limited to 7 days.


问:
Play! Framework Uglify js files
I can't get Play! Framework's uglify plugin to work.

I’ve added addSbtPlugin("com.typesafe.sbt" % "sbt-uglify" % "1.0.3") to plugins.sbt

Then, inside build.sbt, I modified:

lazy val root = (project in file(".")).enablePlugins(PlayScala)

to

lazy val root = (project in file(".")).enablePlugins(PlayScala, SbtWeb)

and also added under that line:

pipelineStages := Seq(uglify)

After doing all this and re-running sbt run It doesn’t seem to be generating the .min.js files that it is supposed to. I manually checked on the target folder as well but no luck. Is there anything I might be doing wrong?

(I’m using this plugin: https://github.com/sbt/sbt-uglify and Play! Framework v.2.5)

答:
Quoting the Play 2.3.x Migration Guide:

UglifyJS 2 is presently provided via the RequireJS plugin (described next). The intent in future is to provide a standalone UglifyJS 2 plugin also for situations where RequireJS is not used.

So you should add the sbt-rjs plugin to your plugins.sbt.

```<code>addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.9")
</code>```

Please mind the correct ordering of the plugins in pipelineStages in build.sbtas well.

```<code>pipelineStages := Seq(rjs, uglify)
</code>```

Title: Play! Framework Uglify js files

Body:
Quoting the Play 2.3.x Migration Guide:

UglifyJS 2 is presently provided via the RequireJS plugin (described next). The intent in future is to provide a standalone UglifyJS 2 plugin also for situations where RequireJS is not used.

So you should add the sbt-rjs plugin to your plugins.sbt.

addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.9")

Please mind the correct ordering of the plugins in pipelineStages in build.sbtas well.

pipelineStages := Seq(rjs, uglify)


问:
iOS Push to another view controller get stuck
I have an base view controller and all my viewcontrollers inherit it.

```<code>@interface BaseViewController () <UIGestureRecognizerDelegate>

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.tabBarController.tabBar.translucent = NO;
    self.navigationController.navigationBar.translucent = NO;

    self.navigationController.interactivePopGestureRecognizer.delegate = self;

    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
    self.navigationItem.backBarButtonItem.title = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void) popToPreViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - getter and setter

- (UIButton *) backButton {
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
        [_backButton addTarget:self action:@selector(popToPreViewController) forControlEvents:UIControlEventTouchUpInside];
        [_backButton setImage:[UIImage imageNamed:@"main_back"] forState:UIControlStateNormal];
        _backButton.hidden = YES;
    }
    return _backButton;
}

@end
</code>```

Sometimes push to another view controller will get stuck ,but the app does not crash.Press home button and open the app again, it shows the another view controller . Is there something wrong with this baseviewcontroller ?

答:
I have been troubled by this problem for a long time, now find a solution.
The reason for this problem is that the root controller performs a gesture pop operation, the problem described above occurs. The workaround is to disable the gesture pop at the root controller and open the gesture pop on the non root controller.</p>

```<code>/// The controller is fully displayed, opening the gesture pop
 Func navigationController (_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

     If viewControllers.first == viewController {
         InteractivePopGestureRecognizer? .isEnabled = false
     } Else {
         InteractivePopGestureRecognizer? .isEnabled = true
     }

     NavigationBar.sendSubview (toBack: navigationBar.overlay)
 }
</code>```

Body:
I have an base view controller and all my viewcontrollers inherit it.

@interface BaseViewController () <UIGestureRecognizerDelegate>

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.tabBarController.tabBar.translucent = NO;
    self.navigationController.navigationBar.translucent = NO;

    self.navigationController.interactivePopGestureRecognizer.delegate = self;

    self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
    self.navigationItem.backBarButtonItem.title = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void) popToPreViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - getter and setter

- (UIButton *) backButton {
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
        [_backButton addTarget:self action:@selector(popToPreViewController) forControlEvents:UIControlEventTouchUpInside];
        [_backButton setImage:[UIImage imageNamed:@"main_back"] forState:UIControlStateNormal];
        _backButton.hidden = YES;
    }
    return _backButton;
}

@end

Sometimes push to another view controller will get stuck ,but the app does not crash.Press home button and open the app again, it shows the another view controller . Is there something wrong with this baseviewcontroller ?

Body:
I have been troubled by this problem for a long time, now find a solution.
The reason for this problem is that the root controller performs a gesture pop operation, the problem described above occurs. The workaround is to disable the gesture pop at the root controller and open the gesture pop on the non root controller.

/// The controller is fully displayed, opening the gesture pop
 Func navigationController (_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

     If viewControllers.first == viewController {
         InteractivePopGestureRecognizer? .isEnabled = false
     } Else {
         InteractivePopGestureRecognizer? .isEnabled = true
     }

     NavigationBar.sendSubview (toBack: navigationBar.overlay)
 }


问:
i need to allow the data which is in between the start and end date
Here i given my database table. i need to create a code to allow the data to show after the start date and remove the data after the end date:

答:
SqlDataAdapter ad = new SqlDataAdapter("select * from ProductTable a,OfferTable b where a.Product_ID='" + textBox15.Text + "' and b.start_date<=(GETDATE())", con);

this code is used to show the data after the start date....

thanks to all who tried to help me .

ContentLicense: CC BY-SA 4.0


问:
Prolog - infinite loop
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

```<code>remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.
</code>```

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

答:
In a situation as yours, you have two options. Either wade through walls of text of traces as you can see in another answer, or try to reduce first what you have to understand. I prefer the latter for I don't like to read much.

But your major problem is this. You said:

And when I call is_middle(1,[2,1,3]) then I get true.

Yes, Prolog found a solution, but it did not find it once but infinitely many times. Just hit SPACE or ; to see this:

```<code>?- is_middle(1,[2,1,3]).
   true
;  true
;  true
;  true
;  true
;  ... .
</code>```

So, already your first query was problematic. The best way to observe this, is to add false to this query:

```
?- is_middle(1,[2,1,3]), <b>false</b>.
   loops.
```

Now, let's try to reduce the size of the query. We can narrow it down to:

```
?- is_middle(1,[1]), <b>false</b>.
   loops.
```

With this we can now look at your program. Before anything else I'll remove the cut. It is misplaced anyway.

To understand what is actually happening, I will narrow down your program by inserting false into it. With these extra goals it is possible to eliminate a lot of unnecessary detail. And still, the remaining program called a failure-slice is of relevance to us, if it is still looping.

```
remove_first_and_last([X],[X]).
<s>remove_first_and_last(In, Out) :- <b>false</b></s>,
    <s>remove_first(In, Out1)</s>,
    <s>remove_last(Out1, Out)</s>.

<s>middle([X], [X]) :- <b>false</b></s>.
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X), <b>false</b>.

is_middle(X, In) :-
    middle(In, Out), <b>false</b>,
    <s>member(X, Out)</s>.
```

Compare this to your original program! Much less reading. To fix the problem you have to fix something in the remaining fragment. I suggest to remove the fact remove_first_and_last([X],[X]). This fact suggests that something is removed, but for this very case, nothing is removed.

For a solution using a dcg directly:

```<code>is_middle(E, Es) :-
   phrase(middle(E), Es).

middle(E) --> [E].
middle(E) --> [_], middle(E), [_].
</code>```

That is as short as it can get, but it has a tiny problem: It does not compute the answer determinately. You can see this by looking at the answer:

```<code>?- is_middle(1, [2,1,3]).
   true
;  false.
</code>```

This ; false is an indication that Prolog was not able to finish the computation determinately. In other words, some space is left. You might be tempted to use a cut. Resist!

If you are really into speed, take the fastest version:

```<code>is_middle(X, Xs) :-
   Xs = [_|Cs],
   middle_el(Cs, Xs, X).

middle_el([], [X|_], X).
middle_el([_,_|Cs], [_|Xs], X) :-
   middle_el(Cs, Xs, X).
</code>```

In case you want @DanielLyons' interpretation which admits even-length lists to have two middle elements, see how easy it is to adopt above grammar definition. Simply add the following two rules:

```<code>middle(E) --> [E,_].
middle(E) --> [_,E].
</code>```

Alternatively, combine all four rules into one:

```<code>middle(E) --> [E] | [E,_] | [_,E] | [_], middle(E), [_].
</code>```

For the fastest solution, things are a bit more complex ...

```<code>is_middle_dl(X, Xs) :-
   Xs = [_|Cs],
   middle_el_dl(Cs, Xs, X).

middle_el_dl([], [X|_], X).
middle_el_dl([_|Cs], Xs, X) :-
   middle_el_dl2(Cs, Xs, X).

middle_el_dl2([], [A,B|_], X) :-
   ( X = A ; X = B ).
middle_el_dl2([_|Cs], [_|Xs], X) :-
   middle_el_dl(Cs, Xs, X).
</code>```

To check it, I use:

```
?- is_middle(1,[2,1,3]), <b>false</b>.
   loops.
```0

Title: Prolog - infinite loop

Body:
I want to check if element is in the middle of list.
I search middle element and next I check if is a member of list, but I get infinite loop.

My predicates:

remove_first([_,H1|T], [H1|T]).

remove_last([_],[]).
remove_last([H|T], [H|T2]) :- remove_last(T, T2).

remove_first_and_last([X],[X]).
remove_first_and_last(In, Out) :-
    remove_first(In, Out1),
    remove_last(Out1, Out).

middle([X], [X]).
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X).

member(X, [X|_]).
member(X, [_|T]) :- member(X, T).

is_middle(X, In) :-
    middle(In, Out),
    member(X, Out), !.

And when I call is_middle(1,[2,1,3]) then I get true.
But when I call is_middle(1,[2,2,3]) then I don't get a result. Interpreter don't interrupt the processing.

Body:
In a situation as yours, you have two options. Either wade through walls of text of traces as you can see in another answer, or try to reduce first what you have to understand. I prefer the latter for I don't like to read much.

But your major problem is this. You said:

And when I call is_middle(1,[2,1,3]) then I get true.

Yes, Prolog found a solution, but it did not find it once but infinitely many times. Just hit SPACE or ; to see this:

?- is_middle(1,[2,1,3]).
   true
;  true
;  true
;  true
;  true
;  ... .

So, already your first query was problematic. The best way to observe this, is to add false to this query:

?- is_middle(1,[2,1,3]), false.
   loops.

Now, let's try to reduce the size of the query. We can narrow it down to:

?- is_middle(1,[1]), false.
   loops.

With this we can now look at your program. Before anything else I'll remove the cut. It is misplaced anyway.

To understand what is actually happening, I will narrow down your program by inserting false into it. With these extra goals it is possible to eliminate a lot of unnecessary detail. And still, the remaining program called a failure-slice is of relevance to us, if it is still looping.

remove_first_and_last([X],[X]).
<s>remove_first_and_last(In, Out) :- false</s>,
    <s>remove_first(In, Out1)</s>,
    <s>remove_last(Out1, Out)</s>.

<s>middle([X], [X]) :- false</s>.
middle(In, X) :-
    remove_first_and_last(In, Out),
    middle(Out, X), false.

is_middle(X, In) :-
    middle(In, Out), false,
    <s>member(X, Out)</s>.

Compare this to your original program! Much less reading. To fix the problem you have to fix something in the remaining fragment. I suggest to remove the fact remove_first_and_last([X],[X]). This fact suggests that something is removed, but for this very case, nothing is removed.

For a solution using a dcg directly:

is_middle(E, Es) :-
   phrase(middle(E), Es).

middle(E) --> [E].
middle(E) --> [_], middle(E), [_].

That is as short as it can get, but it has a tiny problem: It does not compute the answer determinately. You can see this by looking at the answer:

?- is_middle(1, [2,1,3]).
   true
;  false.

This ; false is an indication that Prolog was not able to finish the computation determinately. In other words, some space is left. You might be tempted to use a cut. Resist!

If you are really into speed, take the fastest version:

is_middle(X, Xs) :-
   Xs = [_|Cs],
   middle_el(Cs, Xs, X).

middle_el([], [X|_], X).
middle_el([_,_|Cs], [_|Xs], X) :-
   middle_el(Cs, Xs, X).

In case you want @DanielLyons' interpretation which admits even-length lists to have two middle elements, see how easy it is to adopt above grammar definition. Simply add the following two rules:

middle(E) --> [E,_].
middle(E) --> [_,E].

Alternatively, combine all four rules into one:

middle(E) --> [E] | [E,_] | [_,E] | [_], middle(E), [_].

For the fastest solution, things are a bit more complex ...

is_middle_dl(X, Xs) :-
   Xs = [_|Cs],
   middle_el_dl(Cs, Xs, X).

middle_el_dl([], [X|_], X).
middle_el_dl([_|Cs], Xs, X) :-
   middle_el_dl2(Cs, Xs, X).

middle_el_dl2([], [A,B|_], X) :-
   ( X = A ; X = B ).
middle_el_dl2([_|Cs], [_|Xs], X) :-
   middle_el_dl(Cs, Xs, X).

To check it, I use:

?- length(Xs, N), N mod 2 =:= 0, is_middle_dl(X, Xs).
   Xs = [X,_A], N = 2
;  Xs = [_A,X], N = 2
;  Xs = [_A,X,_B,_C], N = 4
;  Xs = [_A,_B,X,_C], N = 4
;  Xs = [_A,_B,X,_C,_D,_E], N = 6
;  Xs = [_A,_B,_C,X,_D,_E], N = 6
;  Xs = [_A,_B,_C,X,_D,_E,_F,_G], N = 8
;  Xs = [_A,_B,_C,_D,X,_E,_F,_G], N = 8
;  Xs = [_A,_B,_C,_D,X,_E,_F,_G,_H,_I], N = 10
;  Xs = [_A,_B,_C,_D,_E,X,_F,_G,_H,_I], N = 10
;  ... .


问:
JDBC Connection close conecpt
I have created connection's object and stored in the hashMap. While executing query on the connection object I retrieve the object from the hashMap. In finally block I close the connection.
However, when we come for the second time I again retrieve the connection's object from the hashMap. This time while executing the query I get closed connection exception.
If I remove conn.close() from finally, it works.
what is the reason behind this? Moreover, when i print the connection's object I get the object.</p>

答:
You don't have to close Connection after each sql statement.
Newly created Connection is in auto-commit mode :
By default, new connections are in auto-commit mode. From Connection.setAutoCommit doc:

The commit occurs when the statement completes. The time when the
  statement completes depends on the type of SQL Statement:  •For DML
  statements, such as Insert, Update or Delete, and DDL statements, the
  statement is complete as soon as it has finished executing.  •For
  Select statements, the statement is complete when the associated
  result set is closed.  •For CallableStatement objects or for
  statements that return multiple results, the statement is complete
  when all of the associated result sets have been closed, and all
  update counts and output parameters have been retrieved.

But if you set auto-commit to false you have to call Connection.commit method to update database.

Title: JDBC Connection close conecpt


问:
select and modify atomically in multi-threaded application
I am working on an Android application which has most of the code in C. I have compiled SQLite in C and using it.

I have following code:

```<code>void func_foo(){

Select X from table1

Update X in table1

}
</code>```

I want that func_foo behaves atomically and this function is getting called from multiple threads.

My concern is that once I ran select statement from thread1, thread2 should not modify the data of the tables in between.

So will wrapping the whole DB operation inside a transaction make it atomic?

Or do I need to use mutex over the function so that only one instance can access the DB?

答:
I've refereed several stack answers and blog posts about how exactly to do that:

1. What are the best practices for SQLite on Android?

2. http://touchlabblog.tumblr.com/post/24474750219/single-sqlite-connection

Number 1 is best, Number 2 is a lot of extra work and unnecessary. ContentProvider exists so you can share data with other apps.

Body:
I am working on an Android application which has most of the code in C. I have compiled SQLite in C and using it.

I have following code:

void func_foo(){

Select X from table1

Update X in table1

}

I want that func_foo behaves atomically and this function is getting called from multiple threads.

My concern is that once I ran select statement from thread1, thread2 should not modify the data of the tables in between.

So will wrapping the whole DB operation inside a transaction make it atomic?

Or do I need to use mutex over the function so that only one instance can access the DB?


问:
HTML removing all events from element
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

```<code>function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}
</code>```

but there is an error (in console):

```<code>jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent
</code>```

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

答:
You need to use the jQuery object in order to use unbind().

I updated your snippet changing the methods to their jQuery counterparts.

```<code>function disableClickEvent() {
    var elems = $("a");
    elems.each(function() {
        for (var key in toDisableMap) {
            if ($(this).text() == key){
                $(this).prop('onclick',null).off('click');
                break;
            }
         }
    })
}
</code>```

Title: HTML removing all events from element

Body:
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}

but there is an error (in console):

jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

Body:
You need to use the jQuery object in order to use unbind().

I updated your snippet changing the methods to their jQuery counterparts.

function disableClickEvent() {
    var elems = $("a");
    elems.each(function() {
        for (var key in toDisableMap) {
            if ($(this).text() == key){
                $(this).prop('onclick',null).off('click');
                break;
            }
         }
    })
}


问:
How to portably compare std::system_error exceptions to std::errc values?
As far as I've understood, one of the best practices to check system_error conditions in a portable manner is to compare their code() value with values in the std::errc enumeration. However, when I try to run the following code, this does not seem to work.

```<code>#include <cassert>
#include <cerrno>
#include <system_error>

int main() {
    try {
        throw std::system_error(ENOENT, std::system_category());
    } catch (std::system_error const & e) {
        assert(e.code() == std::errc::no_such_file_or_directory); // <- FAILS!?
    }
}
</code>```

Do I misunderstand how these diagnostic errors are supposed to work, or am I doing something wrong? How should one compare std::system_error exceptions to std::errc values?

EDIT: The code seems to work properly using clang++ and libc++, but fails when building against libstdc++ regardless of which GCC or Clang compiler (and version) I use. Related to PR 60555? Any portable workaround?

答:
e.code() returns an instance of ::std::error_code which has overloaded operator == which leads to implicit construction of error_condition object as right hand expression out of std::errc::no_such_file_or_directory. Comparison will fail because error_code returned by exception has system_category while another one will have generic_category. You should compare with error_code::value() instead. Note that this comparison requires static_cast of std::errc value because it is an enum class and does not get implicitly converted to int. Working example:

```<code>#include <cassert>
#include <cerrno>
#include <system_error>
#include <iostream>

int main()
{
    ::std::cout << static_cast< int >(ENOENT) << ::std::endl;
    ::std::cout << static_cast< int >(::std::errc::no_such_file_or_directory) << ::std::endl;
    try
    {
        throw std::system_error(ENOENT, std::system_category());
    }
    catch(::std::system_error const & e)
    {
        assert(e.code().value() == static_cast< int >(::std::errc::no_such_file_or_directory));
    }
}
</code>```

Body:
As far as I've understood, one of the best practices to check system_error conditions in a portable manner is to compare their code() value with values in the std::errc enumeration. However, when I try to run the following code, this does not seem to work.

#include <cassert>
#include <cerrno>
#include <system_error>

int main() {
    try {
        throw std::system_error(ENOENT, std::system_category());
    } catch (std::system_error const & e) {
        assert(e.code() == std::errc::no_such_file_or_directory); // <- FAILS!?
    }
}

Do I misunderstand how these diagnostic errors are supposed to work, or am I doing something wrong? How should one compare std::system_error exceptions to std::errc values?

EDIT: The code seems to work properly using clang++ and libc++, but fails when building against libstdc++ regardless of which GCC or Clang compiler (and version) I use. Related to PR 60555? Any portable workaround?

Body:
e.code() returns an instance of ::std::error_code which has overloaded operator == which leads to implicit construction of error_condition object as right hand expression out of std::errc::no_such_file_or_directory. Comparison will fail because error_code returned by exception has system_category while another one will have generic_category. You should compare with error_code::value() instead. Note that this comparison requires static_cast of std::errc value because it is an enum class and does not get implicitly converted to int. Working example:

#include <cassert>
#include <cerrno>
#include <system_error>
#include <iostream>

int main()
{
    ::std::cout << static_cast< int >(ENOENT) << ::std::endl;
    ::std::cout << static_cast< int >(::std::errc::no_such_file_or_directory) << ::std::endl;
    try
    {
        throw std::system_error(ENOENT, std::system_category());
    }
    catch(::std::system_error const & e)
    {
        assert(e.code().value() == static_cast< int >(::std::errc::no_such_file_or_directory));
    }
}


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答:
Personally I don't see a difference between callbacks, listeners, and delegates.

The observer pattern (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __call__ magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.

```<code>class Foo(object):
  def __init__(self):
    self._bar_observers = []

  def add_bar_observer(self, observer):
    self._bar_observers.append(observer)

  def notify_bar(self, param):
    for observer in self._bar_observers:
      observer(param)

def observer(param):
  print "observer(%s)" % param

class Baz(object):
  def observer(self, param):
    print "Baz.observer(%s)" % param

class CallableClass(object):
  def __call__(self, param):
    print "CallableClass.__call__(%s)" % param

baz = Baz()

foo = Foo()

foo.add_bar_observer(observer) # function
foo.add_bar_observer(baz.observer) # bound method
foo.add_bar_observer(CallableClass()) # callable instance

foo.notify_bar(3)
</code>```

OwnerDisplayName: okoman

Body:
Personally I don't see a difference between callbacks, listeners, and delegates.

The observer pattern (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __call__ magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.

class Foo(object):
  def __init__(self):
    self._bar_observers = []

  def add_bar_observer(self, observer):
    self._bar_observers.append(observer)

  def notify_bar(self, param):
    for observer in self._bar_observers:
      observer(param)

def observer(param):
  print "observer(%s)" % param

class Baz(object):
  def observer(self, param):
    print "Baz.observer(%s)" % param

class CallableClass(object):
  def __call__(self, param):
    print "CallableClass.__call__(%s)" % param

baz = Baz()

foo = Foo()

foo.add_bar_observer(observer) # function
foo.add_bar_observer(baz.observer) # bound method
foo.add_bar_observer(CallableClass()) # callable instance

foo.notify_bar(3)

OwnerDisplayName: orip


问:
Java how to reset "set" values after being changed
```<code>public static void reset() {
        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();
    }

    public static void fight() {

        //user
        player user = new player();
        user.setP_Name(username);
        user.setP_ATK(atk);
        user.setP_HP(hp);
        //END-user

        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();

        System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
                + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
                + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
                + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
                + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
                + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
                + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

        int answer = 0;
        int d;
        int e;
        boolean alive;

        int i;
        for (i = 1; i < 3; i++) {

            System.out.print("\n");

            System.out.println(enemies[i].getName() + " has appeared!");

            System.out.print("\n");

            alive = true;

            while (alive == true) {

                reset();

                System.out.println(enemies[i].getName() + " stats:");
                System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
                System.out.println("Attack[ATK]  : " + enemies[i].getATK());
                System.out.print("\n");

                if (user.getP_HP() > 0) {
                    System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                    System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                    answer = In.getInt();

                    clrscr();

                    System.out.print("\n");
                } else if (user.getP_HP() <= 0) {
                    System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                    return;
                }

                if (answer == 1) {

                    d = enemies[i].getHP() - user.getP_ATK();
                    enemies[i].setHP(d);

                    System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                    System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                    System.out.print("\n");

                    if (enemies[i].getHP() > 0) {
                        e = user.getP_HP() - enemies[i].getATK();
                        user.setP_HP(e);

                        System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + "for " + enemies[i].getATK() + " damage.");
                        System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                        System.out.println("\n");
                    } else if (enemies[1].getHP() <= 0) {

                        System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                                + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                        user.setP_ATK(user.getP_ATK() + (i * 1));
                        user.setP_HP(user.getP_HP() + (i * 10));

                        alive = false;
                    }

                } else if (answer == 2) {
                    if (i == 1) {
                        System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                        alive = false;
                        return;
                    } else {
                        System.out.println("You ran away, back to the last monster you saw!");
                        System.out.print("\n");
                        i = (i - 1);
                    }
                }
            }
        }
    } //fight method
</code>```

In this code, I set values for objects and then put them into an array called

enemies. Afterwards, I change the value of the elements of the objects using the

enemies array. After the "HP" value of the element array reaches zero, it goes

onto the next element. I made it so the user can go back to the previous element

and re-do it, but the element still has the same values as when the user first

altered them. I put all the "set" and enemies arrays which originally defined

the value into a method and tried calling it so it can reset, but I wasn't in

luck. Is there any way I can properly do this?

EDIT:

For those wondering, this is my cheap workaround:

```<code>public static void fight() {

    //user
    player user = new player();
    user.setP_Name(username);
    user.setP_ATK(atk);
    user.setP_HP(hp);
    //END-user

    System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
            + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
            + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
            + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
            + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
            + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
            + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

    int answer = 0;
    int d;
    int e;
    boolean alive;

    int i;
    for (i = 1; i < 6; i++) { //CHEAP WORKAROUND
        //goblin1
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin
        //orc2
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc
        //pheonix3
        stats pheonix = new stats();
        pheonix.setName("Pheonix");
        pheonix.setHP(75);
        pheonix.setATK(5);
        //END-pheonix
        //ancient dragon4
        stats ancdr = new stats();
        ancdr.setName("Ancient Dragon");
        ancdr.setHP(220);
        ancdr.setATK(13);
        //END-ancient dragon
        //hades5
        stats hades = new stats();
        hades.setName("Hades");
        hades.setHP(500);
        hades.setATK(25);
        //END-hades
        stats[] enemies = new stats[6];
        enemies[1] = new stats();
        enemies[2] = new stats();
        enemies[3] = new stats();
        enemies[1] = gob;
        enemies[2] = orc;
        enemies[3] = pheonix;
        enemies[4] = ancdr;
        enemies[5] = hades;
        enemies[1].getName();
        enemies[2].getName();
        enemies[3].getName();
        enemies[4].getName();
        enemies[5].getName();
        enemies[1].getHP();
        enemies[2].getHP();
        enemies[3].getHP();
        enemies[4].getHP();
        enemies[5].getHP();
        enemies[1].getATK();
        enemies[2].getATK();
        enemies[3].getATK();
        enemies[4].getATK();
        enemies[5].getATK(); //CHEAP WORKAROUND

        System.out.print("\n");

        System.out.println(enemies[i].getName() + " has appeared!");

        System.out.print("\n");

        alive = true;

        while (alive == true) {

            System.out.println(enemies[i].getName() + " stats:");
            System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
            System.out.println("Attack[ATK]  : " + enemies[i].getATK());
            System.out.print("\n");

            if (user.getP_HP() > 0) {
                System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                answer = In.getInt();

                clrscr();

                System.out.print("\n");
            } else if (user.getP_HP() <= 0) {
                System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                return;
            }

            if (answer == 1) {

                d = enemies[i].getHP() - user.getP_ATK();
                enemies[i].setHP(d);

                System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                System.out.print("\n");

                if (enemies[i].getHP() > 0) {
                    e = user.getP_HP() - enemies[i].getATK();
                    user.setP_HP(e);

                    System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + " for " + enemies[i].getATK() + " damage.");
                    System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                    System.out.println("\n");
                } else if (enemies[1].getHP() <= 0) {

                    System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                            + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                    user.setP_ATK(user.getP_ATK() + (i * 1));
                    user.setP_HP(user.getP_HP() + (i * 10));

                    alive = false;
                }

            } else if (answer == 2) {
                if (i == 1) {
                    System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                    alive = false;
                    return;
                } else {
                    System.out.println("You ran away, back to the last monster you saw!");
                    System.out.print("\n");
                    i = (i - 1);
                }
            }
        }
    }
} //fight method
</code>```

答: arrays nor any collection have an UNDO method, you need to design your own where you hold the last state of the data container and restore it as required whenever you need it</p>

Body:
public static void reset() {
        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();
    }

    public static void fight() {

        //user
        player user = new player();
        user.setP_Name(username);
        user.setP_ATK(atk);
        user.setP_HP(hp);
        //END-user

        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();

        System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
                + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
                + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
                + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
                + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
                + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
                + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

        int answer = 0;
        int d;
        int e;
        boolean alive;

        int i;
        for (i = 1; i < 3; i++) {

            System.out.print("\n");

            System.out.println(enemies[i].getName() + " has appeared!");

            System.out.print("\n");

            alive = true;

            while (alive == true) {

                reset();

                System.out.println(enemies[i].getName() + " stats:");
                System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
                System.out.println("Attack[ATK]  : " + enemies[i].getATK());
                System.out.print("\n");

                if (user.getP_HP() > 0) {
                    System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                    System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                    answer = In.getInt();

                    clrscr();

                    System.out.print("\n");
                } else if (user.getP_HP() <= 0) {
                    System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                    return;
                }

                if (answer == 1) {

                    d = enemies[i].getHP() - user.getP_ATK();
                    enemies[i].setHP(d);

                    System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                    System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                    System.out.print("\n");

                    if (enemies[i].getHP() > 0) {
                        e = user.getP_HP() - enemies[i].getATK();
                        user.setP_HP(e);

                        System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + "for " + enemies[i].getATK() + " damage.");
                        System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                        System.out.println("\n");
                    } else if (enemies[1].getHP() <= 0) {

                        System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                                + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                        user.setP_ATK(user.getP_ATK() + (i * 1));
                        user.setP_HP(user.getP_HP() + (i * 10));

                        alive = false;
                    }

                } else if (answer == 2) {
                    if (i == 1) {
                        System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                        alive = false;
                        return;
                    } else {
                        System.out.println("You ran away, back to the last monster you saw!");
                        System.out.print("\n");
                        i = (i - 1);
                    }
                }
            }
        }
    } //fight method

In this code, I set values for objects and then put them into an array called

enemies. Afterwards, I change the value of the elements of the objects using the

enemies array. After the "HP" value of the element array reaches zero, it goes

onto the next element. I made it so the user can go back to the previous element

and re-do it, but the element still has the same values as when the user first

altered them. I put all the "set" and enemies arrays which originally defined

the value into a method and tried calling it so it can reset, but I wasn't in

luck. Is there any way I can properly do this?

EDIT:

For those wondering, this is my cheap workaround:

public static void fight() {

    //user
    player user = new player();
    user.setP_Name(username);
    user.setP_ATK(atk);
    user.setP_HP(hp);
    //END-user

    System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
            + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
            + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
            + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
            + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
            + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
            + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

    int answer = 0;
    int d;
    int e;
    boolean alive;

    int i;
    for (i = 1; i < 6; i++) { //CHEAP WORKAROUND
        //goblin1
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin
        //orc2
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc
        //pheonix3
        stats pheonix = new stats();
        pheonix.setName("Pheonix");
        pheonix.setHP(75);
        pheonix.setATK(5);
        //END-pheonix
        //ancient dragon4
        stats ancdr = new stats();
        ancdr.setName("Ancient Dragon");
        ancdr.setHP(220);
        ancdr.setATK(13);
        //END-ancient dragon
        //hades5
        stats hades = new stats();
        hades.setName("Hades");
        hades.setHP(500);
        hades.setATK(25);
        //END-hades
        stats[] enemies = new stats[6];
        enemies[1] = new stats();
        enemies[2] = new stats();
        enemies[3] = new stats();
        enemies[1] = gob;
        enemies[2] = orc;
        enemies[3] = pheonix;
        enemies[4] = ancdr;
        enemies[5] = hades;
        enemies[1].getName();
        enemies[2].getName();
        enemies[3].getName();
        enemies[4].getName();
        enemies[5].getName();
        enemies[1].getHP();
        enemies[2].getHP();
        enemies[3].getHP();
        enemies[4].getHP();
        enemies[5].getHP();
        enemies[1].getATK();
        enemies[2].getATK();
        enemies[3].getATK();
        enemies[4].getATK();
        enemies[5].getATK(); //CHEAP WORKAROUND

        System.out.print("\n");

        System.out.println(enemies[i].getName() + " has appeared!");

        System.out.print("\n");

        alive = true;

        while (alive == true) {

            System.out.println(enemies[i].getName() + " stats:");
            System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
            System.out.println("Attack[ATK]  : " + enemies[i].getATK());
            System.out.print("\n");

            if (user.getP_HP() > 0) {
                System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                answer = In.getInt();

                clrscr();

                System.out.print("\n");
            } else if (user.getP_HP() <= 0) {
                System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                return;
            }

            if (answer == 1) {

                d = enemies[i].getHP() - user.getP_ATK();
                enemies[i].setHP(d);

                System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                System.out.print("\n");

                if (enemies[i].getHP() > 0) {
                    e = user.getP_HP() - enemies[i].getATK();
                    user.setP_HP(e);

                    System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + " for " + enemies[i].getATK() + " damage.");
                    System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                    System.out.println("\n");
                } else if (enemies[1].getHP() <= 0) {

                    System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                            + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                    user.setP_ATK(user.getP_ATK() + (i * 1));
                    user.setP_HP(user.getP_HP() + (i * 10));

                    alive = false;
                }

            } else if (answer == 2) {
                if (i == 1) {
                    System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                    alive = false;
                    return;
                } else {
                    System.out.println("You ran away, back to the last monster you saw!");
                    System.out.print("\n");
                    i = (i - 1);
                }
            }
        }
    }
} //fight method


问:
Designing Relative Layout
How should I design a Relative Layout containing TextViews as shown in Image below.

I tried in many ways but TextView2 was not getting below TextView1.

Is it possible to draw all the TextViews within 1 Relative Layout.

PS - I have to use Relative Layout, as have to use Right of.

Thank You

答:
Try this :

```<code><?xml version="1.0" encoding="utf-8"?>

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 1"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 2"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="20dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Text View 3"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 4"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="55dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="55dp"
        android:text="Text View 5"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 6"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="85dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="85dp"
        android:text="Text View 7"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />
</RelativeLayout>
</code>```

Title: Designing Relative Layout

Body:
Try this :

<?xml version="1.0" encoding="utf-8"?>

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 1"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 2"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="20dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Text View 3"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 4"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="55dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="55dp"
        android:text="Text View 5"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Text View 6"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="85dp"
        android:textSize="20sp"
        android:gravity="start" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="85dp"
        android:text="Text View 7"
        android:layout_marginRight="20dp"
        android:textSize="20sp"
        android:gravity="end" />
</RelativeLayout>


问:
How to add two kind of values from the same columns in a table
I have a table called Expenses in MySQL data store. The table structure and data are given below:

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|503K    |
   |----|--------|
   |2015|406K    |
   |----|--------|
   |2015|1.2M    |
   |----|--------|
   |2016|700K    |
   |----|--------|
   |2016|900K    |
   |----|--------|
   |2016|3.2M    |
   |----|--------|
   |2016|4.7M    |
   ---------------
</code>```

I need to take the sum of all values ending with 'K', group the result by year and multiply the result with 1000. Likewise, I need to take the sum of all the values ending with 'M', group the result by year and multiply the result with 1000000. Finally, I need to add the results of both K values and M values and obtain the total expenses for every year. My final table should look like this in two different formats:

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2109000 |
   |----|--------|
   |2016|9500000 |
   |----|--------|
</code>```

or

```<code>   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2.1M    |
   |----|--------|
   |2016|9.5M    |
   |----|--------|
</code>```

Any suggestions or guidelines?

答:
Even if mysql does allow you to add values ending with non-numeric characters I would suggest you don't get into the habit of thinking that other sql dialects do the same.

```<code>select year,
         cast(
         sum(case when instr(expenses,'k') > 0.0 then
                cast(replace(expenses,'k','') as decimal(15,2)) * 1000
                when instr(expenses,'m') > 0.0 then
                cast(replace(expenses,'m','') as decimal(15,2)) * 1000000
         end
         )
         as int ) en
from t
group by year
</code>```

Result

```<code>+------+---------+
| year | en      |
+------+---------+
| 2015 | 2109000 |
| 2016 | 9500000 |
+------+---------+
2 rows in set, 7 warnings (0.00 sec)
</code>```

Body:
I have a table called Expenses in MySQL data store. The table structure and data are given below:

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|503K    |
   |----|--------|
   |2015|406K    |
   |----|--------|
   |2015|1.2M    |
   |----|--------|
   |2016|700K    |
   |----|--------|
   |2016|900K    |
   |----|--------|
   |2016|3.2M    |
   |----|--------|
   |2016|4.7M    |
   ---------------

I need to take the sum of all values ending with 'K', group the result by year and multiply the result with 1000. Likewise, I need to take the sum of all the values ending with 'M', group the result by year and multiply the result with 1000000. Finally, I need to add the results of both K values and M values and obtain the total expenses for every year. My final table should look like this in two different formats:

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2109000 |
   |----|--------|
   |2016|9500000 |
   |----|--------|

or

   ---------------
   |YEAR|Expenses|
   |----|--------|
   |2015|2.1M    |
   |----|--------|
   |2016|9.5M    |
   |----|--------|

Any suggestions or guidelines?

Body:
Even if mysql does allow you to add values ending with non-numeric characters I would suggest you don't get into the habit of thinking that other sql dialects do the same.

select year,
         cast(
         sum(case when instr(expenses,'k') > 0.0 then
                cast(replace(expenses,'k','') as decimal(15,2)) * 1000
                when instr(expenses,'m') > 0.0 then
                cast(replace(expenses,'m','') as decimal(15,2)) * 1000000
         end
         )
         as int ) en
from t
group by year

Result

+------+---------+
| year | en      |
+------+---------+
| 2015 | 2109000 |
| 2016 | 9500000 |
+------+---------+
2 rows in set, 7 warnings (0.00 sec)


问:
installation of zend studio 8 in ubuntu
When i try to install the zend studio it is not installing. Nothing happens if i click on the installation file. can you please give me the solution for this problem?</p>

答:
First, check that you have the correct version: I'll presume you want just the IDE, not the whole Virtual Development Environment (which is a whole virtual machine image for use with VMware and such). The downloaded file should end with .tar.gz (not .msi nor .dmg).

Next, you'll want to unzip the archive file, which you can do either in the GUI (double-click to open the archive, click "Extract..." and choose a directory to unzip into), or via the shell (tar zxvf filename.tar.gz).

Then you'll go into the directory you just extracted and look for the "ZendStudio" program and double-click (GUI) or run by name (cd into the directory, type ZendStudio to run).

You may need to check that the program is executable; in the GUI you can change this by right-clicking on the file and editing the properties, or in the shell you can type chmod +x ZendStudio.

Further directions are on this page in the Zend Studio guide, but they're not very detailed. Hope that helps!

Title: installation of zend studio 8 in ubuntu