问:
Java and PostgreSQL stored procedure - return registered as out parameter, causing issues with in parameters
I'm trying to call a PostgreSQL stored procedure from a Java app; the procedure has a DATE type parameter so I'm using a java.sql.Date type with CallableStatement.setDate().  However, executing the statement always results in an exception and the SQL logs show this:

```<code>LOG:  execute <unnamed>: select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result
DETAIL:  parameters: $1 = '', $2 = 'foo@bar.com', $3 = 'Joe', $4 = 'Blow', $5 = 'foobar', $6 = 'M', $7 = '1979-03-22 -04:00:00'
ERROR:  column "dob" is of type date but expression is of type text at character 122
HINT:  You will need to rewrite or cast the expression.
QUERY:  INSERT INTO athlete.athlete (email, first_name, last_name, password, gender, dob) VALUES ( $1 ,  $2 ,  $3 ,  $4 ,  $5 ,  $6 )
CONTEXT:  PL/pgSQL function "create_athlete" line 2 at SQL statement
STATEMENT:  select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result
</code>```

The stored procedure actually has 6 parameters (and should receive values $2 through $7 above) - the 7th comes from registering the return value as an out parameter.  This has me confused - is it correct that it appears as 7 parameters when I register an out parameter for the return value?

From all the docs I've read I'm under the impression that the return value has to be registered as the first parameter:

```<code>registerQuery = "{? = call athlete.create_athlete(?,?,?,?,?,?)}";
...
CallableStatement cs = conn.prepareCall(registerQuery);
cs.registerOutParameter(1, Types.BOOLEAN);
cs.setString(2, email);
...
</code>```

The error above suggests to me that there's a mismatch between stored procedure parameters and the parameters supplied to the insert statement.  I've been following documentation for all of this but am clearly doing something wrong.  How do I supply the proper parameters to the stored procedure and retrieve the return value after the call?

答: Postgresql server supports named parameters but the jdbc driver does not support it(well not yet to my knowledge), so until such time only positional parameters is supported.</p>

Body:
I'm trying to call a PostgreSQL stored procedure from a Java app; the procedure has a DATE type parameter so I'm using a java.sql.Date type with CallableStatement.setDate().  However, executing the statement always results in an exception and the SQL logs show this:

LOG:  execute <unnamed>: select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result
DETAIL:  parameters: $1 = '', $2 = 'foo@bar.com', $3 = 'Joe', $4 = 'Blow', $5 = 'foobar', $6 = 'M', $7 = '1979-03-22 -04:00:00'
ERROR:  column "dob" is of type date but expression is of type text at character 122
HINT:  You will need to rewrite or cast the expression.
QUERY:  INSERT INTO athlete.athlete (email, first_name, last_name, password, gender, dob) VALUES ( $1 ,  $2 ,  $3 ,  $4 ,  $5 ,  $6 )
CONTEXT:  PL/pgSQL function "create_athlete" line 2 at SQL statement
STATEMENT:  select * from athlete.create_athlete($1,$2,$3,$4,$5,$6,$7) as result

The stored procedure actually has 6 parameters (and should receive values $2 through $7 above) - the 7th comes from registering the return value as an out parameter.  This has me confused - is it correct that it appears as 7 parameters when I register an out parameter for the return value?

From all the docs I've read I'm under the impression that the return value has to be registered as the first parameter:

registerQuery = "{? = call athlete.create_athlete(?,?,?,?,?,?)}";
...
CallableStatement cs = conn.prepareCall(registerQuery);
cs.registerOutParameter(1, Types.BOOLEAN);
cs.setString(2, email);
...

The error above suggests to me that there's a mismatch between stored procedure parameters and the parameters supplied to the insert statement.  I've been following documentation for all of this but am clearly doing something wrong.  How do I supply the proper parameters to the stored procedure and retrieve the return value after the call?


来源: stackexchange

问:
how to set permanent background of all activities?
I am using following code:

```<code>Public void xyz(View v) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode){
        case 0:
            data.getDataString();
            if(resultCode == RESULT_OK){
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(_activity.getContentResolver(), data.getDataString());
                    RelativeLayout bg = (RelativeLayout) findViewById(R.id.might);
                    Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                    bg.setBackgroundDrawable(drawable);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch blocke.printStackTrace();
                } catch(IOException e) {
                    // TODO Auto-generated catch blocke.printStackTrace();
                }
            }
            break;
    }
}
</code>```

Questions:

It sets Background for only one Activity.

After onDestroy() method, It sets default Background on restart.

答:
Rupinderjeet asnwer was correct. it can make you work by default background.

But here is an easy and best way to do this.

make an style in your style.xml placed in values

```<code><style name="DefaultBackgroundTheme" parent="Base.Theme.AppCompat.Light">
    <item name="android:windowBackground">@drawable/splash_bitmap</item>
</style>
</code>```

Change Base.Theme.AppCompat.Light by your app theme

you can put color, bitmaps or drawables as well here.

and inside your manifest class change your theme by

```<code><activity
    android:name="yourActivityName"
    android:theme="@style/DefaultBackgroundTheme" />
</code>```

Hope this helps you.

ContentLicense: CC BY-SA 3.0

Body:
I am using following code:

Public void xyz(View v) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode){
        case 0:
            data.getDataString();
            if(resultCode == RESULT_OK){
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(_activity.getContentResolver(), data.getDataString());
                    RelativeLayout bg = (RelativeLayout) findViewById(R.id.might);
                    Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                    bg.setBackgroundDrawable(drawable);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch blocke.printStackTrace();
                } catch(IOException e) {
                    // TODO Auto-generated catch blocke.printStackTrace();
                }
            }
            break;
    }
}

Questions:

It sets Background for only one Activity.

After onDestroy() method, It sets default Background on restart.

Body:
Rupinderjeet asnwer was correct. it can make you work by default background.

But here is an easy and best way to do this.

make an style in your style.xml placed in values

<style name="DefaultBackgroundTheme" parent="Base.Theme.AppCompat.Light">
    <item name="android:windowBackground">@drawable/splash_bitmap</item>
</style>

Change Base.Theme.AppCompat.Light by your app theme

you can put color, bitmaps or drawables as well here.

and inside your manifest class change your theme by

<activity
    android:name="yourActivityName"
    android:theme="@style/DefaultBackgroundTheme" />

Hope this helps you.


问:
R plumber on Linux Server
I've made a .R file with a plumber code. The file works fine on my local pc, it works also fine on my linux server.
My only problem now is, that it's only local.

I need to be able to get the API over the server adress.
The server also runs a cronR process which makes all the math and a shiny-app to display some graphs. All the math is stored into an cvs file and plumber should now get the last index and display this so I can use it from everywhere.

Are there any solutions?

Code:

```<code>library(plumber)

path = "/srv/shiny-server/Crypto10/data/"

r = plumb(paste(path,"API.R", sep = ""))

r$run(port=8000)
</code>```

Title: R plumber on Linux Server

Body:
I've made a .R file with a plumber code. The file works fine on my local pc, it works also fine on my linux server.
My only problem now is, that it's only local.

I need to be able to get the API over the server adress.
The server also runs a cronR process which makes all the math and a shiny-app to display some graphs. All the math is stored into an cvs file and plumber should now get the last index and display this so I can use it from everywhere.

Are there any solutions?

Code:

library(plumber)

path = "/srv/shiny-server/Crypto10/data/"

r = plumb(paste(path,"API.R", sep = ""))

r$run(port=8000)

Body:
try

r$run(host="0.0.0.0",port=8000)


问:
Shortening repeating functions
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

```

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

答:
There is no need to define the same variable again and again and multiple functions to perform the same task.

Use:

```<code><input type="button" onclick="some_function('test1')" value="1">
<input type="button" onclick="some_function('test2')" value="2">
<input type="button" onclick="some_function('test3')" value="3">
</code>```

to use the same function.

```<code>function some_function(a) {
    console.log('test: ' + a +' '+ slider.value);
}
</code>```

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function_name('test1')" value="1">
<input type="button" onclick="function_name('test2')" value="2">
<input type="button" onclick="function_name('test3')" value="3">

```

Title: Shortening repeating functions

Body:
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

Body:
There is no need to define the same variable again and again and multiple functions to perform the same task.

Use:

