问:
regex for javascript pattern
```<code><input type="text" name="address" pattern="[0-9a-zA-Z ,\.\/\-&']{0,}">
</code>```

<p>It will allow all except of few special characters but i don't want '//' '///' or any special character repetition like this. what should i change ? </p>

答:
You need to re-write the pattern as

```<code>pattern="(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?"
</code>```

See JS demo:

<form>
<input type="text" name="address" pattern="(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?">
<input type="submit">
</form>```
</div>
</div>
</p>

<p>Note that <code>^</code> and <code>$</code> are added by default, but in case you are using some additional frameworks that override the <em>pattern</em> attribute, you need to add the anchors to the pattern explicitly:</p>

```^(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?$
```

Details:

^ - start of a string

(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]*)*)? - an optional non-capturing group matching 1 or 0 occurrences of:

[0-9a-zA-Z]* - zero or more ASCII letters/digits

(?:[ ,./&'-][0-9a-zA-Z]*)* - 0 or more occurrences of:

[ ,./&'-] - a space, ,, ., / (no need to escape it!), &, ' or - (no need to escape it at the end of the character class, but you can)

[0-9a-zA-Z]+ - one or more ASCII letters/digits

$ - end of string.

Title: regex for javascript pattern

Body:
<input type="text" name="address" pattern="[0-9a-zA-Z ,\.\/\-&']{0,}">

It will allow all except of few special characters but i don't want '//' '///' or any special character repetition like this. what should i change ?

Body:
You need to re-write the pattern as

pattern="(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?"

See JS demo:

<form>
<input type="text" name="address" pattern="(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?">
<input type="submit">
</form>

Note that ^ and $ are added by default, but in case you are using some additional frameworks that override the pattern attribute, you need to add the anchors to the pattern explicitly:

^(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]+)*)?$

Details:

^ - start of a string

(?:[0-9a-zA-Z]*(?:[ ,./&'-][0-9a-zA-Z]*)*)? - an optional non-capturing group matching 1 or 0 occurrences of:

[0-9a-zA-Z]* - zero or more ASCII letters/digits

(?:[ ,./&'-][0-9a-zA-Z]*)* - 0 or more occurrences of:

[ ,./&'-] - a space, ,, ., / (no need to escape it!), &, ' or - (no need to escape it at the end of the character class, but you can)

[0-9a-zA-Z]+ - one or more ASCII letters/digits

$ - end of string.


来源: stackexchange

问:
How to create Most Recently Used list in android studio
Im new to app building and im building an application which stores a profile and data. i want to add an activity where i can display a list of the most recently viewed profiles. Where do i start???</p>

答:
You can get the timestamp when viewing profile, and store it to profiles table in an additional column in your database. Then when you getting the list of profiles just sort them by column timestamp and show in given way.

To access timestamp you can use next code snippet:

```<code>long timestamp = new Date().getTime();
</code>```

Just call it when opening profile and store received value to the database if the value already exists - just update it.

ContentLicense: CC BY-SA 3.0

Body:
You can get the timestamp when viewing profile, and store it to profiles table in an additional column in your database. Then when you getting the list of profiles just sort them by column timestamp and show in given way.

To access timestamp you can use next code snippet:

long timestamp = new Date().getTime();

Just call it when opening profile and store received value to the database if the value already exists - just update it.


问:
When using the matrix command on a dataframe, it produces a list
Hopefully I haven't missed this being asked elsewhere when I looked, it seems basic enough that it should already be addressed but I couldn't find it.

I have a data frame (data_ordered) that looks like this:

```<code>  LAME_chem Year       prop
1    BR_Res 2006 0.07731959
4    BR_Res 2007 0.15568862
7    BR_Res 2008 0.04494382
2    FW_Res 2006 0.12886598
5    FW_Res 2007 0.01796407
8    FW_Res 2008 0.34831461
3   Migrant 2006 0.79381443
6   Migrant 2007 0.82634731
9   Migrant 2008 0.60674157
</code>```

Where both LAME_chem and Year are factors.

I am attempting to convert it to a matrix with the following code:

```<code>data = matrix(data_ordered, ncol = 3, byrow = TRUE)
</code>```

it produces a list of 3 elements, the first being the 3 levels of LAME_chem, the second being the levels of Year, and the third being all the values of prop. What's going on? This should be relatively straightforward shouldn't it?

-edit- I figured it out. The code I wrote apparently asked it to make three matrices, one of each column, when what I wanted was a matrix of the prop values with the rows and columns being the LAME_chem and Years, using data_ordered$prop worked

```<code>data = matrix(data_ordered$prop, ncol = 3, byrow = TRUE)
</code>```

答:
For the issue as I originally described it, @AdamSpannbauer had the best solution:

```<code>data = as.matrix(data_ordered)
</code>```

For what I was actually trying to do, I had to specifically call just the column I was trying to turn into a matrix

```<code>data = matrix(data_ordered$prop, ncol = 3, byrow = TRUE)
</code>```

Body:
Hopefully I haven't missed this being asked elsewhere when I looked, it seems basic enough that it should already be addressed but I couldn't find it.

I have a data frame (data_ordered) that looks like this:

  LAME_chem Year       prop
1    BR_Res 2006 0.07731959
4    BR_Res 2007 0.15568862
7    BR_Res 2008 0.04494382
2    FW_Res 2006 0.12886598
5    FW_Res 2007 0.01796407
8    FW_Res 2008 0.34831461
3   Migrant 2006 0.79381443
6   Migrant 2007 0.82634731
9   Migrant 2008 0.60674157

Where both LAME_chem and Year are factors.

I am attempting to convert it to a matrix with the following code:

data = matrix(data_ordered, ncol = 3, byrow = TRUE)

it produces a list of 3 elements, the first being the 3 levels of LAME_chem, the second being the levels of Year, and the third being all the values of prop. What's going on? This should be relatively straightforward shouldn't it?

-edit- I figured it out. The code I wrote apparently asked it to make three matrices, one of each column, when what I wanted was a matrix of the prop values with the rows and columns being the LAME_chem and Years, using data_ordered$prop worked

data = matrix(data_ordered$prop, ncol = 3, byrow = TRUE)

Body:
For the issue as I originally described it, @AdamSpannbauer had the best solution:

data = as.matrix(data_ordered)

For what I was actually trying to do, I had to specifically call just the column I was trying to turn into a matrix

data = matrix(data_ordered$prop, ncol = 3, byrow = TRUE)


问:
Read Custom Header from https request redirected to IBM BPM 8.5.7
I am routing IBM BPM Process Portal URL from custom portal, when I Log in to custom portal it stores user ID and password in custom http header.
IBM BPM Process Portal not able to understand custom http header and shows login page to authenticate user again.
Is it possible to read custom http header in Process Portal in IBM BPM Std 8.5.7, so it will work like SSO.

Please suggest.

Thank.

答:
This is not so much a "portal" problem as a "WebSphere" problem.  The WebSphere container is in charge of authenticating the user.  That is when a request comes in to an IBM BPM URL, the BPM code asks WebSphere "Hey, is this request authenticated?"  If the answer is yes, it allows the user to get to the URL.  If the answer is no, it does whatever WebSphere has been told is the right next action for an unauthenticated user requests.

What you really need is a "Trust Authentication Interceptor" or TAI.  This is a piece of software you add to WebSphere that can use a different mechanism from the standard login page to Authenticate the user to the WAS container.  If the other software is using a standard SSO technology then it maybe that the software creator already has a TAI you can install.  If it is a "roll your own" solution someone needs to write one.

You can easily find many articles from IBM on how to write a TAI.  Here is an IBM Redbook I found that touches on the topic.

-AP


问:
Create a variable from another variable in shell script
In a shell script I will store the output as a variable like below

```<code>Test=$(/home/$USER/import.py $table)
</code>```

Now this Test variable will have more than 2 lines like below

```<code>table= 123_test
min_id=1
max_id=100
123_test,1,100
</code>```

Now I want to store the last line of the Test variable as another variable called output.

I have tried like below. But not getting the desired result

```<code>output=`$test | tail -n 1`
</code>```

Can we create a variable from another variable in a shell script. If yes, How can we do that?

答:
Use echo to pipe the variable to the other command.

```<code>output=$(echo "$test" | tail -1)
</code>```

or a here-string:

```<code>output=$(tail -1 <<<"$test")
</code>```

Don't forget to quote the variable in both cases, otherwise all the lines will be combined.

Finally, you can use a parameter expansion operator to select the last line, instead of using tail:

```<code>output=${test##*$'\n'}
</code>```

Body:
In a shell script I will store the output as a variable like below

Test=$(/home/$USER/import.py $table)

Now this Test variable will have more than 2 lines like below

table= 123_test
min_id=1
max_id=100
123_test,1,100

Now I want to store the last line of the Test variable as another variable called output.

I have tried like below. But not getting the desired result

output=`$test | tail -n 1`

Can we create a variable from another variable in a shell script. If yes, How can we do that?

Body:
Use echo to pipe the variable to the other command.

output=$(echo "$test" | tail -1)

or a here-string:

output=$(tail -1 <<<"$test")

Don't forget to quote the variable in both cases, otherwise all the lines will be combined.

Finally, you can use a parameter expansion operator to select the last line, instead of using tail:

output=${test##*$'\n'}


问:
Reveal text letter by letter but retain html formatting
I need my text to retain a few html formatting tags, to change the colour of the text as it goes along for example and to show some graphic icons that are placed in my text. My code takes the text from an existing hidden paragraph, blanks the paragraph, unhides it and then reveals it letter by letter as follows.

```<code>        var NextHighlight = HighlightsTop.find('.newhidden').first().closest('p'); // Find the paragraph.
        // Put the text from this highlight paragraph into a variable and remove it from the paragraph, so that we can put it back letter-by-letter below.
        var HighlightText = NextHighlight.html();
        NextHighlight.html("");
        NextHighlight.removeClass('newhidden');

        // Add the text back in, letter by letter.
        showText(NextHighlight, HighlightText, 0, 5);

....

    // The letter-by-letter function.
    var showText = function (target, message, index, interval) {
    if (index < message.length) {
        $(target).append(message[index++]);
        setTimeout(function () { showText(target, message, index, interval); }, interval);
        }
    }
</code>```

The problem is that the html tags are now just shown as straight text in the line. If I change 'html' to 'text' in the elements, it doesn't show the tags but I don't get the formatting either.

EDIT - UPDATE below....

After updating with the answer below, my code now looks like this. I should point out that this happens when the user hits a button, so I'm adding the code from the start of the button click. Maybe there's an error somewhere that I can't see because when I click the button now, I get nothing at all. I'm not seeing any errors in the console either, wondering if I've just missed a ; somewhere...

```<code>$(document).on('click', '.highlight_button',
    function () {
        var MatchReportTop = $(this).closest('.match_div');
        var HighlightsTop = $(this).closest('.highlights');
        var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];

        // recursively get the text nodes
        (function recursiveGetTextNodes(node) {
          if(node.nodeType === 3) {
            // we're a text node? great, store it.  We'll store a clone and the original so we don't lose our place.
            HighlightTextNodes.push({
              active: node,
              ref: node.cloneNode()
            });
            // clear out the original.
            node.textContent = '';
          } else {
            // no text node.  go deeper.
            for(var i = 0, len = node.childNodes.length; i < len; i++) {
              recursiveGetTextNodes(node.childNodes[i]);
            }
          }
        })(NextHighlight.get(0))

        // Add the text back in, letter by letter.
        showText(HighlightTextNodes, 5);

        if (NextHighlight.hasClass('FullTime')) {
            CompleteReveal(MatchReportTop);
        }
});

// The letter-by-letter function.
function showText(target, interval) {
  // to know what we're currently working on, we need to filter
  // the text nodes by a check to see if they are already fully
  // "typed" out.  If the content doesn't match, keep it.  Also,
  // `shift()` off the first one.  That's the one we'll edit
  // this go around.
  var current = target.filter(function(a){
    return a.active.textContent != a.ref.textContent;
  }).shift();

  // if we have a node to work with, the process is not
  // completed. Once `current` is false, we know we've completed
  // the process.
  if (current) {
    // grab the reference node's text up to the active node's
    // length +1 to get the current text plus one letter.
    current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
    // rinse and repeat.
    setTimeout(function () {
      showText(target, interval);
    }, interval);
  }
}
</code>```

答:
So you want to incrementally show text, but it has to retain the HTML.  You could strip the tags and reapply them.  You could ignore the tags as you parse the text and just paste them in in their entirety.  Those are a couple options that first came to mind, but I kind of dislike both of them.

If you rethink the problem, there might be a better solution.  You could target text nodes only and incrementally display each letter from those text nodes.  This is the plan I settled on after rethinking it.  The basic flow would be this:

Gather the text nodes, store their original nodes (that are still attached to the DOM)

store a clone of the node for reference later

empty out the text node

recursively call a timed method that looks for the first node that doesn't match the reference node

add a single letter to that node from the reference node

repeat until all nodes match the reference nodes

// get the `newhidden`'s closest parent paragraph and prepare
// the array that will hold all the text nodes of that paragraph
var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];

// recursively get the text nodes
(function recursiveGetTextNodes(node) {
  if(node.nodeType === 3) {
    // we're a text node? great, store it.  We'll store a clone
    // and the original so we don't lose our place.
    HighlightTextNodes.push({
      active: node,
      ref: node.cloneNode()
    });
    // clear out the original.
    node.textContent = '';
  } else {
    // no text node.  go deeper.
    for(var i = 0, len = node.childNodes.length; i < len; i++) {
      recursiveGetTextNodes(node.childNodes[i]);
    }
  }
})(NextHighlight.get(0))

// Add the text back in, letter by letter.
showText(HighlightTextNodes, 5);

// The letter-by-letter function.
function showText(target, interval) {
  // to know what we're currently working on, we need to filter
  // the text nodes by a check to see if they are already fully
  // "typed" out.  If the content doesn't match, keep it.  Also,
  // `shift()` off the first one.  That's the one we'll edit
  // this go around.
  var current = target.filter(function(a){
    return a.active.textContent != a.ref.textContent;
  }).shift();

  // if we have a node to work with, the process is not
  // completed. Once `current` is falsy, we know we've completed
  // the process.
  if (current) {
    // grab the reference node's text up to the active node's
    // length +1 to get the current text plus one letter.
    current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
    // rinse and repeat.
    setTimeout(function () {
      showText(target, interval);
    }, interval);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, impedit <strong class="newhidden">labore <span>test</span> architecto</strong> quasi, possimus hic velit. Quibusdam quisquam illum quae doloremque, quis iste consequatur vero quaerat molestias doloribus dicta facilis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas iusto laborum hic optio aliquam, adipisci a, dolore rem dolores harum voluptas cum! Similique, velit, commodi. Vero molestias, nobis ducimus nemo.</p></code>```

Body:
I need my text to retain a few html formatting tags, to change the colour of the text as it goes along for example and to show some graphic icons that are placed in my text. My code takes the text from an existing hidden paragraph, blanks the paragraph, unhides it and then reveals it letter by letter as follows.

        var NextHighlight = HighlightsTop.find('.newhidden').first().closest('p'); // Find the paragraph.
        // Put the text from this highlight paragraph into a variable and remove it from the paragraph, so that we can put it back letter-by-letter below.
        var HighlightText = NextHighlight.html();
        NextHighlight.html("");
        NextHighlight.removeClass('newhidden');

        // Add the text back in, letter by letter.
        showText(NextHighlight, HighlightText, 0, 5);

....

    // The letter-by-letter function.
    var showText = function (target, message, index, interval) {
    if (index < message.length) {
        $(target).append(message[index++]);
        setTimeout(function () { showText(target, message, index, interval); }, interval);
        }
    }

The problem is that the html tags are now just shown as straight text in the line. If I change 'html' to 'text' in the elements, it doesn't show the tags but I don't get the formatting either.

EDIT - UPDATE below....

After updating with the answer below, my code now looks like this. I should point out that this happens when the user hits a button, so I'm adding the code from the start of the button click. Maybe there's an error somewhere that I can't see because when I click the button now, I get nothing at all. I'm not seeing any errors in the console either, wondering if I've just missed a ; somewhere...

$(document).on('click', '.highlight_button',
    function () {
        var MatchReportTop = $(this).closest('.match_div');
        var HighlightsTop = $(this).closest('.highlights');
        var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];

        // recursively get the text nodes
        (function recursiveGetTextNodes(node) {
          if(node.nodeType === 3) {
            // we're a text node? great, store it.  We'll store a clone and the original so we don't lose our place.
            HighlightTextNodes.push({
              active: node,
              ref: node.cloneNode()
            });
            // clear out the original.
            node.textContent = '';
          } else {
            // no text node.  go deeper.
            for(var i = 0, len = node.childNodes.length; i < len; i++) {
              recursiveGetTextNodes(node.childNodes[i]);
            }
          }
        })(NextHighlight.get(0))

        // Add the text back in, letter by letter.
        showText(HighlightTextNodes, 5);

        if (NextHighlight.hasClass('FullTime')) {
            CompleteReveal(MatchReportTop);
        }
});