<input type="button" onclick="some_function('test1')" value="1">
<input type="button" onclick="some_function('test2')" value="2">
<input type="button" onclick="some_function('test3')" value="3">

to use the same function.

function some_function(a) {
    console.log('test: ' + a +' '+ slider.value);
}

<!DOCTYPE html>
<html>

<body>
<div id="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>
<input type="button" onclick="function_name('test1')" value="1">
<input type="button" onclick="function_name('test2')" value="2">
<input type="button" onclick="function_name('test3')" value="3">

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}

function function_name(a) {
    console.log('test: ' + a +' '+ slider.value);
}

</script>

</body>
</html>


问:
django count per column
I have a ORM like this

```<code>from django.db import models,

class MyObject(models.Model):

   class Meta:
       db_table = 'myobject'

   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=48)
   status = models.CharField(max_length=48)
</code>```

Imagine I have the following entries

```<code>1 | foo | completed
2 | foo | completed
3 | bar | completed
4 | foo | failed
</code>```

What is the django ORM query that I have to make in order to get a queryset somewhat like the following

```<code>[{'name': 'foo', 'status_count': 'completed: 2, failed: 1'},
 {'name': 'bar', 'status_count': 'completed: 1'}]
</code>```

I started with the following but I don't know how to "merge" the two columns:

```<code>from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id'))
</code>```

The goal of all this to get a table where I can show something like the following:

```<code>Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0
</code>```

答:
You need to include an "order_by" on to the end of your query to group the like items together.

Something like this should work:

```<code>from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id')).order_by()
</code>```

See https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by for details.

EDIT: Sorry, I realize this doesn't answer the question about merging the columns... I don't think you can actually do it in a single query, although you can then loop through the results pretty easily and make your output table.

Title: django count per column

Body:
I have a ORM like this

from django.db import models,

class MyObject(models.Model):

   class Meta:
       db_table = 'myobject'

   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=48)
   status = models.CharField(max_length=48)

Imagine I have the following entries

1 | foo | completed
2 | foo | completed
3 | bar | completed
4 | foo | failed

What is the django ORM query that I have to make in order to get a queryset somewhat like the following

[{'name': 'foo', 'status_count': 'completed: 2, failed: 1'},
 {'name': 'bar', 'status_count': 'completed: 1'}]

I started with the following but I don't know how to "merge" the two columns:

from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id'))

The goal of all this to get a table where I can show something like the following:

Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0

Body:
You need to include an "order_by" on to the end of your query to group the like items together.

Something like this should work:

from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id')).order_by()

See https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by for details.

EDIT: Sorry, I realize this doesn't answer the question about merging the columns... I don't think you can actually do it in a single query, although you can then loop through the results pretty easily and make your output table.


问:
Prevent voice over (Accessibility) from announcing UITableViewCell as selected
When a UITableViewCell is selected, voice over announces "selected", I don't want voice over to say "selected". How can i achieve this ?

Things I have tried with no success:

Changed the cell accessibilityHint and accessibilityLabel

Changed the cell selectionStyle = UITableViewCellSelectionStyleNone

changed the cell accessibilityTraits = UIAccessibilityTraitButton

Question:

I don't want voice over to say "selected" when a cell is selected. How can i achieve this ?

答:
You can create custom cell class and override accessibilityTraits like this:

```<code>- (UIAccessibilityTraits)accessibilityTraits {
     return UIAccessibilityTraitButton;
}
</code>```

Body:
You can create custom cell class and override accessibilityTraits like this:

- (UIAccessibilityTraits)accessibilityTraits {
     return UIAccessibilityTraitButton;
}


问:
Can't set size of image. Disappears from DIV border
I have a question about image positioning and sizing in DIV.
I have an image that I use in a specific DIV and I need it to cover the whole topside of the DIV. When I zoom-in the scale of the browser, instead of shrinking in the DIV, the image disappears and overflows from the right side of the DIV.
Also when I zoom-out the scale, the image is being cut-off from the bottom. I know the problem is with the Height, but I do not know how to fix it.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main {
  background-image: url("upper_title.png");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main_body">
  <div class="upper_main">
  </div>
</div></code>```

EXAMPLE:

答:
Why not simply use an image that take the full width of the top bar :

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main img {
  width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main_body">
  <div class="upper_main">
    <img src="https://lorempixel.com/300/50/" >
  </div>
</div></code>```

Body:
I have a question about image positioning and sizing in DIV.
I have an image that I use in a specific DIV and I need it to cover the whole topside of the DIV. When I zoom-in the scale of the browser, instead of shrinking in the DIV, the image disappears and overflows from the right side of the DIV.
Also when I zoom-out the scale, the image is being cut-off from the bottom. I know the problem is with the Height, but I do not know how to fix it.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main {
  background-image: url("upper_title.png");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}

EXAMPLE:

Body:
Why not simply use an image that take the full width of the top bar :

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main img {
  width:100%;
}

<div class="main_body">
  <div class="upper_main">
    <img src="https://lorempixel.com/300/50/" >
  </div>
</div>


问:
Use Lodash to produce new object from existing object based on array of keys
I am relatively new to Lodash and I'm trying to do something that I'm sure is really easy.

I'm wondering which existing Lodash method to use to take an array of keys and an object, then return a new object containing only the properties (from the original object) that match the keys that were passed in.

```<code>let _ = require("lodash");

// DOES THE FUNCTION BELOW ALREADY EXIST?
let only = function (wanted, srcList) {
  return _.reduce(wanted, function(out,key){
    if(_.has(srcList, key)){
      out[key] = srcList[key]
    }
    return out;
  },{})
}

let src = {
  w: "This is doble vuu",
  x: "This is X",
  y: "This is why?",
  z: "This is zeee!"
};

var want = ['x','z'];

let newObject  = only(want,src);

console.log(newObject)
</code>```

The code I have works, but I don't want to re-invent the proverbial wheel, no matter how simple it is.

答: _.pick works perfectly as suggested by Gruff Bunny in the comments. I don't know why it didn't seem more obvious when I was going through dozens of methods available in Lodash</p>

Body:
I am relatively new to Lodash and I'm trying to do something that I'm sure is really easy.

I'm wondering which existing Lodash method to use to take an array of keys and an object, then return a new object containing only the properties (from the original object) that match the keys that were passed in.

let _ = require("lodash");

// DOES THE FUNCTION BELOW ALREADY EXIST?
let only = function (wanted, srcList) {
  return _.reduce(wanted, function(out,key){
    if(_.has(srcList, key)){
      out[key] = srcList[key]
    }
    return out;
  },{})
}

let src = {
  w: "This is doble vuu",
  x: "This is X",
  y: "This is why?",
  z: "This is zeee!"
};

var want = ['x','z'];

let newObject  = only(want,src);

console.log(newObject)

The code I have works, but I don't want to re-invent the proverbial wheel, no matter how simple it is.


问:
How to capitalize the first character of every sentence
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

```<code>    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }
</code>```

答:
I would suggest to use a regex to identify all the dots in your sentence. Get the match, make it upper case and replace it back in the original sentence, in the match index. I dont actually have any IDE in which try the code on .NET right now but i can write it in pseudocode for better understanding.</p>

```<code>    String setence = "your.setence.goes.here";
    Regex rx = new Regex("/\..*?[A-Z]/");
    foreach (Match match in rx.Matches(sentence))
    {
        setence.remove(match.Index, 2).insert(match.Index, String.ToUpper(match.Value));
    }
</code>```

Body:
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }

Body:
I would suggest to use a regex to identify all the dots in your sentence. Get the match, make it upper case and replace it back in the original sentence, in the match index. I dont actually have any IDE in which try the code on .NET right now but i can write it in pseudocode for better understanding.

    String setence = "your.setence.goes.here";
    Regex rx = new Regex("/\..*?[A-Z]/");
    foreach (Match match in rx.Matches(sentence))
    {
        setence.remove(match.Index, 2).insert(match.Index, String.ToUpper(match.Value));
    }


问:
Does SQL Server transform text in any way when performing a BULK INSERT?
I'm trying to use a BULK INSERT statement to populate a large (17-million-row) table in SQL Server from a text file.  One column, of type nchar(17) has a UNIQUE constraint on it.  I've checked (using some Python code) that the file contains no duplicates, but when I execute the query I get this error message from SQL Server:

Cannot insert duplicate key row in object 'dbo.tbl_Name' with unique index 'IX_tbl_Name'.

Could Server be transforming the text in some way as it executes BULK INSERT?  Do SQL Server databases forbid any punctuation marks in nchar columns, or require that any be escaped?  Is there any way I can find out which row is causing the trouble?  Should I switch to some other method for inserting the data?

答: Another thought too would be that empty or null values count as duplicates, so your Python code may not have found any text duplicates, but what about the empties?</p>

OwnerDisplayName: Tommy Herbert

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Nick DeVore


问:
Limitations in running Ruby/Rails on windows
In the installation documentation to RoR it mentions that there are many limitations to running Ruby on Rails on Windows, and in some cases, whole libraries do not work.

How bad are these limitations, should I always default to Linux to code / run RoR, and is Iron Ruby expected to fix these limitations or are they core to the OS itself?

EDIT Thanks for the answer around installation and running on Linux, but I am really trying to understand the limitations in functionality as referenced in the installation documentation, and non-working libraries - I am trying to find a link to the comment, but it was referenced in an installation read me when I installed the msi package I think

EDIT
Thanks for the references to IronRuby lately, it is certainly a project to watch, and as it, obviously, is a .NET language, it will be invaluable if it lives up to the promises. Eventually, however, in my case, I just bit the bullet and installed an Ubuntu server.

<bias> I should've done it years ago </bias>

答: There is a packaged installer available at http://railsinstaller.org/ which is worth checking out.</p>

OwnerDisplayName: lagerdalek

LastEditorDisplayName: Charles Roper


问:
How does str.replace() method work?
I have this input:

```<code>'0472/91.39.17'
</code>```

I want to replace my input with '1234567890' one by one like this:

```<code>'1234/56.78.90'
</code>```

But my outcome is

```<code>0472/91.09.17
</code>```

Here's my code

```<code>phone = '0472/91.39.17'
repl = 1234567890

for i in phone:
    if i.isdigit():
        for j in str(repl):
            x = phone.replace(i, j)
        print(x)
</code>```

What is the proper way to do this?

答:
You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. Re-combine that together with ''.join to get a string as a result, and Bob's your uncle.

```<code>repliter = iter(str(repl))

result = ''.join(next(repliter) if c.isdigit() else c for c in phone)
# the ternary expression here evaluates to:
# if c.isdigit():
#     next(repliter)
# else:
#     c
</code>```

Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead.

```<code>import itertools

repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...
</code>```

Title: How does str.replace() method work?

Body:
I have this input:

'0472/91.39.17'

I want to replace my input with '1234567890' one by one like this:

'1234/56.78.90'

But my outcome is

0472/91.09.17

Here's my code

phone = '0472/91.39.17'
repl = 1234567890

for i in phone:
    if i.isdigit():
        for j in str(repl):
            x = phone.replace(i, j)
        print(x)

What is the proper way to do this?

Body:
You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. Re-combine that together with ''.join to get a string as a result, and Bob's your uncle.

repliter = iter(str(repl))

result = ''.join(next(repliter) if c.isdigit() else c for c in phone)
# the ternary expression here evaluates to:
# if c.isdigit():
#     next(repliter)
# else:
#     c

Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead.

import itertools

repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...


问:
C# How to add string variables with values to the any System.Collections class and retrieve them
So I have a slightly interesting problem right here. What I'm trying to achieve is to add between 1000 to 2000 string variables to the list and later compare them with another strings. So far I can achieve this by using below code:

```<code>var list = new List<string>();
var item_1 = "USA";
var item_2 = "Canada";
var item_3 = "Cuba";
...................
var item_N = "Country_N";
list.Add(item_1);
list.Add(item_2);
list.Add(item_3);
.................
list.Add(item_N);
</code>```

And comparing them with another strings looks like below (using FluentAssertions class):

```<code>list[0].Should().Match(stringToCompare_1);
list[1].Should().Match(stringToCompare_2);
list[2].Should().Match(stringToCompare_3);
</code>```

The biggest problem that I see here is it's sort of hard to memorize what string was added to a particular index of the list (unstoppable scrolling between the code is boring). My question: is there any more elegant way to handle this situation? Something that might look like below (List class method ValueOf is fictional):

```<code>var list = new List<string>();
var item_1_USA = "USA";
var item_2_Canada = "Canada";
var item_3_Cuba = "Cuba";
list.ValueOf(item_1_USA).Should().Match(stringToCompare_1);
list.ValueOf(item_1_Canada).Should().Match(stringToCompare_2);
list.ValueOf(item_1_Cuba).Should().Match(stringToCompare_3);
</code>```