// The letter-by-letter function.
function showText(target, interval) {
  // to know what we're currently working on, we need to filter
  // the text nodes by a check to see if they are already fully
  // "typed" out.  If the content doesn't match, keep it.  Also,
  // `shift()` off the first one.  That's the one we'll edit
  // this go around.
  var current = target.filter(function(a){
    return a.active.textContent != a.ref.textContent;
  }).shift();

  // if we have a node to work with, the process is not
  // completed. Once `current` is false, we know we've completed
  // the process.
  if (current) {
    // grab the reference node's text up to the active node's
    // length +1 to get the current text plus one letter.
    current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
    // rinse and repeat.
    setTimeout(function () {
      showText(target, interval);
    }, interval);
  }
}

Body:
So you want to incrementally show text, but it has to retain the HTML.  You could strip the tags and reapply them.  You could ignore the tags as you parse the text and just paste them in in their entirety.  Those are a couple options that first came to mind, but I kind of dislike both of them.

If you rethink the problem, there might be a better solution.  You could target text nodes only and incrementally display each letter from those text nodes.  This is the plan I settled on after rethinking it.  The basic flow would be this:

Gather the text nodes, store their original nodes (that are still attached to the DOM)

store a clone of the node for reference later

empty out the text node

recursively call a timed method that looks for the first node that doesn't match the reference node