As many suggested (including @Postlagerkarte) to edit the question to clarify what I'm trying to achieve. I'm testing the web app, and while going through every step of this application (imagine booking engine), I need to capture and store different info (like user's First Name, Last Name, Email Address, Phone Number, etc). The amount of the captured info can sometimes exceed 2000 items. Currently I'm using data structure List. Later, at the final step of my application, I need to compare my stored values with what ever present on this final page. For instance: user's first name, that was captured on Step 2 of the booking engine must match with value on final step. List Contains method won't be suitable here as it can validate incorrect information. Accessing the values using list[0]....list[N] is very inconvenient, as I can forget what exactly was stored at that index. I'm solving it now by scrolling through the code to return back. Any wise navigation is appreciated.

答:
Why can't you use the Contains() method saying

```<code>list.Contains(stringToCompare_1);
</code>```

Body:
So I have a slightly interesting problem right here. What I'm trying to achieve is to add between 1000 to 2000 string variables to the list and later compare them with another strings. So far I can achieve this by using below code:

var list = new List<string>();
var item_1 = "USA";
var item_2 = "Canada";
var item_3 = "Cuba";
...................
var item_N = "Country_N";
list.Add(item_1);
list.Add(item_2);
list.Add(item_3);
.................
list.Add(item_N);

And comparing them with another strings looks like below (using FluentAssertions class):

list[0].Should().Match(stringToCompare_1);
list[1].Should().Match(stringToCompare_2);
list[2].Should().Match(stringToCompare_3);

The biggest problem that I see here is it's sort of hard to memorize what string was added to a particular index of the list (unstoppable scrolling between the code is boring). My question: is there any more elegant way to handle this situation? Something that might look like below (List class method ValueOf is fictional):

var list = new List<string>();
var item_1_USA = "USA";
var item_2_Canada = "Canada";
var item_3_Cuba = "Cuba";
list.ValueOf(item_1_USA).Should().Match(stringToCompare_1);
list.ValueOf(item_1_Canada).Should().Match(stringToCompare_2);
list.ValueOf(item_1_Cuba).Should().Match(stringToCompare_3);

As many suggested (including @Postlagerkarte) to edit the question to clarify what I'm trying to achieve. I'm testing the web app, and while going through every step of this application (imagine booking engine), I need to capture and store different info (like user's First Name, Last Name, Email Address, Phone Number, etc). The amount of the captured info can sometimes exceed 2000 items. Currently I'm using data structure List. Later, at the final step of my application, I need to compare my stored values with what ever present on this final page. For instance: user's first name, that was captured on Step 2 of the booking engine must match with value on final step. List Contains method won't be suitable here as it can validate incorrect information. Accessing the values using list[0]....list[N] is very inconvenient, as I can forget what exactly was stored at that index. I'm solving it now by scrolling through the code to return back. Any wise navigation is appreciated.

Body:
Why can't you use the Contains() method saying

list.Contains(stringToCompare_1);


问:
How to change Hive Database to Oracle Database as Primary Database in Kylo?
I'm kylo platform for my tool. I need the Oracle database instead of the hive database on the kylo platform.</p>

答:
Yes, you can use Kylo to land data in Oracle as the destination database instead of Hive.The (data ingest template) that comes with Kylo uses Hive by default. Some features in Kylo also depend on Hive (e.g. Validation, Profiling).

However, you can create your custom template in NiFi that uses Oracle as the destination database. NiFi has some processors that can help you design your template. One example is PutSQL processor. All available processors are documented here.

The steps to use this flow via Kylo are:

Create the template in NiFi and test that it works.

Register the template in Kylo and configure properties that should be exposed to a feed creator.

Create a feed out of the registered template and provide feed-specific values for the properties exposed in step 2.

Schedule the feed to run on a cron or time-based schedule. Kylo will show feed executions via the Operations Manager UI.

Kylo has some useful video tutorials that can help you with configuring the above steps (template registration, feed creation, feed monitoring).

ContentLicense: CC BY-SA 4.0


问:
Blueprism: how to use the replace function in a calculation stage?
I am reading a text from an application using BluePrism. The text has the following structure (the number varies from case to case): "Please take note of your order reference: 525". I need to be able to extract the number from the text. Looking at the calculation stage, there is a replace function: replace(text, pattern, new-text). I want to use this function to replace all alphabetic characters in my text with an empty string to return only whatever is numeric. How can I input that in the pattern?
So I want something like this: </p>

```<code>Replace([Order confirmation text ], /^[A-z]+$/, " ")
</code>```

<p>Also, I tried to look for a proper documentation for the VBOs that are shipped with blueprism, but couldn't find any. Does anyone know where we can get documentations for blueprism functions? </p>

答:
A few things here:

-Your pattern isn't matching because it's looking for a constant string of letters from start to finish (^ anchors to the beginning of the string and $ anchors to the end).

-You're replacing the pattern with a space, not an empty string, so you'll end up with a bunch of spaces in your result even if you correct the pattern.

-You said you only want to replace alphabetic characters, but it looks like you also want to get rid of spaces and colons.

Try replacing [A-Za-z :]+ with "".

Body:
I am reading a text from an application using BluePrism. The text has the following structure (the number varies from case to case): "Please take note of your order reference: 525". I need to be able to extract the number from the text. Looking at the calculation stage, there is a replace function: replace(text, pattern, new-text). I want to use this function to replace all alphabetic characters in my text with an empty string to return only whatever is numeric. How can I input that in the pattern?
So I want something like this:

Replace([Order confirmation text ], /^[A-z]+$/, " ")

Also, I tried to look for a proper documentation for the VBOs that are shipped with blueprism, but couldn't find any. Does anyone know where we can get documentations for blueprism functions?


问:
karate: File upload using csv file
am trying to implement testing for POST request  to upload file using csv file format.But getting response as 500 exception.</p>

```<code>Given path  location + 'abc/ssd?&id=22'
And multipart file myFile = { read: 'test.csv', filename: 'test.csv', ContentType: 'text/csv' }
When method post
Then status 200

Response :
Content-Type : multipart/form-data; boundary=jyrjg5ysdfdgj4gdgsjm2342
</code>```

答:
It is very hard to figure with the lack of details.

Anyway, note that it should be contentType with a lower-case c.

If you still have problems, try providing more info.

Title: karate: File upload using csv file

Body:
am trying to implement testing for POST request  to upload file using csv file format.But getting response as 500 exception.

Given path  location + 'abc/ssd?&id=22'
And multipart file myFile = { read: 'test.csv', filename: 'test.csv', ContentType: 'text/csv' }
When method post
Then status 200

Response :
Content-Type : multipart/form-data; boundary=jyrjg5ysdfdgj4gdgsjm2342


问:
Object is possibly 'undefined'
So I am in vscode on typescript 2.5.3 and the following code:

```<code>export function isHttpHeaders ( headers: HttpHeaders | undefined ):
headers is HttpHeaders {
    return !!headers && !!headers.get && !!headers.set
}

function headersToHeadersSpec ( options?: RequestOptionsArgs ):
 Headers | undefined {

  const { headers } = options as RequestOptionsArgs

  if ( isHttpHeaders( headers ) ) {
    const reqHeaders = new Headers()
    headers.forEach( reqHeaders.set.bind( reqHeaders ) )
    return reqHeaders
  } else {
    return undefined
  }
}
</code>```

When I attempt to compile, for some reason the line headers.forEach( reqHeaders.set.bind( reqHeaders ) ) is complaining that the headers value is possibly undefined. Shouldn't the type guard guarantee that the value is not undefined?

答:
The error comes from your definition of HttpHeaders which sets forEach as an optional member.

To fix the error, just label-it non-optional by removing the ? :

```<code>interface HttpHeaders {
  get?: string
  set?: string
  forEach (Function): void
}
</code>```

Title: Object is possibly 'undefined'

Body:
So I am in vscode on typescript 2.5.3 and the following code:

export function isHttpHeaders ( headers: HttpHeaders | undefined ):
headers is HttpHeaders {
    return !!headers && !!headers.get && !!headers.set
}

function headersToHeadersSpec ( options?: RequestOptionsArgs ):
 Headers | undefined {

  const { headers } = options as RequestOptionsArgs

  if ( isHttpHeaders( headers ) ) {
    const reqHeaders = new Headers()
    headers.forEach( reqHeaders.set.bind( reqHeaders ) )
    return reqHeaders
  } else {
    return undefined
  }
}

When I attempt to compile, for some reason the line headers.forEach( reqHeaders.set.bind( reqHeaders ) ) is complaining that the headers value is possibly undefined. Shouldn't the type guard guarantee that the value is not undefined?

Body:
The error comes from your definition of HttpHeaders which sets forEach as an optional member.

To fix the error, just label-it non-optional by removing the ? :

interface HttpHeaders {
  get?: string
  set?: string
  forEach (Function): void
}


问:
Beautifulsoup code no longer working in python script
I have a python script that I am having trouble with and I think I have narrowed the issue down to this line:

```<code>formkey = soup.find_all("script")[9].string[153:][:-141]
</code>```

I believe that this line is supposed to return the value of "form_key" on this page https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html

Is there something I'm missing? Thanks

答:
You should use BeautifulSoup to find elements and then regex (re) to parse text inside your target elements. Like this:

```<code>import re, requests
from bs4 import BeautifulSoup

regex = re.compile(r'formKey:\s*"(.*)"')

r = requests.get('https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html')
soup = BeautifulSoup(r.text, "html5lib")
scripts = soup.find_all("script")

all_of_them = [None if match is None else match.groups() for match in [regex.search(script.text) for script in scripts]]
just_the_matches = [match.groups() for match in [regex.search(script.text) for script in scripts] if script is not None]
</code>```

The results:

```<code>>>> all_of_them
[None, None, None, None, None, None, None, None, None, (u'U53YNK8paAE4Cdij',), None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
>>> just_the_matches
[(u'U53YNK8paAE4Cdij',)]
</code>```

Important:

Do not make assumptions, such as "it's the 10th script" or "the data I want is exactly between characters XXX and YYY".

If they add a script, your program is broken. You don't want that.

If they change a bit of this 10th script, your program is broken. You don't want that.

Try to always think of how to make your program more robust to external perturbations.

Also:

As @alexisdevarennes puts it, if you can have the data in several places, try to retrieve it from the easiest place (or the most robust place).

Body:
I have a python script that I am having trouble with and I think I have narrowed the issue down to this line:

formkey = soup.find_all("script")[9].string[153:][:-141]

I believe that this line is supposed to return the value of "form_key" on this page https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html

Is there something I'm missing? Thanks

Body:
You should use BeautifulSoup to find elements and then regex (re) to parse text inside your target elements. Like this:

import re, requests
from bs4 import BeautifulSoup

regex = re.compile(r'formKey:\s*"(.*)"')

r = requests.get('https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html')
soup = BeautifulSoup(r.text, "html5lib")
scripts = soup.find_all("script")

all_of_them = [None if match is None else match.groups() for match in [regex.search(script.text) for script in scripts]]
just_the_matches = [match.groups() for match in [regex.search(script.text) for script in scripts] if script is not None]

The results:

>>> all_of_them
[None, None, None, None, None, None, None, None, None, (u'U53YNK8paAE4Cdij',), None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
>>> just_the_matches
[(u'U53YNK8paAE4Cdij',)]

Important:

Do not make assumptions, such as "it's the 10th script" or "the data I want is exactly between characters XXX and YYY".

If they add a script, your program is broken. You don't want that.

If they change a bit of this 10th script, your program is broken. You don't want that.

Try to always think of how to make your program more robust to external perturbations.

Also:

As @alexisdevarennes puts it, if you can have the data in several places, try to retrieve it from the easiest place (or the most robust place).


问:
How to include common elements in onsen ui pages?
Is there a way to include commmon elements e.g splitter menu in different html pages in onsen ui rather than repeating the code on each page?</p>

答:
Your question was kinda vague, but if I understand correctly you want the ons-splitter to persist across multiple pages? If that's the case, you should just be updating the ons-splitter-content inside ons-splitter, it can be any valid html.

Same thing goes for ons-tabbar for example, change the "content" element, and the tab structure will persist across pages.

Here's an example in the documentation for multiple pages with a splitter:

https://onsen.io/v2/api/js/ons-splitter.html


问:
Some redirects are translating incorrectly while most are working as expected
Using Apache, MySQL, and PHP, and I'm noticing strange behaviors with URL redirects.

Our db entry is

```<code>src = 'pfe/pdf/03-b-06.pdf'
dst = 'https://site2.com/communities/policyprocedure/pfe/Active/03-b-06.pdf'
</code>```

The redirect result translates correctly:

```<code>'http://site1.com/pfe/pdf/03-b-06.pdf'
</code>```

Resolves to:

```<code>'https://site2.com/communities/policyprocedure/pfe/Active/03-b-06.pdf'
</code>```

However, this one does not resolve correctly:

```<code>src = 'employee/jsp/common/generic.jsp?id=22910'
dst = 'https://site2.com/communities/policyprocedure/pfe/intranet-pages/22-urology'
</code>```

Redirect translates as:

```<code>'http://site1.com/employee/jsp/common/generic.jsp?id=22910'
</code>```

Resloves to:

```<code>'https://site2.com/communities/policyprocedure/pfe/intranet-pages/22.-urology'
</code>```

We have thousands of URLs using numbers, and hyphens, and alpha characters  (i.e. /03-example) that work but only a dozen out of several thousand don't work.

Could it be something to do with the destination and its URL encoding? I have made sure it wasn't a character set or character encoding in the SQL insert/update strings.

答:
index php:

```<code><?php
// Pull in the database config
require_once dirname(__FILE__) . "/config.php";
require_once dirname(__FILE__) . "/functions.php";

// Turn off error reporting
error_reporting(0);

// Get the requested URL
$src = htmlspecialchars($_GET['src']);

// Handle the empty src
if (empty($src)) {
  header('Location: ' . $at);
  exit;
}

// Open a DB connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Stop if the DB connection fails
if ($conn->connect_error) {
  die('Connection failed: ' . $conn->connect_error);
}

// Query the database
$sql = "SELECT dst FROM map WHERE src = '" . $src . "'";
$result = $conn->query($sql);
$conn->close();

// Act on the results
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    if (!getResult($row['dst'])) {
      fourOhFourCapture($sp,$row['dst']);
    }
    header('Location: ' . $row['dst']);

  }
</code>```

config .php:

```<code><?php

$servername = 'servername';
$username = 'username';
$password = 'password';
$dbname = 'database';

$file = '/home/svc_account/404_results.txt';

$at = 'https://site1.cpm/';
$sp = 'https://site2.com/';
</code>```

function php:

```<code><?php

function urlExist($url)
{
  $handle = curl_init($url);

  if (false === $handle) {
    return false;
  }

  curl_setopt($handle, CURLOPT_HEADER, false);
  curl_setopt($handle, CURLOPT_FAILONERROR, true);
  curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") );
  curl_setopt($handle, CURLOPT_NOBODY, true);
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
  $connectable = curl_exec($handle);
  curl_close($handle);
  return $connectable;
}

function fourOhFour($url,$req)
{
  header('Location: ' . $url . '?requestUrl=' . $req);
}

function fourOhFourCapture($url,$src)
{
  global $file;
   file_put_contents($file, $url.$src, FILE_APPEND | LOCK_EX);
}

/**
 * getResult - accepts a url, uses curl to check the status, and returns false if the code is 404, and true for any
 * other result
 * @param $url
 * @return bool
 */
function getResult($url) {

  $handle = curl_init($url);
  curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

  /* Get the HTML or whatever is linked in $url. */
  $response = curl_exec($handle);

  /* Check for 404 (file not found). */
  $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  curl_close($handle);

  if($httpCode == 404) {
    return false;
  } else {
    return true;
  }

}
</code>```

apache rewrite:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteRule ^$ https://site2.com/ [L]

  RewriteRule ^/index\.php$ - [L]
  RewriteRule ^/lbactive\.html$ - [L]
  RewriteRule ^/robots\.txt$ - [L]

  RewriteCond %{REQUEST_URI} ^/dept/department\.jsp [OR]
  RewriteCond %{REQUEST_URI} ^/common/generic\.jsp
  RewriteRule .* %{REQUEST_URI} [E=IS_LEGACY_OID:TRUE]

  RewriteMap legacy_oid_map txt:/var/vhost/site1/data/rewrites_legacy_oid.txt

  RewriteCond %{ENV:IS_LEGACY_OID} ^TRUE$
  RewriteCond %{QUERY_STRING} id=([0-9]+)
  RewriteRule .* ${legacy_oid_map:%1}? [R=301,L]

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

  RewriteRule ^/(.*)$ /index.php?src=$1 [R=301,L]
</IfModule>
</code>```

Body:
Using Apache, MySQL, and PHP, and I'm noticing strange behaviors with URL redirects.

Our db entry is

src = 'pfe/pdf/03-b-06.pdf'
dst = 'https://site2.com/communities/policyprocedure/pfe/Active/03-b-06.pdf'

The redirect result translates correctly:

'http://site1.com/pfe/pdf/03-b-06.pdf'

Resolves to:

'https://site2.com/communities/policyprocedure/pfe/Active/03-b-06.pdf'

However, this one does not resolve correctly:

src = 'employee/jsp/common/generic.jsp?id=22910'
dst = 'https://site2.com/communities/policyprocedure/pfe/intranet-pages/22-urology'

Redirect translates as:

'http://site1.com/employee/jsp/common/generic.jsp?id=22910'

Resloves to:

'https://site2.com/communities/policyprocedure/pfe/intranet-pages/22.-urology'

We have thousands of URLs using numbers, and hyphens, and alpha characters  (i.e. /03-example) that work but only a dozen out of several thousand don't work.

Could it be something to do with the destination and its URL encoding? I have made sure it wasn't a character set or character encoding in the SQL insert/update strings.

Body:
index php:

<?php
// Pull in the database config
require_once dirname(__FILE__) . "/config.php";
require_once dirname(__FILE__) . "/functions.php";

// Turn off error reporting
error_reporting(0);

// Get the requested URL
$src = htmlspecialchars($_GET['src']);

// Handle the empty src
if (empty($src)) {
  header('Location: ' . $at);
  exit;
}

// Open a DB connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Stop if the DB connection fails
if ($conn->connect_error) {
  die('Connection failed: ' . $conn->connect_error);
}

// Query the database
$sql = "SELECT dst FROM map WHERE src = '" . $src . "'";
$result = $conn->query($sql);
$conn->close();

// Act on the results
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    if (!getResult($row['dst'])) {
      fourOhFourCapture($sp,$row['dst']);
    }
    header('Location: ' . $row['dst']);

  }

config .php:

<?php

$servername = 'servername';
$username = 'username';
$password = 'password';
$dbname = 'database';

$file = '/home/svc_account/404_results.txt';

$at = 'https://site1.cpm/';
$sp = 'https://site2.com/';

function php:

<?php

function urlExist($url)
{
  $handle = curl_init($url);

  if (false === $handle) {
    return false;
  }

  curl_setopt($handle, CURLOPT_HEADER, false);
  curl_setopt($handle, CURLOPT_FAILONERROR, true);
  curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") );
  curl_setopt($handle, CURLOPT_NOBODY, true);
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
  $connectable = curl_exec($handle);
  curl_close($handle);
  return $connectable;
}

function fourOhFour($url,$req)
{
  header('Location: ' . $url . '?requestUrl=' . $req);
}

function fourOhFourCapture($url,$src)
{
  global $file;
   file_put_contents($file, $url.$src, FILE_APPEND | LOCK_EX);
}

/**
 * getResult - accepts a url, uses curl to check the status, and returns false if the code is 404, and true for any
 * other result
 * @param $url
 * @return bool
 */
function getResult($url) {

  $handle = curl_init($url);
  curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

  /* Get the HTML or whatever is linked in $url. */
  $response = curl_exec($handle);

  /* Check for 404 (file not found). */
  $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  curl_close($handle);

  if($httpCode == 404) {
    return false;
  } else {
    return true;
  }

}

apache rewrite:

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteRule ^$ https://site2.com/ [L]

  RewriteRule ^/index\.php$ - [L]
  RewriteRule ^/lbactive\.html$ - [L]
  RewriteRule ^/robots\.txt$ - [L]

  RewriteCond %{REQUEST_URI} ^/dept/department\.jsp [OR]
  RewriteCond %{REQUEST_URI} ^/common/generic\.jsp
  RewriteRule .* %{REQUEST_URI} [E=IS_LEGACY_OID:TRUE]

  RewriteMap legacy_oid_map txt:/var/vhost/site1/data/rewrites_legacy_oid.txt

  RewriteCond %{ENV:IS_LEGACY_OID} ^TRUE$
  RewriteCond %{QUERY_STRING} id=([0-9]+)
  RewriteRule .* ${legacy_oid_map:%1}? [R=301,L]

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

  RewriteRule ^/(.*)$ /index.php?src=$1 [R=301,L]
</IfModule>


问:
Shortening repeating functions
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

```

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

答:
Well you could inspect the element that triggered the event to get it's associated value like this and to be consistant with yoru slider you can bind to all inputs with a special class like this:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var buttons = document.getElementsByClassName('button');

output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
for(var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.onclick = function() {
    var a = 'test'+this.value;
    console.log('test: ' + a +' '+ slider.value);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<input type="button" class="button" value="3"></code>```

Title: Shortening repeating functions

Body:
I am trying to make the sliders output the values depending on the which button has been clicked.

<!DOCTYPE html>

  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

<input type="button" onclick="function1()" value="1">
<input type="button" onclick="function2()" value="2">
<input type="button" onclick="function3()" value="3">

</script>

As you can see for each of the buttons, the functions are being repeated and only the variable 'a' is being changed. I was wondering if there was a way to make this code more efficient, in other words shorter.

Please let me know if you have any solutions for this.
Thanks.

Body:
Well you could inspect the element that triggered the event to get it's associated value like this and to be consistant with yoru slider you can bind to all inputs with a special class like this:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var buttons = document.getElementsByClassName('button');

output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
for(var i = 0; i < buttons.length; i++) {
  var button = buttons[i];
  button.onclick = function() {
    var a = 'test'+this.value;
    console.log('test: ' + a +' '+ slider.value);
  }
}

<div id="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<input type="button" class="button" value="3">


答:
I accomplish this by simply writing the data frame and reading it back specifiying all columns are numeric. I use data.table package, but it applies to basic read/write functions as well. </p>

```<code>library(data.table)
fwrite(dfm,"some.name.temp")
dfm <- fread("some.name.temp",colClasses="numeric")
</code>```

Title: Change all columns from factor to numeric in R

Body:
I am working with a big dataset that is causing some trouble because some of the columns I the dataset are being treated as factors. How can I convert all of the columns from factor to numeric, without having to do that column by column??

I have tried to apply a small loop, but it returns NA values. Here's a sample data that applies to the case:

data <- structure(list(v1 = c(22.394, 43.72, 58.544, 56.877, 1.659, 29.142,
67.836, 68.851), v2 = c(144.373, 72.3, 119.418, 112.429, 35.779,
41.661, 166.941, 126.548), v3 = structure(c(33L, 29L, 33L, 5L,
13L, 31L, 5L, 8L), .Label = c("", "#VALUE!", "0", "1", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20",
"21", "22", "23", "24", "25", "26", "28", "29", "3", "30", "32",
"33", "4", "48", "5", "6", "7", "8", "9"), class = "factor"),
    v4 = structure(c(24L, 6L, 22L, 23L, 16L, 22L, 23L, 26L), .Label = c("",
    "-1", "-2", "-4", "#VALUE!", "0", "1", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "2", "24", "28",
    "29", "3", "4", "5", "6", "7", "8", "9"), class = "factor")), .Names = c("v1",
"v2", "v3", "v4"), row.names = c("4", "5", "6", "7", "8", "9",
"10", "11"), class = "data.frame")

for (i in 1:ncol(data)){
data[,i] <- as.numeric(as.character(data[i]))
} ## returns NAs

Is there some command that I can apply to turn all these columns into a numeric class?

Body:
I accomplish this by simply writing the data frame and reading it back specifiying all columns are numeric. I use data.table package, but it applies to basic read/write functions as well.

library(data.table)
fwrite(dfm,"some.name.temp")
dfm <- fread("some.name.temp",colClasses="numeric")


问:
Xamarin multi-dex issue
I am using xamarin with infragistics native controls. My android project won't compile because of this

```<code>trouble writing output: Too many method references: 73153; max is 65536.
        You may try using --multi-dex option.
</code>```

I attempt to enable the mutli dex option, the I get this

```<code>Error: Error executing task CheckDuplicateJavaLibraries: Could not find file "/Users/..../Library/Developer/Xamarin/android-sdk-macosx/extras/android/support/multidex/library/libs/android-support-multidex.jar". (Test)
</code>```

How do I fix this in Xamarin? I also can't find android-support-mutlidex.jar to download even if I were to install it...

Help please!

答:
Try the following:

enable ProGuard first in Android project settings

if you still have more than 64k Java methods - switch Multi-Dex on instead

if that didn't help, try to disable linker having your Multi-Dex enabled

Title: Xamarin multi-dex issue

Body:
I am using xamarin with infragistics native controls. My android project won't compile because of this

trouble writing output: Too many method references: 73153; max is 65536.
        You may try using --multi-dex option.

I attempt to enable the mutli dex option, the I get this

Error: Error executing task CheckDuplicateJavaLibraries: Could not find file "/Users/..../Library/Developer/Xamarin/android-sdk-macosx/extras/android/support/multidex/library/libs/android-support-multidex.jar". (Test)

How do I fix this in Xamarin? I also can't find android-support-mutlidex.jar to download even if I were to install it...

Help please!


问:
JavaScript - I condition "if" doesn't respond properly
Here is the idea behind the code: The article has an avatar object in the beginning. e.g.:

```<code><div class="column-right">
  <div class="inner">
    <h3>Header of article</h3>
    <div id="avatar">
      <img>
      <div>avatar title</div>
    </div>
    <p>long text</p>
  </div>
 </div>
</code>```

When a user scrolls down, the avatar obviously disappears. So I wanted to make a clone of said avatar and put it in the left column using position fixed.

Here is the JavaScript code:

```<code>document.body.onscroll = function(e) {
    var scrolled = document.documentElement.scrollTop;
    var newAv;

    if ( (scrolled > avatarCoords.bottom) && !newAv ) {
        //check if user scrolled below the avatar. if clone of avatar exists, do anything:

        newAv = avatar.cloneNode(true);
        //clone actual element, whick user can't   see right now

        newAv.style.position = "fixed";
        newAv.style.left = 2 + "px";
        newAv.style.top = 10 + "px";

        document.body.appendChild(newAv);  //add clone in document
    }

    if( (scrolled < avatarCoords.bottom) && newAv ) {
        newAv.parentNode.removeChild(newAv);
    }
}

function getCoords(element) {
    var box = element.getBoundingClientRect();
    return {
        bottom: box.top + avatar.offsetHeight
    }
}
</code>```

I don't understand why the first condition keeps responding even though the variable newAv is assigned. !newAv is supposed to be false after first cloning.

If you can answer the first question, tell me why newAv can't be removed as well.

Thank you!

答:
You keep redefining newAV inside the onscroll function.

Make this a global variable (so this remembers the value from previous call):

```<code>var newAv;
document.body.onscroll = function(e) {
  var scrolled = document.documentElement.scrollTop; // etc
</code>```

Body:
Here is the idea behind the code: The article has an avatar object in the beginning. e.g.:

Header of article

avatar title

long text

When a user scrolls down, the avatar obviously disappears. So I wanted to make a clone of said avatar and put it in the left column using position fixed.

Here is the JavaScript code:

document.body.onscroll = function(e) {
    var scrolled = document.documentElement.scrollTop;
    var newAv;

    if ( (scrolled > avatarCoords.bottom) && !newAv ) {
        //check if user scrolled below the avatar. if clone of avatar exists, do anything:

        newAv = avatar.cloneNode(true);
        //clone actual element, whick user can't   see right now

        newAv.style.position = "fixed";
        newAv.style.left = 2 + "px";
        newAv.style.top = 10 + "px";

        document.body.appendChild(newAv);  //add clone in document
    }

    if( (scrolled < avatarCoords.bottom) && newAv ) {
        newAv.parentNode.removeChild(newAv);
    }
}

function getCoords(element) {
    var box = element.getBoundingClientRect();
    return {
        bottom: box.top + avatar.offsetHeight
    }
}

I don't understand why the first condition keeps responding even though the variable newAv is assigned. !newAv is supposed to be false after first cloning.

If you can answer the first question, tell me why newAv can't be removed as well.

Thank you!

Body:
You keep redefining newAV inside the onscroll function.

Make this a global variable (so this remembers the value from previous call):

var newAv;
document.body.onscroll = function(e) {
  var scrolled = document.documentElement.scrollTop; // etc


问:
Custom Discussion board alerts stopped working in SharePoint 2013
We had Custom Discussion board alerts on 4 servers SharePoint 2013 farm working until I changed something in the AlertHandler : IAlertNotifyHandler class
I tried debugging by attaching to the timer service but nothing works.

Anyone has a way to debug or figure out why there are no alert emails from Discussion boards but there are from other lists. (Even twice).

Thanks in advance

答:
Turns out the farm had an invalid server registered with it.
After removing the server from the farm, custom alerts started showing up in the inbox. </p>


问:
Convert void (*)() to void (*)(unsigned char)
I'm trying to convert a void (*)() to void (*)(unsigned char) but my knowledge in C++ isn't good enough. I searched, but I could not find any examples. So I thought to create a function of function but I get some error:

```<code>typedef void (* voidFuncPtr)();
void castHandler(voidFuncPtr handler)(uint8_t gpio_num)
{
    handler();
}

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    // typedef void (* voidFuncPtr)();
    // typedef void (* gpio_interrupt_handler_t)(uint8_t gpio_num);
    // typedef void (* gpio_interrupt_handler_t)(unsigned char)
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));
}
</code>```

error: 'castHandler' declared as function returning a function  void
  castHandler(voidFuncPtr handler)(uint8_t gpio_num)

error: 'castHandler' was not declared in this scope
       gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));

Can someone help me?

答:
You need to maintain a table of handlers for each GPIO. Something like the following (untested and incomplete - some initializations and error checking are omitted) code:</p>

```<code>typedef void (* voidFuncPtr)();

voidFuncPtr handlers[MAX_HANDLERS];

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    handlers[pin] = handler;
}

void handleGPIO(unsigned char pin)
{
    if (handlers[pin])
        handlers[pin]();
}

void enableGPIOInterrupts(void)
{
    /// Do this for each available pin
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, handleGPIO);
}
</code>```

Body:
I'm trying to convert a void (*)() to void (*)(unsigned char) but my knowledge in C++ isn't good enough. I searched, but I could not find any examples. So I thought to create a function of function but I get some error:

typedef void (* voidFuncPtr)();
void castHandler(voidFuncPtr handler)(uint8_t gpio_num)
{
    handler();
}

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    // typedef void (* voidFuncPtr)();
    // typedef void (* gpio_interrupt_handler_t)(uint8_t gpio_num);
    // typedef void (* gpio_interrupt_handler_t)(unsigned char)
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));
}

error: 'castHandler' declared as function returning a function  void
  castHandler(voidFuncPtr handler)(uint8_t gpio_num)

error: 'castHandler' was not declared in this scope
       gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));

Can someone help me?

Body:
You need to maintain a table of handlers for each GPIO. Something like the following (untested and incomplete - some initializations and error checking are omitted) code:

typedef void (* voidFuncPtr)();

voidFuncPtr handlers[MAX_HANDLERS];

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    handlers[pin] = handler;
}

void handleGPIO(unsigned char pin)
{
    if (handlers[pin])
        handlers[pin]();
}

void enableGPIOInterrupts(void)
{
    /// Do this for each available pin
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, handleGPIO);
}


问:
How do I do this in Javascript and Django?
I'm used to putting my javascripts in the top of my page in the head section.  In my javascript, I use a lot of template stuff from Django like:  {{ user.id }} {{ post.body }}

I decided to move my javascript into another file, and then import it using: script src=

But since my javascript is in another file now it can't read my Django template stuff.

What do I do? I have Django template stuff all over the javascript, and I must move my javascript to another file.

答:
You can generate your javascript as a template too! But that requires serving your dynamic javascript via Django.

For instance..

```<code>#views
def some_js(request):
    return render_to_response('js/some_dynamic_js.js', {}, mimetype='text/javascript')
</code>```

There is nothing that says that Django templates must be HTML. They are simply a way of templating TEXT. Code is text, so it can be templated. I do this in my current project.

Body:
You can generate your javascript as a template too! But that requires serving your dynamic javascript via Django.

For instance..

#views
def some_js(request):
    return render_to_response('js/some_dynamic_js.js', {}, mimetype='text/javascript')

There is nothing that says that Django templates must be HTML. They are simply a way of templating TEXT. Code is text, so it can be templated. I do this in my current project.


问:
Inequality joins in Pandas?
I usually use Dataframe.merge to combine dataframes in pandas. From my understanding, this only works on equality joins. What is the idiomatic way to join two dataframes using other types of checks (e.g. inequality)?</p>

答:
merge() is fairly limited.  You can accomplish more complex joins using pandasql.sqldf.  You can write pretty much any sql query and refer to your existing dataframes as table names in the sql statements.

https://github.com/yhat/pandasql/
A known bug is the inability to select multiple tables in product joins, such as

```<code>select d1.something, d2.something else from df1 as d1, df2 as d2 where d1.date=d2.date
</code>```

However, if you can do joins without any problem, and a statement like I have above can be translated into a join.

Title: Inequality joins in Pandas?

Body:
merge() is fairly limited.  You can accomplish more complex joins using pandasql.sqldf.  You can write pretty much any sql query and refer to your existing dataframes as table names in the sql statements.

https://github.com/yhat/pandasql/
A known bug is the inability to select multiple tables in product joins, such as

select d1.something, d2.something else from df1 as d1, df2 as d2 where d1.date=d2.date

However, if you can do joins without any problem, and a statement like I have above can be translated into a join.


问:
Qt: QHeaderView place sort-indicator on the right of the header text
If I set: QHeaderView::down-arrow { subcontrol-position: center left}, the down-arrow is on the left of the column, and if I set center right, it is placed on the right of the column, but I want to place the arrow next to the title (on the right side).

答:
The way I sorted was by creating a QProxyStyle for the header, and override drawControl.
I also assigned an empty icon to hide the default one.

treeviewwidget.cpp at initialize():

```<code>treeviewHeaderProxy* m_oHeaderStyle = new treeviewHeaderProxy();
treeview->header()->setStyle(m_oHeaderStyle);
treeview->header()->setDefaultAlignment(Qt::AlignCenter);
treeview->header()->setStyleSheet("QHeaderView::down-arrow { image: url(:/shared/empty); }"
                                "QHeaderView::up-arrow { image: url(:/shared/empty); } ");
</code>```

treeviewHeaderProxy.h:

```<code>class treeviewHeaderProxy : public QProxyStyle
{
public:
    explicit treeviewHeaderProxy();
    void drawControl(ControlElement oCtrElement, const QStyleOption * poStylrOptionption, QPainter * poPainter, const QWidget * poWidget = 0) const;

};
</code>```

treeviewHeaderProxy.cpp:

```<code>void treeviewHeaderProxy::drawControl(ControlElement oCtrElement, const QStyleOption *poStyleOptionption, QPainter *poPainter, const QWidget *poWidget) const
{
    // Header label?
    if (oCtrElement == CE_HeaderLabel) {
        QStyleOptionHeader *poStyleOptionHeader = (QStyleOptionHeader *) poStyleOptionption;
        QStyleOptionHeader::SortIndicator sortOption = poStyleOptionHeader->sortIndicator;
        QRect oRect = poStyleOptionHeader->rect;

        // Text
        int iTextWidth = poStyleOptionHeader->fontMetrics.width(poStyleOptionHeader->text);
        int iTextHeight = poStyleOptionHeader->fontMetrics.height();
        QRect oTextRect = QRect(oRect.left() + oRect.width(), catRect.top() + (oRect.height() - iTextHeight)/2,
                                iTextWidth*1.2, iTextHeight);
        poPainter->setPen(SUPER_DARK_GREY);
        poPainter->drawText(oTextRect, poStyleOptionHeader->text); // Draw text

        // Sort Indicator
        QPixmap oSortPixmap;
        switch(sortOption){
        case QStyleOptionHeader::SortDown:
            oSortPixmap = QIcon(":/shared/drop_up_grey").pixmap(10,10);
            break;
        case QStyleOptionHeader::SortUp:
            oSortPixmap = QIcon(":/shared/drop_down_grey").pixmap(10,10);
            break;
        }

        if(!oSortPixmap.isNull()){
            QRect oSortRect = QRect(oTextRect.left() + oTextRect.width(), oRect.top() + (oRect.height() - oSortPixmap.height())/2,
                                    oSortPixmap.width(), oSortPixmap.height());
            poPainter->drawPixmap(oSortRect, oSortPixmap); // Draw sortIcon
        }
        return;
    }
    QProxyStyle::drawControl(oCtrElement, poStyleOptionption, poPainter, poWidget);
}
</code>```

Body:
The way I sorted was by creating a QProxyStyle for the header, and override drawControl.
I also assigned an empty icon to hide the default one.

treeviewwidget.cpp at initialize():

treeviewHeaderProxy* m_oHeaderStyle = new treeviewHeaderProxy();
treeview->header()->setStyle(m_oHeaderStyle);
treeview->header()->setDefaultAlignment(Qt::AlignCenter);
treeview->header()->setStyleSheet("QHeaderView::down-arrow { image: url(:/shared/empty); }"
                                "QHeaderView::up-arrow { image: url(:/shared/empty); } ");

treeviewHeaderProxy.h:

class treeviewHeaderProxy : public QProxyStyle
{
public:
    explicit treeviewHeaderProxy();
    void drawControl(ControlElement oCtrElement, const QStyleOption * poStylrOptionption, QPainter * poPainter, const QWidget * poWidget = 0) const;

};

treeviewHeaderProxy.cpp:

void treeviewHeaderProxy::drawControl(ControlElement oCtrElement, const QStyleOption *poStyleOptionption, QPainter *poPainter, const QWidget *poWidget) const
{
    // Header label?
    if (oCtrElement == CE_HeaderLabel) {
        QStyleOptionHeader *poStyleOptionHeader = (QStyleOptionHeader *) poStyleOptionption;
        QStyleOptionHeader::SortIndicator sortOption = poStyleOptionHeader->sortIndicator;
        QRect oRect = poStyleOptionHeader->rect;

        // Text
        int iTextWidth = poStyleOptionHeader->fontMetrics.width(poStyleOptionHeader->text);
        int iTextHeight = poStyleOptionHeader->fontMetrics.height();
        QRect oTextRect = QRect(oRect.left() + oRect.width(), catRect.top() + (oRect.height() - iTextHeight)/2,
                                iTextWidth*1.2, iTextHeight);
        poPainter->setPen(SUPER_DARK_GREY);
        poPainter->drawText(oTextRect, poStyleOptionHeader->text); // Draw text

        // Sort Indicator
        QPixmap oSortPixmap;
        switch(sortOption){
        case QStyleOptionHeader::SortDown:
            oSortPixmap = QIcon(":/shared/drop_up_grey").pixmap(10,10);
            break;
        case QStyleOptionHeader::SortUp:
            oSortPixmap = QIcon(":/shared/drop_down_grey").pixmap(10,10);
            break;
        }

        if(!oSortPixmap.isNull()){
            QRect oSortRect = QRect(oTextRect.left() + oTextRect.width(), oRect.top() + (oRect.height() - oSortPixmap.height())/2,
                                    oSortPixmap.width(), oSortPixmap.height());
            poPainter->drawPixmap(oSortRect, oSortPixmap); // Draw sortIcon
        }
        return;
    }
    QProxyStyle::drawControl(oCtrElement, poStyleOptionption, poPainter, poWidget);
}


问:
How to check if activity is in foreground or in visible background?
I have a splash screen on a timer. My problem is that before I finish() my activity I need to check that the next activity has started because a system dialogue box pops-up and I only want to finish(); once the user has selected an option from the dialogue box?

I know that there are many questions on how to see if your activity is in the foreground but I do not know if this allows for dialogue boxes on top of the activity too.

Here is the problem, the red is my activity which is in the background while the dialogue is in the foreground:

EDIT: I have tried just not using finish() but then my activity can be gone back to in the stack of applications which I am trying to avoid.

答:
Would Activity.onWindowFocusChanged(boolean hasFocus) be useful here? That, plus a class-level flag, something like isFocused that onWindowFocusChanged sets, would be an easy way to tell at any point in your activity if it is focused or not. From reading the docs, it looks like it would properly set "false" in any situation where the activity isn't directly in the physical "foreground", like if a dialog is being displayed or the notification tray is pulled down.

Example:

```<code>boolean isFocused;
@Override
void onWindowFocusChanged (boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    isFocused = hasFocus;
}

void someMethod() {
    if (isFocused) {
        // The activity is the foremost object on the screen
    } else {
        // The activity is obscured or otherwise not visible
    }
}
</code>```

Body:
Would Activity.onWindowFocusChanged(boolean hasFocus) be useful here? That, plus a class-level flag, something like isFocused that onWindowFocusChanged sets, would be an easy way to tell at any point in your activity if it is focused or not. From reading the docs, it looks like it would properly set "false" in any situation where the activity isn't directly in the physical "foreground", like if a dialog is being displayed or the notification tray is pulled down.

Example:

boolean isFocused;
@Override
void onWindowFocusChanged (boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    isFocused = hasFocus;
}

void someMethod() {
    if (isFocused) {
        // The activity is the foremost object on the screen
    } else {
        // The activity is obscured or otherwise not visible
    }
}


问:
Can't set size of image. Disappears from DIV border
I have a question about image positioning and sizing in DIV.
I have an image that I use in a specific DIV and I need it to cover the whole topside of the DIV. When I zoom-in the scale of the browser, instead of shrinking in the DIV, the image disappears and overflows from the right side of the DIV.
Also when I zoom-out the scale, the image is being cut-off from the bottom. I know the problem is with the Height, but I do not know how to fix it.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main {
  background-image: url("upper_title.png");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main_body">
  <div class="upper_main">
  </div>
</div></code>```

EXAMPLE:

答:
Flexbox is life, Flexbox is our savior.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 10px;
  max-width: 78.3%;
  height: 500px;
  box-shadow: 0px 0px 15px 0px rgba(50,50,50,0.87);
  display: flex;
  flex-direction: column;
}
.upper_main {
  background-image: url("http://lorempixel.com/1000/100/sports/");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}