add a single letter to that node from the reference node

repeat until all nodes match the reference nodes

// get the `newhidden`'s closest parent paragraph and prepare
// the array that will hold all the text nodes of that paragraph
var NextHighlight = $('.newhidden').first().closest('p'), HighlightTextNodes = [];

// recursively get the text nodes
(function recursiveGetTextNodes(node) {
  if(node.nodeType === 3) {
    // we're a text node? great, store it.  We'll store a clone
    // and the original so we don't lose our place.
    HighlightTextNodes.push({
      active: node,
      ref: node.cloneNode()
    });
    // clear out the original.
    node.textContent = '';
  } else {
    // no text node.  go deeper.
    for(var i = 0, len = node.childNodes.length; i < len; i++) {
      recursiveGetTextNodes(node.childNodes[i]);
    }
  }
})(NextHighlight.get(0))

// Add the text back in, letter by letter.
showText(HighlightTextNodes, 5);

// The letter-by-letter function.
function showText(target, interval) {
  // to know what we're currently working on, we need to filter
  // the text nodes by a check to see if they are already fully
  // "typed" out.  If the content doesn't match, keep it.  Also,
  // `shift()` off the first one.  That's the one we'll edit
  // this go around.
  var current = target.filter(function(a){
    return a.active.textContent != a.ref.textContent;
  }).shift();

  // if we have a node to work with, the process is not
  // completed. Once `current` is falsy, we know we've completed
  // the process.
  if (current) {
    // grab the reference node's text up to the active node's
    // length +1 to get the current text plus one letter.
    current.active.textContent = current.ref.textContent.substr(0,current.active.textContent.length + 1);
    // rinse and repeat.
    setTimeout(function () {
      showText(target, interval);
    }, interval);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga, impedit <strong class="newhidden">labore <span>test</span> architecto</strong> quasi, possimus hic velit. Quibusdam quisquam illum quae doloremque, quis iste consequatur vero quaerat molestias doloribus dicta facilis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas iusto laborum hic optio aliquam, adipisci a, dolore rem dolores harum voluptas cum! Similique, velit, commodi. Vero molestias, nobis ducimus nemo.</p>


问:
how to make a child of linearLayout align to parents right programmatically?
I have a linearLayout_child inside another linearLayout_parent.

I want to make linearLayout_child aligned to parent's right.

How can I do this?

what if I want all linearLayout_parent's children be aligned to their parent's right?

I want to do them both programmatically.

update

is there any tool with which I can see the current layout properties and attributes in my Activity's view? The code changes many attributes from the original XMl and it's hard to follow at a specific situation.

here is my xml:

```<code>        <MyTextView
            android:id="@+id/navBarDistance"
            style="@style/NavBarDistance"
            android:textSize="19dp"
            android:text="miles"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <MyTextView
            android:id="@+id/navBarDistanceUnit"
            style="@style/NavBarDistUnit"
            android:textSize="19dp"
            android:text="0.1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            />
    </LinearLayout>
        <LinearLayout
            android:id="@+id/navBarDistanceLayoutRtl"
            android:layout_width="70dp"
            android:layout_height="match_parent"
            android:layout_marginRight="8dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical|right"
            android:orientation="horizontal"
            android:visibility="gone">

            <MyTextViewType
                android:id="@+id/navBarDistanceUnitRtl"
                style="@style/NavBarDistUnit"
                android:textSize="19dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="3dp"
                />

            <MyTextViewType
                android:id="@+id/navBarDistanceRtl"
                style="@style/NavBarDistance"
                android:textSize="19dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
</LinearLayout>
</code>```

and here is parts of the code:

the change to AlerterMode and then coming back to non-alrter more makes navBarDistanceLayoutRtl be aligned to left instead of right

```<code>            if (bIsAlertMode)
            {

...
                if (rtlMode)
                {
                    width = view.findViewById(R.id.navBarDistanceLayoutRtl).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
                    DistanceBar.setMargins(3, 20, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayoutRtl).setLayoutParams(DistanceBar);
                }
                else
                {
                    width = view.findViewById(R.id.navBarDistanceLayout).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
                    DistanceBar.setMargins(3, 20, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayout).setLayoutParams(DistanceBar);

                }

...

            }
            else
            {
   ...

                if (rtlMode)
                {
                    width = view.findViewById(R.id.navBarDistanceLayoutRtl).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                    DistanceBar.setMargins(20, 8, 3, 0);

                    DistanceBar.gravity = RelativeLayout.ALIGN_PARENT_RIGHT;

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setLayoutParams(DistanceBar);

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.navBarDistanceLayout).setVisibility(View.GONE);
                    distance = (TextView)view.findViewById(R.id.navBarDistanceRtl);
                    distanceUnit = (TextView)view.findViewById(R.id.navBarDistanceUnitRtl);
                }
                else
                {
                    width = view.findViewById(R.id.navBarDistanceLayout).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                    DistanceBar.setMargins(0, 8, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayout).setLayoutParams(DistanceBar);

                    DistanceBar.gravity = RelativeLayout.ALIGN_PARENT_LEFT;

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setVisibility(View.GONE);
                    view.findViewById(R.id.navBarDistanceLayout).setVisibility(View.VISIBLE);
                    distance = (TextView)view.findViewById(R.id.navBarDistance);
                    distanceUnit = (TextView)view.findViewById(R.id.navBarDistanceUnit);

                }

                ...
            }
        }
</code>```

答:
I've found a solution in my case, where i'm adding Views to a Linear Layout, just set gravity to TEXT_ALIGNMENT_VIEW_START:

```<code>    LinearLayout row = new LinearLayout(Control.this);
    row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    row.setGravity(View.TEXT_ALIGNMENT_VIEW_START);
</code>```

Body:
I have a linearLayout_child inside another linearLayout_parent.

I want to make linearLayout_child aligned to parent's right.

How can I do this?

what if I want all linearLayout_parent's children be aligned to their parent's right?

I want to do them both programmatically.

update

is there any tool with which I can see the current layout properties and attributes in my Activity's view? The code changes many attributes from the original XMl and it's hard to follow at a specific situation.

here is my xml:

        <MyTextView
            android:id="@+id/navBarDistance"
            style="@style/NavBarDistance"
            android:textSize="19dp"
            android:text="miles"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <MyTextView
            android:id="@+id/navBarDistanceUnit"
            style="@style/NavBarDistUnit"
            android:textSize="19dp"
            android:text="0.1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            />
    </LinearLayout>
        <LinearLayout
            android:id="@+id/navBarDistanceLayoutRtl"
            android:layout_width="70dp"
            android:layout_height="match_parent"
            android:layout_marginRight="8dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical|right"
            android:orientation="horizontal"
            android:visibility="gone">

            <MyTextViewType
                android:id="@+id/navBarDistanceUnitRtl"
                style="@style/NavBarDistUnit"
                android:textSize="19dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="3dp"
                />

            <MyTextViewType
                android:id="@+id/navBarDistanceRtl"
                style="@style/NavBarDistance"
                android:textSize="19dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
</LinearLayout>

and here is parts of the code:

the change to AlerterMode and then coming back to non-alrter more makes navBarDistanceLayoutRtl be aligned to left instead of right

            if (bIsAlertMode)
            {

...
                if (rtlMode)
                {
                    width = view.findViewById(R.id.navBarDistanceLayoutRtl).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
                    DistanceBar.setMargins(3, 20, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayoutRtl).setLayoutParams(DistanceBar);
                }
                else
                {
                    width = view.findViewById(R.id.navBarDistanceLayout).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
                    DistanceBar.setMargins(3, 20, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayout).setLayoutParams(DistanceBar);

                }

...

            }
            else
            {
   ...

                if (rtlMode)
                {
                    width = view.findViewById(R.id.navBarDistanceLayoutRtl).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                    DistanceBar.setMargins(20, 8, 3, 0);

                    DistanceBar.gravity = RelativeLayout.ALIGN_PARENT_RIGHT;

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setLayoutParams(DistanceBar);

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setVisibility(View.VISIBLE);
                    view.findViewById(R.id.navBarDistanceLayout).setVisibility(View.GONE);
                    distance = (TextView)view.findViewById(R.id.navBarDistanceRtl);
                    distanceUnit = (TextView)view.findViewById(R.id.navBarDistanceUnitRtl);
                }
                else
                {
                    width = view.findViewById(R.id.navBarDistanceLayout).getWidth();
                    android.widget.LinearLayout.LayoutParams DistanceBar = new LinearLayout.LayoutParams(width, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                    DistanceBar.setMargins(0, 8, 3, 0);
                    view.findViewById(R.id.navBarDistanceLayout).setLayoutParams(DistanceBar);

                    DistanceBar.gravity = RelativeLayout.ALIGN_PARENT_LEFT;

                    view.findViewById(R.id.navBarDistanceLayoutRtl).setVisibility(View.GONE);
                    view.findViewById(R.id.navBarDistanceLayout).setVisibility(View.VISIBLE);
                    distance = (TextView)view.findViewById(R.id.navBarDistance);
                    distanceUnit = (TextView)view.findViewById(R.id.navBarDistanceUnit);

                }

                ...
            }
        }

Body:
I've found a solution in my case, where i'm adding Views to a Linear Layout, just set gravity to TEXT_ALIGNMENT_VIEW_START:

    LinearLayout row = new LinearLayout(Control.this);
    row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    row.setGravity(View.TEXT_ALIGNMENT_VIEW_START);


问:
MongoDB: use MongoImport with csv to update single field only
I am trying to update a single field in each document in my collection using a csv and Mongoimport with –upsert included.
However the process removes all other fields in the document.

I have a Books Collection with documents like:

```<code>{

    "_id" : "knOIv8ZUUK",
    "Price" : 2.2,
    "Title" : "Rats Ahoy"
}

{

    "_id" : "okYEGuWznv",
    "Price" : 3.3,
    "Title" : "Friendly Fish"
}
</code>```

a csv file:

```<code>_id,Price

knOIv8ZUUK,2.2

okYEGuWznv,3.3
</code>```

And import using:

```<code>mongoimport  --db local  --collection Books --upsert  --type csv
             --headerline  --file c:\import\newPrice
</code>```

With results deleting the Title field

```<code>{

    "_id" : "knOIv8ZUUK",
    "Price" : 2.2
}

{

    "_id" : "okYEGuWznv",
    "Price" : 3.3
}
</code>```

I, incorrectly, thought Upsert would just update an imported field.
So is there another process I can use to update just 1 field in large number of documents?
thanks

答:
New feature has been added since version 3.4 Documentation here.

Check this option

```<code>--mode insert|upsert|merge
</code>```

In your case you can use this may be:

```<code>--mode merge
</code>```

Body:
I am trying to update a single field in each document in my collection using a csv and Mongoimport with –upsert included.
However the process removes all other fields in the document.

I have a Books Collection with documents like:

{

    "_id" : "knOIv8ZUUK",
    "Price" : 2.2,
    "Title" : "Rats Ahoy"
}

{

    "_id" : "okYEGuWznv",
    "Price" : 3.3,
    "Title" : "Friendly Fish"
}

a csv file:

_id,Price

knOIv8ZUUK,2.2

okYEGuWznv,3.3

And import using:

mongoimport  --db local  --collection Books --upsert  --type csv
             --headerline  --file c:\import\newPrice

With results deleting the Title field

{

    "_id" : "knOIv8ZUUK",
    "Price" : 2.2
}

{

    "_id" : "okYEGuWznv",
    "Price" : 3.3
}

I, incorrectly, thought Upsert would just update an imported field.
So is there another process I can use to update just 1 field in large number of documents?
thanks

Body:
New feature has been added since version 3.4 Documentation here.

Check this option

--mode insert|upsert|merge

In your case you can use this may be:

--mode merge


问:
How to run firefox program in linux and get its output on windows
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

```<code># firefox
Error: GDK_BACKEND does not match available displays
</code>```

Please help

答:
You need to supply Firefox with a virtual graphic screen. You could for example install XMing on Windows, and configure PuTTY to "forward X connection".

Then Firefox will "draw" on the screen, and the screen will be transmitted to your PC. Your mouse and keyboard signals will be transmitted to the remote server.

This setup should go about six times as slow than your current Web connection, since your connection to the Internet, which is the bottleneck, is unchanged, and now you're pushing massive X data on it instead of browsing elements.

A better possibility would be to install Squid proxy on the remote server, then configure your PuTTY to open a "tunnel" from remote port 127.0.0.1:3128 to local port 3128, and finally instructing your Windows Firefox to use 127.0.0.1 on port 3128 as proxy for all protocols.

This way, the browsing information will be downloaded remotely, compressed and forwarded to you.

This should be around twice as slow as your current connection (unless you're connecting with old Web sites without gz/deflate support, and mostly text with no images. In that case you might experience a connection up to five times as fast, albeit with a somewhat increased latency.

(An even better but even more complicated setup involves running a local proxy, connected through SSH tunnel to a remote proxy).

In all cases your navigation might appear as coming from the remote machine, but to ensure there's no information leak, you need to properly configure the proxy.

ContentLicense: CC BY-SA 4.0

Body:
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

# firefox
Error: GDK_BACKEND does not match available displays

Please help


问:
Ambiguous overload for class operator>>
I am trying to overload the class operator for istream (>>) and I am getting the error Ambiguous overload for operator>> for some reason. The operator for ostream works perfectly but istream does not.
Does someone know why?

```<code>#include <iostream>
#include <fstream>
using namespace std;

class Person
{
    public:
      Person(string name="Empty", int num=0)
      :name(name), num(num){}

      friend istream& operator>> (istream& is, Person& o)
      {
        is >> o.name>> o.num;
         return is;
      }

      friend ostream& operator<< (ostream& os, Person& o)
      {
        return os << o.name<< " " << o.num<< endl;
      }
    private:
      string name;
      int num;

};

int main()
{
    ifstream fajl("input.txt");

    Person a();
    fajl >> a ;
    cout << a ;

}
</code>```

input.txt:

```<code>Name1 15
Name2 16
</code>```

I get the error in line: fajl >> a ;

答:
This is not a variable declaration:

```<code>Person a();
</code>```

is a function declaration. The correct code to declare a variable is:

```<code>Person a;
</code>```

Title: Ambiguous overload for class operator>>

Body:
I am trying to overload the class operator for istream (>>) and I am getting the error Ambiguous overload for operator>> for some reason. The operator for ostream works perfectly but istream does not.
Does someone know why?

#include <iostream>
#include <fstream>
using namespace std;

class Person
{
    public:
      Person(string name="Empty", int num=0)
      :name(name), num(num){}

      friend istream& operator>> (istream& is, Person& o)
      {
        is >> o.name>> o.num;
         return is;
      }

      friend ostream& operator<< (ostream& os, Person& o)
      {
        return os << o.name<< " " << o.num<< endl;
      }
    private:
      string name;
      int num;

};

int main()
{
    ifstream fajl("input.txt");

    Person a();
    fajl >> a ;
    cout << a ;

}

input.txt:

Name1 15
Name2 16

I get the error in line: fajl >> a ;

Body:
This is not a variable declaration:

Person a();

is a function declaration. The correct code to declare a variable is:

Person a;


问:
Strange RAM behavior in Kingfisher
I use Kingfisher to load images into the Card View (UIView), as in the tinder, I set the Kingfisher to cache the images to disk, but during the paging of the cards, the memory consumption increases dramatically from 39 megabytes to 247 and after a while again becomes 39, But the problem is that when the memory is freed, in the application for a second UI slows down (I think this is blocked by the main thread). This problem is similar to this one. How can I fix it?

I set the settings for Kingfisher in AppDelegate in didFinishLaunchingWithOptions

```<code>fileprivate func setupKingfisherSettings() {
        let megabytes: UInt = 300
        ImageCache.default.maxDiskCacheSize = megabytes * 1024 * 1024
        ImageCache.default.maxMemoryCost = 1
    }
</code>```

Snippet of code. When I removed this code, this problem did not occur.

```<code>private func downloadImages(_ card: CardModel) {
    if let placeAvatarURLString = card.photoURLsProperties.placePhotoURLs.first {
        if let placeAvatarURL = URL(string: placeAvatarURLString) {
            venueImageView.kf.indicatorType = .activity
            venueImageView.kf.setImage(with: placeAvatarURL)
        } else {
            venueImageView.image = UIImage(named: "CardDefaultImage")
        }
    } else if let eventLogoURLPath = card.photoURLsProperties.placeLogoURLs.first {
        if let url = URL(string: eventLogoURLPath) {
            venueImageView.kf.indicatorType = .activity
            venueImageView.kf.setImage(with: url)
        } else {
            venueImageView.image = UIImage(named: "CardDefaultImage")
        }
    } else {
        venueImageView.image = UIImage(named: "CardDefaultImage")
    }
}
</code>```

Updated:: I found a regularity when this happens. This jump in memory occurs when ImageCache extracts an image that is larger than 5 megabytes. I found it using debugPrint in this method diskImage, if the image is equal to or more than 5 megabytes, then there is a jump, if 4 megabytes, then everything is fine.

I'm testing on the iPhone 7, more than 74 gigabytes of free memory.

```<code> func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? {
        if let data = diskImageData(forComputedKey: key) {
            debugPrint("ImageCache data.count", data.count / 1024 / 1024)
            return serializer.image(with: data, options: options)
        } else {
            return nil
        }
    }
</code>```

答:
At the moment I solved my problem, I wrote my Custom CacheSerializer, and I compress the images up to 3 megabytes. But I'm interested in other answers, how to solve this problem.</p>

```<code>import Kingfisher

struct AppNameKingfisherCacheSerializer: CacheSerializer {

    func data(with image: Image, original: Data?) -> Data? {
        return image.compressToData(3)
    }

    func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
        return UIImage(data: data)
    }

}
</code>```

Title: Strange RAM behavior in Kingfisher

Body:
I use Kingfisher to load images into the Card View (UIView), as in the tinder, I set the Kingfisher to cache the images to disk, but during the paging of the cards, the memory consumption increases dramatically from 39 megabytes to 247 and after a while again becomes 39, But the problem is that when the memory is freed, in the application for a second UI slows down (I think this is blocked by the main thread). This problem is similar to this one. How can I fix it?

I set the settings for Kingfisher in AppDelegate in didFinishLaunchingWithOptions

fileprivate func setupKingfisherSettings() {
        let megabytes: UInt = 300
        ImageCache.default.maxDiskCacheSize = megabytes * 1024 * 1024
        ImageCache.default.maxMemoryCost = 1
    }

Snippet of code. When I removed this code, this problem did not occur.

private func downloadImages(_ card: CardModel) {
    if let placeAvatarURLString = card.photoURLsProperties.placePhotoURLs.first {
        if let placeAvatarURL = URL(string: placeAvatarURLString) {
            venueImageView.kf.indicatorType = .activity
            venueImageView.kf.setImage(with: placeAvatarURL)
        } else {
            venueImageView.image = UIImage(named: "CardDefaultImage")
        }
    } else if let eventLogoURLPath = card.photoURLsProperties.placeLogoURLs.first {
        if let url = URL(string: eventLogoURLPath) {
            venueImageView.kf.indicatorType = .activity
            venueImageView.kf.setImage(with: url)
        } else {
            venueImageView.image = UIImage(named: "CardDefaultImage")
        }
    } else {
        venueImageView.image = UIImage(named: "CardDefaultImage")
    }
}

Updated:: I found a regularity when this happens. This jump in memory occurs when ImageCache extracts an image that is larger than 5 megabytes. I found it using debugPrint in this method diskImage, if the image is equal to or more than 5 megabytes, then there is a jump, if 4 megabytes, then everything is fine.

I'm testing on the iPhone 7, more than 74 gigabytes of free memory.

 func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? {
        if let data = diskImageData(forComputedKey: key) {
            debugPrint("ImageCache data.count", data.count / 1024 / 1024)
            return serializer.image(with: data, options: options)
        } else {
            return nil
        }
    }

Body:
At the moment I solved my problem, I wrote my Custom CacheSerializer, and I compress the images up to 3 megabytes. But I'm interested in other answers, how to solve this problem.

import Kingfisher

struct AppNameKingfisherCacheSerializer: CacheSerializer {

    func data(with image: Image, original: Data?) -> Data? {
        return image.compressToData(3)
    }

    func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
        return UIImage(data: data)
    }

}


问:
How to extract all span's on a page using iMacros?
```<code><span class="Fcontainer"><a href="http://www.codechef.com" rel="noopener nofollow" target="_blank" onclick="return MN.openUrl(this);" class="external_link" data-qt-tooltip="codechef.com" data-tooltip="attached">Programming Competition,Programming Contest,Online Computer Programming</a></span>
<span class="Fcontainer"><a href="http://www.hackerrank.com" rel="noopener nofollow" target="_blank" onclick="return MN.openUrl(this);" class="external_link" data-qt-tooltip="hackerrank.com">HackerRank</a></span>
</code>```

A number of span's with same class is there a webpage.

I am using

```<code>TAG POS={{!LOOP}} TYPE=SPAN ATTR=CLASS:Fcontainer* EXTRACT=TXT
SET !VAR4 {{!EXTRACT}}
</code>```

But I am only to save 1 entry to my csv file column, that is only "Programming Competition,Programming Contest,Online Computer Programming"

How do I save all the span's with same class to csv file, with multiple columns?

答: Use Play Loop. Code is tested and works.

Body:
Programming Competition,Programming Contest,Online Computer Programming
HackerRank

A number of span's with same class is there a webpage.

I am using

TAG POS={{!LOOP}} TYPE=SPAN ATTR=CLASS:Fcontainer* EXTRACT=TXT
SET !VAR4 {{!EXTRACT}}

But I am only to save 1 entry to my csv file column, that is only "Programming Competition,Programming Contest,Online Computer Programming"

How do I save all the span's with same class to csv file, with multiple columns?


问:
How to bind a RibbonButton to a command with parameters?
I have a ribbon with many ribbon-tabs and ribbon-buttons.
This a common Ribbon that act on many views. I'm in a situation that I need a reference to the XamDataGrid in order for the ribbon-button hooked command to execute properly.

I have no clue how to pass a reference to the Ribbon or even deal with it keeping in mind this a common Ribbon menu.

Please note that I'm using MVVM.

Thank you

答:
Look at telerik site.
http://docs.telerik.com/devtools/wpf/mvvm-helpers/common-event-to-command-behavior

```<code><telerik:EventToCommandBehavior.EventBindings>
<telerik:EventBinding Command="{Binding CustomCommand}" EventName="MouseLeftButtonDown" RaiseOnHandledEvents="True"
                      CommandParameter="This is a command parameter!"/>
</code>```

Body:
Look at telerik site.
http://docs.telerik.com/devtools/wpf/mvvm-helpers/common-event-to-command-behavior

<telerik:EventToCommandBehavior.EventBindings>
<telerik:EventBinding Command="{Binding CustomCommand}" EventName="MouseLeftButtonDown" RaiseOnHandledEvents="True"
                      CommandParameter="This is a command parameter!"/>


问:
Stop sourcing a file
I have deleted phpbrew and now having this error when starting up the terminal:

source: Error encountered while sourcing file “/home/machine/.phpbrew/phpbrew.fish”:
source: No such file or directory

How do I get a list of all sourced files and stop sourcing a certain file?

答:
There is no way in general to get a list of all sourced files. Such information isn't recorded in any single place, or even multiple, places that can be checked with 100% certainty you didn't overlook one. However, in this case that probably isn't necessary since it is almost certainly going to be due to a source command run from your fish config script or a script it runs. So

```<code>cd ~/.config/fish
grep source **.fish
grep '\. ' **.fish
</code>```

The latter because . is an alias for source. You may not find source phpbrew.fish because that script may be sourced by a plugin manager like fisherman or oh-my-fish. In which case it might be loaded indirectly by the plugin manager.

Title: Stop sourcing a file

Body:
There is no way in general to get a list of all sourced files. Such information isn't recorded in any single place, or even multiple, places that can be checked with 100% certainty you didn't overlook one. However, in this case that probably isn't necessary since it is almost certainly going to be due to a source command run from your fish config script or a script it runs. So

cd ~/.config/fish
grep source **.fish
grep '\. ' **.fish

The latter because . is an alias for source. You may not find source phpbrew.fish because that script may be sourced by a plugin manager like fisherman or oh-my-fish. In which case it might be loaded indirectly by the plugin manager.


问:
averaging by months with daily data
I have daily data with my matrix, divided into 6 columns -  "Years, months, days, ssts, anoms, missing ".

I want to calculate the average of each month of SST in each year. (For example - 1981 - september - avg values sts of all days in sept), and I want to do the same for all the years. i am trying to work, my code, but am unable to do so.

答:
You should use dplyr package in R. For this, we will call your data df

```<code>require(dplyr)

df.mnths <- df %>%
            group_by(Years, months) %>%
            summarise(Mean.SST = mean(SSTs))

df.years <- df %>%
            group_by(Years) %>%
            summarise(Mean.SST = mean(SSTs))
</code>```

This is two new data sets that will have the mean(SST) for each month of each year in df.mnths, and another dataset that will have mean(SST) for all years in df.years.

Title: averaging by months with daily data

Body:
You should use dplyr package in R. For this, we will call your data df

require(dplyr)

df.mnths <- df %>%
            group_by(Years, months) %>%
            summarise(Mean.SST = mean(SSTs))

df.years <- df %>%
            group_by(Years) %>%
            summarise(Mean.SST = mean(SSTs))

This is two new data sets that will have the mean(SST) for each month of each year in df.mnths, and another dataset that will have mean(SST) for all years in df.years.


问:
Java orm problem
There is a big table business_apply in our system. It's used to store business apply information, and contains hundreds of columns.

When business type differs, a column may mean different things.

What kind of orm framework can make our life easier? Hibernate, iBatis or something else?

答: IBatis is great for letting you do manual SQL, putting you in manual control of handling table designs which perhaps don't lend themselves to proper ORM handling.</p>

ContentLicense: CC BY-SA 2.5

Title: Java orm problem


问:
Text goes outside containing div
I have this codepen here, shouldn't the text goes to new line when it reaches the right border of div?

html:

```<code><div class="test">

    <p>dfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodj</p>
</div>
</code>```

css:

```<code>div.test{
    width:400px;
    height:800px;
    border-style: solid;
    border-color: red;
    margin:1px; padding:1px;

}
</code>```

答:
Because the text doesn't have any space, so it won't create a new line.

Try to put:

[space]/( )/( )

For example, I changed my text from:

```<code>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
</code>```

into:

```<code>xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx
</code>```

It will create its own new line.

Title: Text goes outside containing div

Body:
I have this codepen here, shouldn't the text goes to new line when it reaches the right border of div?

html:

dfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodjdfsjiodj

css:

div.test{
    width:400px;
    height:800px;
    border-style: solid;
    border-color: red;
    margin:1px; padding:1px;

}

Body:
Because the text doesn't have any space, so it won't create a new line.

Try to put:

[space]/(&nbsp;)/(&#160;)

For example, I changed my text from:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

into:

xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxx

It will create its own new line.


问:
How do I show an error message if a program is not running?
I would like to write a piece of code that will check if a program is running and if it isn't then a MsgBox will appear. I have done this before with a specific file using the code below:

```<code>If (Not System.IO.Directory.Exists("\\twa-file2\staffhomes\" + TextBox1.Text)) Then
    MsgBox("Home Area Not Found", MsgBoxStyle.Information, "Error")
End If
</code>```

Would someone be able to tell me how to do this for a program?

答: You want to look at the Process.GetProcesses Method ().</p>

Body:
I would like to write a piece of code that will check if a program is running and if it isn't then a MsgBox will appear. I have done this before with a specific file using the code below:

If (Not System.IO.Directory.Exists("\\twa-file2\staffhomes\" + TextBox1.Text)) Then
    MsgBox("Home Area Not Found", MsgBoxStyle.Information, "Error")
End If

Would someone be able to tell me how to do this for a program?


问:
Make WebView ignore scene CSS in JavaFX
When I load a site / html using javafx.scene.web.WebView that site seems to be affected by my scene custom styling. A minimal example to demonstrate the issue.

Main.java

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();

        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();

        root.getChildren().add(webView);

        webView.getEngine().load("http://google.pl");

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

test.css

```<code>.text-area,
.text-field {
  -fx-background-color: red;
}
</code>```

This results in

Ultimately I wish for a method like webview.getEngine().dontInheritStyles()of course there is none and I couldn't find any method of doing it otherwise. Tried:

```<code>webView.getStylesheets().clear();
webView.setStyle(null);
webView.getStyleClass().clear();
</code>```

none of them worked. One way that I think could make this work (haven't tried it yet tho) would be to open the webview in a sub window which doesn't use the same scene, however I want the webview to be embeded in my existing application view so that option would be my last resort and I rather avoid it.

答:
You can also use style classes in your CSS to manage which elements get styles applied to them. Define a 'myapplication' class in your css, and add that class to your root node.

test.css

```<code>/* any text fields inside a container with the myapplication style class */
.myapplication > .text-field{
    -fx-background-color: red;
}

/* any text areas inside a container with the myapplication style class */
.myapplication > .text-area{
    -fx-background-color: red;
}
</code>```

Main.java

```<code>...
root.getStyleClass().add("myapplication");
TextField txtField = new TextField("Application text field");
root.getChildren().addAll(webView, txtField);
...
</code>```

Using the '>' css selector (https://www.w3schools.com/cssref/css_selectors.asp) this way will apply the style to text fields whose parent has the style class 'myapplication'. When a WebView is created, it has the style class 'web-view' (https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#webview)

While there is no real way to prevent style values from being inherited, style classes are not added to children.

Title: Make WebView ignore scene CSS in JavaFX

Body:
When I load a site / html using javafx.scene.web.WebView that site seems to be affected by my scene custom styling. A minimal example to demonstrate the issue.

Main.java

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();

        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();

        root.getChildren().add(webView);

        webView.getEngine().load("http://google.pl");

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

test.css

.text-area,
.text-field {
  -fx-background-color: red;
}

This results in

Ultimately I wish for a method like webview.getEngine().dontInheritStyles()of course there is none and I couldn't find any method of doing it otherwise. Tried:

webView.getStylesheets().clear();
webView.setStyle(null);
webView.getStyleClass().clear();

none of them worked. One way that I think could make this work (haven't tried it yet tho) would be to open the webview in a sub window which doesn't use the same scene, however I want the webview to be embeded in my existing application view so that option would be my last resort and I rather avoid it.

Body:
You can also use style classes in your CSS to manage which elements get styles applied to them. Define a 'myapplication' class in your css, and add that class to your root node.

test.css

/* any text fields inside a container with the myapplication style class */
.myapplication > .text-field{
    -fx-background-color: red;
}

/* any text areas inside a container with the myapplication style class */
.myapplication > .text-area{
    -fx-background-color: red;
}

Main.java

...
root.getStyleClass().add("myapplication");
TextField txtField = new TextField("Application text field");
root.getChildren().addAll(webView, txtField);
...

Using the '>' css selector (https://www.w3schools.com/cssref/css_selectors.asp) this way will apply the style to text fields whose parent has the style class 'myapplication'. When a WebView is created, it has the style class 'web-view' (https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#webview)

While there is no real way to prevent style values from being inherited, style classes are not added to children.


问:
SQLite query won't execute. It is crashing on button click
Application launch successfully but on button click it crash in CustomListView behind ImageButton

This code form ListView custom adapter:

```<code>holder.submitAttendance.setOnClickListener(new OnClickListener() {
        @Override
       public void onClick(View v) {
            String Lt,teacherName,status = null,startTime,endTime;
            if(holder.radioButtonPresent.isChecked())
            {
                status=holder.radioButtonPresent.getText().toString();
            }
            else if(holder.radioButtonAbsent.isChecked())
            {
                status=holder.radioButtonAbsent.getText().toString();
            }
            startTime=holder.etxtStart_time_Picker.getText().toString();
            endTime=holder.etxtEnd_time_Picker.getText().toString();
            Lt=holder.txtlt.getText().toString();
            teacherName=holder.txtteacher.getText().toString();
        dataBaseHelper1.insertData(Lt,teacherName,status,startTime,endTime);
        }
    });
</code>```

this form sqlite database helper class

```<code>public class DataBaseHelper extends SQLiteOpenHelper
{

public static String DATABASE_NAME = "Teacher.db";
public static String TABLE_NAME = "Teacher_Table";
public static String Col_1_LT = "LT";
public static String Col_2_TName = "Teacher_Name";
public static String Col_3_Status = "Status";
public static String Col_4_StartTime = "StartTime";
public static String Col_5_EndTime = "EndTime";

public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
    String query="create table" + TABLE_NAME +"( LT TEXT PRIMARY
    KEY,Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT)";
    db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
    ContentValues contentValues = new ContentValues();
    public boolean insertData(String Lt, String TeacherName, String Status,String StartTime, String EndTime)
   {
    SQLiteDatabase db = this.getWritableDatabase();
    contentValues.put(Col_1_LT, Lt);
    contentValues.put(Col_2_TName, TeacherName);
    contentValues.put(Col_3_Status, Status);
    contentValues.put(Col_4_StartTime, StartTime);
    contentValues.put(Col_5_EndTime, EndTime);
    long result = db.insert(TABLE_NAME, null, contentValues);
    db.close();
    //to check whether Data is Inserted in Database
    if (result == -1) {
        {
            return false;
        }
    } else
        {
        return true;
        }
}}
</code>```

Stacktrace:

```<code>beginning of crash
06-06 20:31:56.713 2888-2888/com.practice.testlistviewcustomadapter E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.practice.testlistviewcustomadapter, PID: 2888
    android.database.sqlite.SQLiteException: near "tableTeacher_Table": syntax error (code 1): , while compiling: create tableTeacher_Table( LT TEXT PRIMARY KEY, Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
      at com.practice.testlistviewcustomadapter.DataBaseHelper.onCreate(DataBaseHelper.java:40)
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
      at com.practice.testlistviewcustomadapter.DataBaseHelper.insertData(DataBaseHelper.java:52)
      at com.practice.testlistviewcustomadapter.CustomAdapter$1.onClick(CustomAdapter.java:122)
      at android.view.View.performClick(View.java:5637)
      at android.view.View$PerformClick.run(View.java:22429)
      at android.os.Handler.handleCallback(Handler.java:751)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6119)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
      06-06 20:31:56.716 1593-2079/system_process W/ActivityManager:   Force finishing activity com.practice.testlistviewcustomadapter/.MainActivity
06-06 20:31:56.754 1299-1355/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
</code>```

答:
You are missing space and comma in your Create Table query:

Change it to:

```<code>String query = "create table " + TABLE_NAME +"(LT TEXT PRIMARY
KEY,Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT);";
db.execSQL(query);
</code>```

Body:
Application launch successfully but on button click it crash in CustomListView behind ImageButton

This code form ListView custom adapter:

holder.submitAttendance.setOnClickListener(new OnClickListener() {
        @Override
       public void onClick(View v) {
            String Lt,teacherName,status = null,startTime,endTime;
            if(holder.radioButtonPresent.isChecked())
            {
                status=holder.radioButtonPresent.getText().toString();
            }
            else if(holder.radioButtonAbsent.isChecked())
            {
                status=holder.radioButtonAbsent.getText().toString();
            }
            startTime=holder.etxtStart_time_Picker.getText().toString();
            endTime=holder.etxtEnd_time_Picker.getText().toString();
            Lt=holder.txtlt.getText().toString();
            teacherName=holder.txtteacher.getText().toString();
        dataBaseHelper1.insertData(Lt,teacherName,status,startTime,endTime);
        }
    });

this form sqlite database helper class

public class DataBaseHelper extends SQLiteOpenHelper
{

public static String DATABASE_NAME = "Teacher.db";
public static String TABLE_NAME = "Teacher_Table";
public static String Col_1_LT = "LT";
public static String Col_2_TName = "Teacher_Name";
public static String Col_3_Status = "Status";
public static String Col_4_StartTime = "StartTime";
public static String Col_5_EndTime = "EndTime";

public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
    String query="create table" + TABLE_NAME +"( LT TEXT PRIMARY
    KEY,Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT)";
    db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
    ContentValues contentValues = new ContentValues();
    public boolean insertData(String Lt, String TeacherName, String Status,String StartTime, String EndTime)
   {
    SQLiteDatabase db = this.getWritableDatabase();
    contentValues.put(Col_1_LT, Lt);
    contentValues.put(Col_2_TName, TeacherName);
    contentValues.put(Col_3_Status, Status);
    contentValues.put(Col_4_StartTime, StartTime);
    contentValues.put(Col_5_EndTime, EndTime);
    long result = db.insert(TABLE_NAME, null, contentValues);
    db.close();
    //to check whether Data is Inserted in Database
    if (result == -1) {
        {
            return false;
        }
    } else
        {
        return true;
        }
}}

Stacktrace:

beginning of crash
06-06 20:31:56.713 2888-2888/com.practice.testlistviewcustomadapter E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.practice.testlistviewcustomadapter, PID: 2888
    android.database.sqlite.SQLiteException: near "tableTeacher_Table": syntax error (code 1): , while compiling: create tableTeacher_Table( LT TEXT PRIMARY KEY, Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1677)
      at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
      at com.practice.testlistviewcustomadapter.DataBaseHelper.onCreate(DataBaseHelper.java:40)
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
      at com.practice.testlistviewcustomadapter.DataBaseHelper.insertData(DataBaseHelper.java:52)
      at com.practice.testlistviewcustomadapter.CustomAdapter$1.onClick(CustomAdapter.java:122)
      at android.view.View.performClick(View.java:5637)
      at android.view.View$PerformClick.run(View.java:22429)
      at android.os.Handler.handleCallback(Handler.java:751)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6119)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
      06-06 20:31:56.716 1593-2079/system_process W/ActivityManager:   Force finishing activity com.practice.testlistviewcustomadapter/.MainActivity
06-06 20:31:56.754 1299-1355/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property

Body:
You are missing space and comma in your Create Table query:

Change it to:

String query = "create table " + TABLE_NAME +"(LT TEXT PRIMARY
KEY,Teacher_Name TEXT, Status TEXT, StartTime TEXT, EndTime TEXT);";
db.execSQL(query);


问:
UIImage resize (Scale proportion)

Possible Duplicate:

  Resize UIImage with aspect ratio?

The following piece of code is resizing the image perfectly, but the problem is that it messes up the aspect ratio (resulting in a skewed image). Any pointers?

```<code>// Change image resolution (auto-resize to fit)
+ (UIImage *)scaleImage:(UIImage*)image toResolution:(int)resolution {
    CGImageRef imgRef = [image CGImage];
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGRect bounds = CGRectMake(0, 0, width, height);

    //if already at the minimum resolution, return the orginal image, otherwise scale
    if (width <= resolution && height <= resolution) {
        return image;

    } else {
        CGFloat ratio = width/height;

        if (ratio > 1) {
            bounds.size.width = resolution;
            bounds.size.height = bounds.size.width / ratio;
        } else {
            bounds.size.height = resolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    UIGraphicsBeginImageContext(bounds.size);
    [image drawInRect:CGRectMake(0.0, 0.0, bounds.size.width, bounds.size.height)];
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}
</code>```

答:
That's ok not a big problem . thing is u got to find the proportional width and height

like if size is  2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be  722.0 x 480.0

```<code>here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y
=>
x=(w/h)*y;

submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)
</code>```

U can submit in this web page . ARC

Confused ? alright ,  here is category for UIImage which will do the thing for you.

```<code>@interface UIImage (UIImageFunctions)
    - (UIImage *) scaleToSize: (CGSize)size;
    - (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)

- (UIImage *) scaleToSize: (CGSize)size
{
    // Scalling selected image to targeted size
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    if(self.imageOrientation == UIImageOrientationRight)
    {
        CGContextRotateCTM(context, -M_PI_2);
        CGContextTranslateCTM(context, -size.height, 0.0f);
        CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
    }
    else
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);

    CGImageRef scaledImage=CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    UIImage *image = [UIImage imageWithCGImage: scaledImage];

    CGImageRelease(scaledImage);

    return image;
}

- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
    if(self.size.width>self.size.height)
    {
        NSLog(@"LandScape");
        size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
    }
    else
    {
        NSLog(@"Potrait");
        size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
    }

    return [self scaleToSize:size1];
}

@end
</code>```

-- the following is appropriate call to do this if img is the UIImage instance.

img=[img scaleProportionalToSize:CGSizeMake(320, 480)];

Title: UIImage resize (Scale proportion)

Body:
Possible Duplicate:

  Resize UIImage with aspect ratio?

The following piece of code is resizing the image perfectly, but the problem is that it messes up the aspect ratio (resulting in a skewed image). Any pointers?

// Change image resolution (auto-resize to fit)
+ (UIImage *)scaleImage:(UIImage*)image toResolution:(int)resolution {
    CGImageRef imgRef = [image CGImage];
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGRect bounds = CGRectMake(0, 0, width, height);

    //if already at the minimum resolution, return the orginal image, otherwise scale
    if (width <= resolution && height <= resolution) {
        return image;

    } else {
        CGFloat ratio = width/height;

        if (ratio > 1) {
            bounds.size.width = resolution;
            bounds.size.height = bounds.size.width / ratio;
        } else {
            bounds.size.height = resolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    UIGraphicsBeginImageContext(bounds.size);
    [image drawInRect:CGRectMake(0.0, 0.0, bounds.size.width, bounds.size.height)];
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

Body:
That's ok not a big problem . thing is u got to find the proportional width and height

like if size is  2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be  722.0 x 480.0

here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y
=>
x=(w/h)*y;

submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)

U can submit in this web page . ARC

Confused ? alright ,  here is category for UIImage which will do the thing for you.

@interface UIImage (UIImageFunctions)
    - (UIImage *) scaleToSize: (CGSize)size;
    - (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)

- (UIImage *) scaleToSize: (CGSize)size
{
    // Scalling selected image to targeted size
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    if(self.imageOrientation == UIImageOrientationRight)
    {
        CGContextRotateCTM(context, -M_PI_2);
        CGContextTranslateCTM(context, -size.height, 0.0f);
        CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
    }
    else
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);

    CGImageRef scaledImage=CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    UIImage *image = [UIImage imageWithCGImage: scaledImage];

    CGImageRelease(scaledImage);

    return image;
}

- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
    if(self.size.width>self.size.height)
    {
        NSLog(@"LandScape");
        size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
    }
    else
    {
        NSLog(@"Potrait");
        size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
    }

    return [self scaleToSize:size1];
}

@end

-- the following is appropriate call to do this if img is the UIImage instance.

img=[img scaleProportionalToSize:CGSizeMake(320, 480)];


问:
With Android's new architecture components, does savedInstanceState matter?
Reading about Android's new Architecture Components, the recommendation is to use various ViewModel instances to feed data to Activities and Fragments.

There's also this notion of driving data from a single persistent model:

The second important principle is that you should drive your UI from a
  model, preferably a persistent model. Persistence is ideal for two
  reasons: your users won't lose data if OS destroys your app to free up
  resources and your app will continue to work even when a network
  connection is flaky or not connected. Models are components that are
  responsible for handling the data for the app. They are independent
  from the Views and app components in your app, hence they are isolated
  from the lifecycle issues of those components.

And a similar notion of a single source of truth:

In this model, the database serves as the single source of truth, and
  other parts of the app access it via the repository. Regardless of
  whether you use a disk cache, we recommend that your repository
  designate a data source as the single source of truth to the rest of
  your app.

In the code examples I've seen, they do pass the savedInstanceState bundle up to the super class's implementation, for example:

```<code>@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String userId = getArguments().getString(UID_KEY);
    viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
    viewModel.init(userId);
}
</code>```

but, it seems like there's no reason any more for our Activities to explicitly store/retrieve important values to/from savedInstanceState.

Is savedInstanceState irrelevant with the new architecture?

答:
it seems like there's no reason any more for our Activities to explicitly store/retrieve important values to/from savedInstanceState.

That would depend entirely upon what is in the activities.

Is savedInstanceState irrelevant with the new architecture?

No.

The idea behind the saved instance state has been, and continues to be, helping the activity pretend as though it had been around all along, even though the activity had been destroyed and recreated along the way, either because of:

a configuration change (e.g., screen rotation), or

process termination (e.g., the user leaves the app, Android terminates the process, and the user returns to the app within a half-hour)

So, for example, suppose we have an activity with a form. When the user fills in the form and clicks a "save" action bar item, we want to persist the contents of the form. And, in some cases, we are opening the form on some existing data that is already persisted, and so we want to load that. Those are problems that the Android Architecture Components, particularly Room, are designed to help with.

But, suppose the user fills in a field on the form, then rotates the screen. In this case, most likely we do not want to save the change in the database yet, because the user has not clicked "save" to express interest in persisting this change. So, we rely on onSaveInstanceState() to handle that for us. In this case, the built-in onSaveInstanceState() handles this, as the contents of an EditText is obvious user-mutable state.

But, suppose in addition, after editing the field, the user taps on an ImageButton to choose a contact. That uses ACTION_PICK to bring up the contacts picker, and the user chooses a contact there. Control returns to the original activity, which perhaps has a TextView to show the contact's name, or perhaps updates the ImageButton with the contacts avatar. Now the user rotates the screen. Once again, we may not want to persist this yet. However, this time, the activity is not going to automatically hold onto the Uri of our contact, as it does not know how to. So, we put that in the saved instance state Bundle ourselves, overriding onSaveInstanceState().

Data stores (e.g., databases) represent the single "source of truth", but it is application logic that decides when data becomes "truth", and instance state is a common approach for handling data that may become truth in the future but is not truth yet.

Body:
Reading about Android's new Architecture Components, the recommendation is to use various ViewModel instances to feed data to Activities and Fragments.

There's also this notion of driving data from a single persistent model:

The second important principle is that you should drive your UI from a
  model, preferably a persistent model. Persistence is ideal for two
  reasons: your users won't lose data if OS destroys your app to free up
  resources and your app will continue to work even when a network
  connection is flaky or not connected. Models are components that are
  responsible for handling the data for the app. They are independent
  from the Views and app components in your app, hence they are isolated
  from the lifecycle issues of those components.

And a similar notion of a single source of truth:

In this model, the database serves as the single source of truth, and
  other parts of the app access it via the repository. Regardless of
  whether you use a disk cache, we recommend that your repository
  designate a data source as the single source of truth to the rest of
  your app.

In the code examples I've seen, they do pass the savedInstanceState bundle up to the super class's implementation, for example:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String userId = getArguments().getString(UID_KEY);
    viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
    viewModel.init(userId);
}

but, it seems like there's no reason any more for our Activities to explicitly store/retrieve important values to/from savedInstanceState.

Is savedInstanceState irrelevant with the new architecture?


问:
iOS implement the file browser push same view controller show error
I need create the file browser function using the UITableViewController.

I load the data in the tableview, if user selected row at index path is a folder,

I want to push the same data structure and uitableview and using reload tableview to change the data show in the save view controller.

So I try to add

```<code> [self.navigationController pushViewController:self animated:YES];
</code>```

in the didSelectRowAtIndexPath delegate method.

All method code :

```<code> -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

     [self.navigationController pushViewController:self animated:YES];
 }
</code>```

But I got the error log is below

```<code> Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Pushing the same view controller instance more than once is not supported
</code>```

I using pushViewController because the iOS can show the back to preview file title and have  navigation animate.

Have anyone can teach me how to resolve the problem or have some better function implement method?

thank you very much.

答:
You can use this method:</p>

```<code>[self.navigationController pushViewController: [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"YourViewController"] animated: YES];
</code>```

Body:
I need create the file browser function using the UITableViewController.

I load the data in the tableview, if user selected row at index path is a folder,

I want to push the same data structure and uitableview and using reload tableview to change the data show in the save view controller.

So I try to add

 [self.navigationController pushViewController:self animated:YES];

in the didSelectRowAtIndexPath delegate method.

All method code :

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

     [self.navigationController pushViewController:self animated:YES];
 }

But I got the error log is below

 Terminating app due to uncaught exception 'NSInvalidArgumentException',
 reason: 'Pushing the same view controller instance more than once is not supported

I using pushViewController because the iOS can show the back to preview file title and have  navigation animate.

Have anyone can teach me how to resolve the problem or have some better function implement method?

thank you very much.

Body:
You can use this method:

[self.navigationController pushViewController: [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"YourViewController"] animated: YES];


问:
Android Studio 2.1 debugger does not show local variables
I am trying to debug over network in Android Studio. I connected via port 5555 and generally it is possible step through break points. But it often takes minutes just to execute one line of code and the other thing is that I don't see any variables which are no members. All I see is the this object, but no variables from within methods. How can I enable it?

As you can see I am within the method and at least the activity object is initialized, but it is not visible in the variables monitor.

UPDATE:

The problem remains when using USB debugging. No local variables are visible, not even when trying to evaluate expressions while debugging:

Android Studio 2.1, Gradle 2.1.0, Java 1.8

答: While this is not a permanent solution to this problem, my most consistent fix (after trying the other answers here to no avail) has simply been restarting my computer.</p>


问:
Saving a Twitter Sample Stream to RavenDB results in the exception The maximum number of requests (30) allowed for this session has been reached
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

```<code>using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}
</code>```

DocumentStoreHolder.cs

```<code>using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}
</code>```

TwitterModels.cs

```<code>namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}
</code>```

答:
You're creating a single document session, and using that for all tweets that are received. So, if you receive 5000 tweets over the span of an hour, you'll hit this issue.

Two ways to fix this:

If TweetReceived is sparse (e.g. it fires a few times a minute or less), then just create a new Raven session each time the tweet is received.

If TweetReceived is fired a bunch of times in quick succession (e.g. 5000 tweets received in a few seconds), then use Raven BulkInsert.

Option #1, session for each tweet received:

```<code>static void Main(string[] args)
{
    Auth.SetUserCredentials() // redacted for SO

    var stream = Stream.CreateSampleStream();
    stream.TweetReceived += (sender, theTweet) =>
    {
        var tm = new TwitterModels
        {
            Id = theTweet.Tweet.Id,
            TheTextFromTwitter = theTweet.Tweet.FullText
        };

        using (var session = DocumentStoreHolder.Store.OpenSession())
        {
           session.Store(tm);
           session.SaveChanges();
        }
    };
    stream.StartStream();
}
</code>```

Option #2, using Bulk Insert:

```<code>using (BulkInsertOperation bulkInsert = store.BulkInsert())
{
   stream.TweetReceived += (sender, theTweet) =>
   {
       var tm = new TwitterModels
       {
           Id = theTweet.Tweet.Id,
           TheTextFromTwitter = theTweet.Tweet.FullText
       };

       bulkInsert.Store(tm);
   }
};
</code>```

Either will work here. Use #1 if Tweets arrive sparsely over the lifetime of the app. Use #2 if tweets arrive all at once in bulk.

Body:
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}

DocumentStoreHolder.cs

using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}

TwitterModels.cs

namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}

Body:
You're creating a single document session, and using that for all tweets that are received. So, if you receive 5000 tweets over the span of an hour, you'll hit this issue.

Two ways to fix this:

If TweetReceived is sparse (e.g. it fires a few times a minute or less), then just create a new Raven session each time the tweet is received.

If TweetReceived is fired a bunch of times in quick succession (e.g. 5000 tweets received in a few seconds), then use Raven BulkInsert.

Option #1, session for each tweet received:

static void Main(string[] args)
{
    Auth.SetUserCredentials() // redacted for SO

    var stream = Stream.CreateSampleStream();
    stream.TweetReceived += (sender, theTweet) =>
    {
        var tm = new TwitterModels
        {
            Id = theTweet.Tweet.Id,
            TheTextFromTwitter = theTweet.Tweet.FullText
        };

        using (var session = DocumentStoreHolder.Store.OpenSession())
        {
           session.Store(tm);
           session.SaveChanges();
        }
    };
    stream.StartStream();
}

Option #2, using Bulk Insert:

using (BulkInsertOperation bulkInsert = store.BulkInsert())
{
   stream.TweetReceived += (sender, theTweet) =>
   {
       var tm = new TwitterModels
       {
           Id = theTweet.Tweet.Id,
           TheTextFromTwitter = theTweet.Tweet.FullText
       };

       bulkInsert.Store(tm);
   }
};

Either will work here. Use #1 if Tweets arrive sparsely over the lifetime of the app. Use #2 if tweets arrive all at once in bulk.