.down {
  outline: red dashed 2px;
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main_body">
  <div class="upper_main"></div>
 <div class="down"></div>
</div></code>```

Body:
I have a question about image positioning and sizing in DIV.
I have an image that I use in a specific DIV and I need it to cover the whole topside of the DIV. When I zoom-in the scale of the browser, instead of shrinking in the DIV, the image disappears and overflows from the right side of the DIV.
Also when I zoom-out the scale, the image is being cut-off from the bottom. I know the problem is with the Height, but I do not know how to fix it.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 150px;
  max-width: 78.3%;
  height: 500px;
  -webkit-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  -moz-box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
  box-shadow: 0px 0px 15px 0px rgba(50, 50, 50, 0.87);
}

.upper_main {
  background-image: url("upper_title.png");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}

EXAMPLE:

Body:
Flexbox is life, Flexbox is our savior.

.main_body {
  background-color: white;
  margin: auto;
  margin-top: 10px;
  max-width: 78.3%;
  height: 500px;
  box-shadow: 0px 0px 15px 0px rgba(50,50,50,0.87);
  display: flex;
  flex-direction: column;
}
.upper_main {
  background-image: url("http://lorempixel.com/1000/100/sports/");
  background-repeat: no-repeat;
  background-size: cover;
  height: 8%;
}
.down {
  outline: red dashed 2px;
  flex-grow: 1;
}

<div class="main_body">
  <div class="upper_main"></div>
 <div class="down"></div>
</div>