问:
stackoverflow exception was unhandled
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

```<code>        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }
</code>```

答:
In a nutshell you have a potential (varying on input) case of:

```<code>function bigzarb()
{
    bigzarb()
}
</code>```

so long as the numbers in textBox7 are > 3, i.e. an unclosed recursion loop, which will inevitably become a stackoverflow.

Put a breakpoint on the line in question and you'll quickly see the problem. Without knowing what your method does (I don't recognise the algorithm) I can't help much about cleaning it up, but the first step might be to have a get out clause to return from the function conditionally. However, I also see you overwriting the input arguments u and v before they get used so perhaps you've made a mistake in the algo?

Title: stackoverflow exception was unhandled

Body:
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }

Body:
In a nutshell you have a potential (varying on input) case of:

function bigzarb()
{
    bigzarb()
}

so long as the numbers in textBox7 are > 3, i.e. an unclosed recursion loop, which will inevitably become a stackoverflow.

Put a breakpoint on the line in question and you'll quickly see the problem. Without knowing what your method does (I don't recognise the algorithm) I can't help much about cleaning it up, but the first step might be to have a get out clause to return from the function conditionally. However, I also see you overwriting the input arguments u and v before they get used so perhaps you've made a mistake in the algo?


来源: stackexchange

问:
Android Studio's Android emulator will not start.
After installing Android Studio, I initially started it up to see how it works. It started up like normal, and I closed it. After starting a react native project and trying to open it with react-native run-android , I am told to have an Android device running first, so I go back to android studio to open the emulator, and when I launch an emulator, a bar in Android Studio will fill up like so.

However, when the bar fills up all the way, nothing happens. I've made sure I have the proper folders in the System variables as ANDROID_HOME, the emulator ran once before, so what's the deal? I even tried deleting the virtual device and creating a new one, and uninstalling and reinstalling the emulator part of the Studio program. Also I opened up a new project in Android Studio and had it run using my AVD. After having the "Starting AVD" bar fill up, I get a bar saying that Studio is waiting for the device to start up, infinitely.

Nothing else on the Internet is helping, and I can't launch it from the command line because emulator is not being recognized as a command despite me triple checking the correct folders are in the path. Any ideas what is causing this? I am running Windows 10.

答:
This helped me:
1. Open AVD for editing
2. "Graphisc: Automatic" change to "Hardware - ..."</p>

ContentLicense: CC BY-SA 3.0


问:
Angular 2 Routes to show confirmation screen without compoent?
I have the UX design in my project like suppose I have a Register page, so I have made a Register component with its html and css and given a state 'localhost:8080/register' i.e. '/register'as a route.
On successfull registeration I want to display a different HTML template for register with some route stats as "/register/done" but here I donot want to make any new component, So is it possible to create a route without component.
The second approach is I can replace the HTML template in the current component to show the successfull registration confirmation screen. So is it possible to change the HTML template dynamically or not. As I am using webpack, it is not possible I think.

If there is any other solution to show these two related routes with different HTML template and route then please share it here.

Thanks in advance!!

答:
```<code>I have solved it like you say but with optimized ngIf else in Angular 4. like following-

<div class="parent-div">
  <div class="signup-center " *ngIf="!signUpDone; else confirm">
      <div>Signup with emailid>
          ....Signup screen.....
      </div>
  </div>
  <ng-template #confirm>
     <div>Congratulations!! You have successfully created your account</div>
  </ng-template>
</div>
</code>```


问:
javascript auto refresh div without refreshing the whole page
```<code><script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
  $(document).ready(function() {
    var refreshId = setInterval(function() {
      $("#curl-refresh").load('test-xml.php');
    }, 30000);
    $.ajaxSetup({ cache: false });
  });
</script>
</code>```

I am trying to refresh the div content without refreshing the whole page. I'm getting the desired output, but the browser hangs after some time.

I have seen similar questions, but none of them helped me. Please help me out

My question is similar to this:
Auto refresh div causing browser to hang

答:
Sometimes you can't prevent browser from caching in that case you can use some url query random parameter to prevent caching to be happen. some like :

```<code>var url = "test-xml.php?" + Math.random();
</code>```

or

```<code>var url = "test-xml.php?" + new Date().getTime();
</code>```

Body:
Sometimes you can't prevent browser from caching in that case you can use some url query random parameter to prevent caching to be happen. some like :

var url = "test-xml.php?" + Math.random();

or

var url = "test-xml.php?" + new Date().getTime();


问:
If Cycle in R Shiny
I am trying to write a simple If Cycle in R Shiny but I am founding some issues. I want to create a variable, in this case m, according to what the user inputs. Here there is the code:

```<code>if(input$city=="Enter Text..."){

 m<-reactive({leaflet() %>%
  addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
  addPolylines(data = trips(),
               lng = ~V1,
               lat = ~V2,weight=1,color="purple") %>%
addCircles(lng = geocode(input$city)$lon, lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city, color="blue",fillOpacity = 0)
})

} else {

m<-reactive({leaflet() %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1,
                 lat = ~V2,weight=1,color="purple")
})
}
</code>```

In doing this I get an error that says that I am trying to do something outside a reactive environment, but the variable m is defined as reactive. How can I fix this?

Thanks

答:
input$city is indeed a reactive element which needs to be use in a reactive environment.
Just add the if statement inside of your reactive() function. And it will make the code clearer since the beginning of the leaflet construction is the same.

```<code> m<-reactive({leaflet() %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1,
                 lat = ~V2,weight=1,color="purple") %>%
    {if(input$city=="Enter Text..."){
          addCircles(., lng = geocode(input$city)$lon,
          lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city,
          color="blue",fillOpacity = 0)
     } else {.}
    }
})
</code>```

By using addCircles(.,, you get the chaining into the if statement and with else {.}, you just return the previous element, without adding the addCircles function.

Title: If Cycle in R Shiny

Body:
I am trying to write a simple If Cycle in R Shiny but I am founding some issues. I want to create a variable, in this case m, according to what the user inputs. Here there is the code:

if(input$city=="Enter Text..."){

 m<-reactive({leaflet() %>%
  addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
  addPolylines(data = trips(),
               lng = ~V1,
               lat = ~V2,weight=1,color="purple") %>%
addCircles(lng = geocode(input$city)$lon, lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city, color="blue",fillOpacity = 0)
})

} else {

m<-reactive({leaflet() %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1,
                 lat = ~V2,weight=1,color="purple")
})
}

In doing this I get an error that says that I am trying to do something outside a reactive environment, but the variable m is defined as reactive. How can I fix this?

Thanks

Body:
input$city is indeed a reactive element which needs to be use in a reactive environment.
Just add the if statement inside of your reactive() function. And it will make the code clearer since the beginning of the leaflet construction is the same.

 m<-reactive({leaflet() %>%
    addProviderTiles(providers$OpenStreetMap.BlackAndWhite) %>%
    addPolylines(data = trips(),
                 lng = ~V1,
                 lat = ~V2,weight=1,color="purple") %>%
    {if(input$city=="Enter Text..."){
          addCircles(., lng = geocode(input$city)$lon,
          lat = geocode(input$city)$lat, weight = 5,
          radius =input$radius, popup = input$city,
          color="blue",fillOpacity = 0)
     } else {.}
    }
})

By using addCircles(.,, you get the chaining into the if statement and with else {.}, you just return the previous element, without adding the addCircles function.


问:
How to select from whereIn clause using Laravel Eloquent ORM or Query Builder?
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

```<code>SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)
</code>```

Laravel Query (It's not working) -

```<code>Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();
</code>```

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

答:
You can use ->toArray() on that object to convert it to an array so that the IN clause works properly:

```<code>Users::where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id',
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()->toArray()
        )->get();
</code>```

Body:
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)

Laravel Query (It's not working) -

Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

Body:
You can use ->toArray() on that object to convert it to an array so that the IN clause works properly:

Users::where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id',
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()->toArray()
        )->get();


问:
Automated string insertion on windows
Normally I'm a mac person, but at my new job I'm finding myself using a PC. I often have to open html files and for every href link insert a target blank argument. Rather then do this manually I was wondering if there was a script that I could use to automate the process. Say:

search for href

find the second double quotation after the href string

insert the string "target = _blank"

Mind you I have never used a shell script on a PC in my life, so much explanation might be needed here.

Thanks,

答: I use Groovy for those kind of tasks.  Good thing with Groovy (as well as with other famous scripting languages), someone might have already done the task you want to accomplish.  In your case, I found this article.  It demonstrates a similar case you mentioned (Search and Replace).</p>

ContentLicense: CC BY-SA 2.5

Title: Automated string insertion on windows


问:
How to Get Array Inside stdClass
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

```<code><?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "```";
print_r($data);
echo "```";
?>
</code>```

i want to get all "statusdesc" Values after decode.
I am getting results something like this

```<code>stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)
</code>```

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.

答:
```<code>$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
</code>```

this should return you array of object(stdClass)

```<code>$elm = json_decode( $json );
var_dump( $elm->posts );
</code>```

you can get one of your string in this way:

```<code>$elm->posts[5]->statusdesc
</code>```

or you can convert your json into array using json_decode( $json, true )

NOTE: json_decode can't remember your original class as serialize it always return stdClass (you can access to properties but not to the methods of the original class)

Title: How to Get Array Inside stdClass

Body:
I am trying to decode with json
http://digitsolutions4u.com/apps_services/statuslist.php?catid=1
like this

<?php
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "
";
print_r($data);
echo "
";
?>

i want to get all "statusdesc" Values after decode.
I am getting results something like this

stdClass Object
(
    [posts] => Array
        (
            [0] => stdClass Object
                (
                    [statusid] => 1329
                    [statusdesc] => love86.jpg
                )
)
)

i just want to list out all statusdesc available on the page like
love86.jpg
love87.jpg
love88.jpg
and so on. Anyone can provide me solution(code)  for this? I have tried several threads, but no success.

Body:
$json_url = "http://digitsolutions4u.com/apps_services/statuslist.php?catid=1";
$json = file_get_contents($json_url);

this should return you array of object(stdClass)

$elm = json_decode( $json );
var_dump( $elm->posts );

you can get one of your string in this way:

$elm->posts[5]->statusdesc

or you can convert your json into array using json_decode( $json, true )

NOTE: json_decode can't remember your original class as serialize it always return stdClass (you can access to properties but not to the methods of the original class)


问:
Reverse Regex Selection with Spring MongoDB
I have a mongo collection with objects like these:

```<code>[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]
</code>```

Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).

Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.

Thinking about something like this, with regex, but I'm not sure how should it look like:

```<code>Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );
</code>```

答:
You actually want a "reverse regex" here, as you need to use the data in the document in order to match on another field.

Presently you can really only do this with MongoDB using $where, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery instead, so we can construct from BasicDBObject and Code primatives:

```<code>    BasicDBObject basicDBObject = new BasicDBObject("$where",
            new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));

    BasicQuery query = new BasicQuery(basicDBObject);
</code>```

That will test the "id" field in the document to see if it matches the value from entityType at the "end of the string" and without considering "case". The ! is a Not condition, so the "reverse" of the logic is applied to "not match" where the field actually did end that way.

Body:
I have a mongo collection with objects like these:

[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]

Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).

Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.

Thinking about something like this, with regex, but I'm not sure how should it look like:

Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );

Body:
You actually want a "reverse regex" here, as you need to use the data in the document in order to match on another field.

Presently you can really only do this with MongoDB using $where, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery instead, so we can construct from BasicDBObject and Code primatives:

    BasicDBObject basicDBObject = new BasicDBObject("$where",
            new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));

    BasicQuery query = new BasicQuery(basicDBObject);

That will test the "id" field in the document to see if it matches the value from entityType at the "end of the string" and without considering "case". The ! is a Not condition, so the "reverse" of the logic is applied to "not match" where the field actually did end that way.


问:
Element of 2D matrix in Python
I have the following Python code to display the matrix element, but it does not show what is expected as I want to show the first element instead of first line elements. What is the problem?</p>

```<code>import numpy as np

ss = [-0.115, -0.052, 0.559, -0.344, 0.077, 0.032, -0.017, -0.035]
sx = np.matrix([[ss[0],ss[1],ss[2],ss[3]],[ss[4],ss[5],ss[6],ss[7]]])

print('s0=', sx[0])
print('s00=', sx[0][0])
</code>```

答:
For accessing a first row in an 2d array

```<code>print('s0=', sx[0,:]))  # replace zero with row you want to access
</code>```

And to access first element.

```<code>print('s00=', sx.item(0,0)) # replace 0,0 with the position of element
</code>```

For documentation refer

Title: Element of 2D matrix in Python

Body:
I have the following Python code to display the matrix element, but it does not show what is expected as I want to show the first element instead of first line elements. What is the problem?

import numpy as np

ss = [-0.115, -0.052, 0.559, -0.344, 0.077, 0.032, -0.017, -0.035]
sx = np.matrix([[ss[0],ss[1],ss[2],ss[3]],[ss[4],ss[5],ss[6],ss[7]]])

print('s0=', sx[0])
print('s00=', sx[0][0])

Body:
For accessing a first row in an 2d array

print('s0=', sx[0,:]))  # replace zero with row you want to access

And to access first element.

print('s00=', sx.item(0,0)) # replace 0,0 with the position of element

For documentation refer


问:
Python for starters - TypeError: '<' not supported between instances of 'str' and 'int'
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

```<code>print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')
</code>```

答:
Your input is a string, and you need to convert it to an int to use comparison operator.

Instead of :

```<code>print('how old are you?')
myAge = input()
</code>```

Try this:

```<code>myAge = int(input('How old are you?')
</code>```

Body:
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')

Body:
Your input is a string, and you need to convert it to an int to use comparison operator.

Instead of :

print('how old are you?')
myAge = input()

Try this:

myAge = int(input('How old are you?')


问:
Change only color when changing Theme
I want to support different themes in my android application.
The themes should only differ in two colors. So there are these colors for every theme:

Primary Color

Secondary Color

What I want is, that there is one big default theme, that also has children like button styles et, like this (styles.xml):

```<code><style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="homeAsUpIndicator">@drawable/my_stackoverflow_arrow</item>
    [...]
</style>

<style name="DefaultTheme.NoActionBar">
    <!-- hide action bar and title -->
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="DefaultTheme.Button">
    <item name="android:textAllCaps">true</item>
    <item name="android:textStyle">bold</item>
    [...]
</style>
</code>```

But now I also want to change themes for different colors. Therefore, I have created a resource in the attrs.xml file:

```<code><resources>
    <attr name="ThemeColorPrimary" format="reference" />
    <attr name="ThemeColorSecondary" format="reference" />
</resources>
</code>```

So now I can use this attribute in my styles.xml from above like this:

```<code><style name="DefaultTheme.Button">
    <item name="android:textAllCaps">true</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">?attr/ThemeColorPrimary</item>
    [...]
</style>
</code>```

But how do I create my colored themes? I know I need to do something like this:

```<code><item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
</code>```

But where? And which theme inherits from which? If I now have something like:

```<code><style name="BlueTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlueSecondary</item>
</style>

<style name="GreyTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeGreyPrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeGreySecondary</item>
</style>

<style name="BlackTheme" parent="DefaultTheme">
    <item name="ThemeColorPrimary">@color/ThemeBlackPrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlackSecondary</item>
</style>
</code>```

I can't specify in AndroidManifest.xml the theme like this:

```<code><activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/DefaultTheme.NoActionBar" />
</code>```

Because the specified resources would be missing. Otherwise I also can't to this:

```<code><activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/BlueTheme.NoActionBar" />
</code>```

because BlueTheme has no Child that is called "NoActionBar".

I know this is confusing, I am pretty confused myself.
How can I solve this?
Thank you in advance.

答:
You have to specify those custom attributes in the parent theme:

```<code><style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="ThemeColorPrimary">@color/defaultPrimaryColor</item>
    <item name="ThemeColorSecondary">@color/defaultSecondaryColor</item>
</style>
</code>```

Then each children of DefaultTheme would have access to your custom attributes and also can override those.

If you want to combine NoActionBar and BlueTheme, then you have to subclass NoActionBar theme:

```<code><style name="BlueNoActionBarTheme" parent="DefaultTheme.NoActionBar">
    <item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlueSecondary</item>
</style>
</code>```

Title: Change only color when changing Theme

Body:
I want to support different themes in my android application.
The themes should only differ in two colors. So there are these colors for every theme:

Primary Color

Secondary Color

What I want is, that there is one big default theme, that also has children like button styles et, like this (styles.xml):

But now I also want to change themes for different colors. Therefore, I have created a resource in the attrs.xml file:

<resources>
    <attr name="ThemeColorPrimary" format="reference" />
    <attr name="ThemeColorSecondary" format="reference" />
</resources>

So now I can use this attribute in my styles.xml from above like this:

But how do I create my colored themes? I know I need to do something like this:

<item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>

But where? And which theme inherits from which? If I now have something like:

I can't specify in AndroidManifest.xml the theme like this:

<activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/DefaultTheme.NoActionBar" />

Because the specified resources would be missing. Otherwise I also can't to this:

<activity
    android:name="StackOverflowActivity"
    android:screenOrientation="portrait"
    android:theme="@style/BlueTheme.NoActionBar" />

because BlueTheme has no Child that is called "NoActionBar".

I know this is confusing, I am pretty confused myself.
How can I solve this?
Thank you in advance.

Body:
You have to specify those custom attributes in the parent theme:

<style name="DefaultTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="ThemeColorPrimary">@color/defaultPrimaryColor</item>
    <item name="ThemeColorSecondary">@color/defaultSecondaryColor</item>
</style>

Then each children of DefaultTheme would have access to your custom attributes and also can override those.

If you want to combine NoActionBar and BlueTheme, then you have to subclass NoActionBar theme:

<style name="BlueNoActionBarTheme" parent="DefaultTheme.NoActionBar">
    <item name="ThemeColorPrimary">@color/ThemeBluePrimary</item>
    <item name="ThemeColorSecondary">@color/ThemeBlueSecondary</item>
</style>


问:
Can Xtext Language Server support multiple clients?
Can Xtext LSP server by used as dls as a service? Where all files are stored on server (remote location) and handle multiple connections from different clients in the same time?

If yes any suggestions how to implement this will be very much appreciated.

答:
The basic assumption of the Language Server Protocol is that both the client and the server have access to the same set of files. Therefore LSP is not designed to work in a real client-server scenario. The serving of files to clients would have to be implemented with a separate service, or as an extension of LSP.

If you're looking for a web client solution, you could have a look at Monaco editor. It could be a good basis for implementing such a file service.


问:
How To redirect after i loggin to curl script
```<code><?php
$username = "";
$password = "";
$url = "https://wordpress.com/wp-login.php";
$cookie = dirname(__FILE__)."/cookie.txt";

$postdata = "log=".$username."&pwd=".$password."&rememberme=forever&wp-submit=Log+In&redirect_to=https%3A%2F%2Fwordpress.com%2F&testcookie=1
";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, "https://wordpress.com/wp-login.php?redirect_to=https%3A%2F%2Fwordpress.com%2F");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);

$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {

    {

    curl_setopt($ch, CURLOPT_POST, 1); // change back to GET
    curl_setopt($ch, CURLOPT_URL, 'https://wordpress.com/me'); // set url for next request

    $exec = curl_exec($ch); // make request to buy on the same handle with the current login session
}
}
curl_close($ch);
unset($ch);
?>
</code>```

<p>i want to be redirected to a new url after i login successfully to curl script (https://wordpress.com/me). am getting nothing on the screen after i run the code on a localhost. also i am not able to view anything on the browser but the cookies are been inserted to cookie.txt file </p>

答:
How about this, or have i missunderstood the question?:

```<code>header("Location: http://newurl.com");
exit();
</code>```

If you are interested in doing some chain requests with curl, try investigating the responses on this question: Keeping session alive with Curl and PHP

Body:
<?php
$username = "";
$password = "";
$url = "https://wordpress.com/wp-login.php";
$cookie = dirname(__FILE__)."/cookie.txt";

$postdata = "log=".$username."&pwd=".$password."&rememberme=forever&wp-submit=Log+In&redirect_to=https%3A%2F%2Fwordpress.com%2F&testcookie=1
";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, "https://wordpress.com/wp-login.php?redirect_to=https%3A%2F%2Fwordpress.com%2F");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);

$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {

    {

    curl_setopt($ch, CURLOPT_POST, 1); // change back to GET
    curl_setopt($ch, CURLOPT_URL, 'https://wordpress.com/me'); // set url for next request

    $exec = curl_exec($ch); // make request to buy on the same handle with the current login session
}
}
curl_close($ch);
unset($ch);
?>

i want to be redirected to a new url after i login successfully to curl script (https://wordpress.com/me). am getting nothing on the screen after i run the code on a localhost. also i am not able to view anything on the browser but the cookies are been inserted to cookie.txt file

Body:
How about this, or have i missunderstood the question?:

header("Location: http://newurl.com");
exit();

If you are interested in doing some chain requests with curl, try investigating the responses on this question: Keeping session alive with Curl and PHP


问:
How can I overwrite the entire document, instead of just updating the fields?
How can I overwrite the entire document, instead of just updating the fields?
Here is the method I use right now but doesn't work:

```<code>updateFilmTitle: function(req, res) {
    var id = req.params.id;
    console.log(id);
    filmTitleModel.findByIdAndUpdate(id, req.body, {
        overwrite: true
    }, {
        new: true
    }, (error, response) => {
        if (error) {
            res.json(error);
            console.error(error);
            return;
        }
        console.log("filmTitle form has been updated!");
        res.json(response);
        console.log(response);
    });
},
</code>```

here how my model looks like,

```<code>var venueSchema = new Schema({
    ticketServiceRequired: { type: Boolean, required: true },
    filmSettings: {
        type: {
            filmContactName: { type: String, required: true },
            filmSeatingAmount: { type: Number, required: true },
            filmMediaDelivery: { type: Array, required: true },
            filmRentalFee: {
                price: { type: Number, required: true },
                type: { type: String, required: true },
            },
        }
    },

 });
</code>```

答:
new and overwrite both are options, so it should be this:

```<code>filmTitleModel.findByIdAndUpdate(id, req.body, {
  overwrite : true,
  new       : true
}, (error, response) => { ... });
</code>```

Body:
How can I overwrite the entire document, instead of just updating the fields?
Here is the method I use right now but doesn't work:

updateFilmTitle: function(req, res) {
    var id = req.params.id;
    console.log(id);
    filmTitleModel.findByIdAndUpdate(id, req.body, {
        overwrite: true
    }, {
        new: true
    }, (error, response) => {
        if (error) {
            res.json(error);
            console.error(error);
            return;
        }
        console.log("filmTitle form has been updated!");
        res.json(response);
        console.log(response);
    });
},

here how my model looks like,

var venueSchema = new Schema({
    ticketServiceRequired: { type: Boolean, required: true },
    filmSettings: {
        type: {
            filmContactName: { type: String, required: true },
            filmSeatingAmount: { type: Number, required: true },
            filmMediaDelivery: { type: Array, required: true },
            filmRentalFee: {
                price: { type: Number, required: true },
                type: { type: String, required: true },
            },
        }
    },

 });

Body:
new and overwrite both are options, so it should be this:

filmTitleModel.findByIdAndUpdate(id, req.body, {
  overwrite : true,
  new       : true
}, (error, response) => { ... });


问:
How to create bean by double reference?
I do not know how to articulate/search the issue in the first place.

So the bean initialized are :

```<code><bean id='domain' factory-bean='appConfig' factory-method='getDomain'/
<bean id='prod' class='java.lang.String'> <constructor-arg value='Base.Prod'/> </bean>
<bean id='test' class='java.lang.String'> <constructor-arg value='Base.Beta' /> </bean>
</code>```

Now I need to create a bean "X" using the value of Prod or Test depending on the value of domain. If domain is Prod,use the bean of Prod to initialize bean X else use Test.

${${domain}} does not work. I tried searching but was not able to find a question that meant this.

答:
This will work

```<code>@Value("${domain}")
private String domain;
</code>```

Combined with

```<code>-Ddomain=dev
</code>```

Spring adds any system properties to properties read from properties file.

Title: How to create bean by double reference?

Body:
I do not know how to articulate/search the issue in the first place.

So the bean initialized are :

<bean id='domain' factory-bean='appConfig' factory-method='getDomain'/
<bean id='prod' class='java.lang.String'> <constructor-arg value='Base.Prod'/> </bean>
<bean id='test' class='java.lang.String'> <constructor-arg value='Base.Beta' /> </bean>

Now I need to create a bean "X" using the value of Prod or Test depending on the value of domain. If domain is Prod,use the bean of Prod to initialize bean X else use Test.

${${domain}} does not work. I tried searching but was not able to find a question that meant this.

Body:
This will work

@Value("${domain}")
private String domain;

Combined with

-Ddomain=dev

Spring adds any system properties to properties read from properties file.


问:
R errorbar and polygon with ggplot
I have a problem using polygon with ggplot. I plot some model predictions and observations (mean and confidence level), and I want to plot a polygon for my observation's confidence level. Here is my data

```<code>Mat_ic_mu=matrix(c(-3.347582, -3.297287, -3.333237, -3.206484, -3.313200,
-3.313200,-3.313200,-3.313200,-3.355346, -3.315213, -3.354656, -3.252734,
-3.328607, -3.328607, -3.328607, -3.328607,-3.363109, -3.333138,
-3.376076, -3.298983, -3.344014, -3.344014, -3.344014,
-3.344014),ncol=3,nrow=8)

modelName=c("model 1","model 2","model 3","model 0")
type=rep(c("Pred modèle", "Obs"), each = 4)
boxdata=data.frame(Mat_ic_mu,modelName,type)
colnames(boxdata)=c("icp","pred","icm","model","type")

ggplot(boxdata, aes(x = model, y = pred, ymax = icp, ymin = icm,
                    group = type, colour = type, shape = type)) +
  geom_errorbar(width=0.20) +
  geom_point() +
  scale_shape_manual(name="legend",values=c(19, 4)) +
  scale_color_manual(name="legend",values = c("orange","deepskyblue")) +
  xlab("modèles") +
  ylab("intervalle de confiance")+
  ggtitle(paste("Intervalle de confiance en ",end_year+1," pour ",Pays_a_predire," âge " , age_bp+start_age-1,sep=""))
</code>```

What I want is adding polygon for my Obs, but so long I couldn't figure out a way to add geom_polygon to my code.

The resulting figure is as follows:

but what I really want is something more like this :

using polygon to create the confidence level, with the mean in the middle

答:
Using geom_line and geom_ribbon, we need to subset the data to our layers:

```<code>ggplot(mapping = aes(x = model, y = pred, ymax = icp, ymin = icm)) +
  geom_ribbon(aes(group = 1), data = subset(boxdata, type == "Obs"), alpha = 0.2) +
  geom_line(aes(group = 1), data = subset(boxdata, type == "Obs")) +
  geom_errorbar(data = subset(boxdata, type == "Pred modèle"), width = 0.20) +
  geom_point(data = subset(boxdata, type == "Pred modèle"))
</code>```

Title: R errorbar and polygon with ggplot

Body:
I have a problem using polygon with ggplot. I plot some model predictions and observations (mean and confidence level), and I want to plot a polygon for my observation's confidence level. Here is my data

Mat_ic_mu=matrix(c(-3.347582, -3.297287, -3.333237, -3.206484, -3.313200,
-3.313200,-3.313200,-3.313200,-3.355346, -3.315213, -3.354656, -3.252734,
-3.328607, -3.328607, -3.328607, -3.328607,-3.363109, -3.333138,
-3.376076, -3.298983, -3.344014, -3.344014, -3.344014,
-3.344014),ncol=3,nrow=8)

modelName=c("model 1","model 2","model 3","model 0")
type=rep(c("Pred modèle", "Obs"), each = 4)
boxdata=data.frame(Mat_ic_mu,modelName,type)
colnames(boxdata)=c("icp","pred","icm","model","type")

ggplot(boxdata, aes(x = model, y = pred, ymax = icp, ymin = icm,
                    group = type, colour = type, shape = type)) +
  geom_errorbar(width=0.20) +
  geom_point() +
  scale_shape_manual(name="legend",values=c(19, 4)) +
  scale_color_manual(name="legend",values = c("orange","deepskyblue")) +
  xlab("modèles") +
  ylab("intervalle de confiance")+
  ggtitle(paste("Intervalle de confiance en ",end_year+1," pour ",Pays_a_predire," âge " , age_bp+start_age-1,sep=""))

What I want is adding polygon for my Obs, but so long I couldn't figure out a way to add geom_polygon to my code.

The resulting figure is as follows:

but what I really want is something more like this :

using polygon to create the confidence level, with the mean in the middle

Body:
Using geom_line and geom_ribbon, we need to subset the data to our layers:

ggplot(mapping = aes(x = model, y = pred, ymax = icp, ymin = icm)) +
  geom_ribbon(aes(group = 1), data = subset(boxdata, type == "Obs"), alpha = 0.2) +
  geom_line(aes(group = 1), data = subset(boxdata, type == "Obs")) +
  geom_errorbar(data = subset(boxdata, type == "Pred modèle"), width = 0.20) +
  geom_point(data = subset(boxdata, type == "Pred modèle"))


问:
How to get SUM of a column in PDO query
I am trying to get Summation of a column from my database table. But I get just 0.00. My codes are:

```<code>$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];
</code>```

It supposed to echo 306700.80. I've checked the query. It works fine in Database but not in my PHP script. What's wrong with it?

答:
edit: my explaining was wrong, i think. But is remains coming to do not reformat your date in the database.
That is: I suppose you store your date in columns of the type DATE/DATETIME</p>

```<code><?php
$total_income_query = $db->prepare("
    SELECT SUM(credit)
    from accounts
    WHERE date BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y')
               AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];
</code>```

Title: How to get SUM of a column in PDO query

Body:
I am trying to get Summation of a column from my database table. But I get just 0.00. My codes are:

$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];

It supposed to echo 306700.80. I've checked the query. It works fine in Database but not in my PHP script. What's wrong with it?

Body:
edit: my explaining was wrong, i think. But is remains coming to do not reformat your date in the database.
That is: I suppose you store your date in columns of the type DATE/DATETIME

<?php
$total_income_query = $db->prepare("
    SELECT SUM(credit)
    from accounts
    WHERE date BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y')
               AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];


问:
Get database last N data points from each node (Cloudant/couchdb)
TL;DR: MapReduce or POST request?

What is the correct(=most efficient) way to fetch the latest n data points of multiple sensors, from Cloudant or equivalent database?

Sensor data is stored in individual documents like this:

```<code>{
  "_id": "2d26dbd8e655ae02bdab611afc92b6cf",
  "_rev": "1-a64448521f05935b915e4bee12328e84",
  "date": "2017-06-20T15:59:50.509Z",
  "name": "Sensor01",
  "temperature": 24.5,
  "humidity": 45.3,
  "rssi": -33
}
</code>```

I want the fetch the latest 10 documents from sensor01-sensor99 so I can feed it to UI.

I have discovered few options:

1. Use map reduce function

Reduce each sensor data to array under sensor01, sensor02, etc...

E.g.
Map:

```<code>function (doc) {
  if (doc.name && doc.temperature) emit(doc.name, doc.temperature);
}
</code>```

Reduce:

```<code>function (keys, values, rereduce) {
  var temp_arr=[];

  for (i=0;i<values.length;i++)
  {
    temp_arr.push(values);
  }
  return temp_arr;
}
</code>```

I couldn't get this to work, but I think the method should be viable.

2. Multi-document fetching

```<code>{
"queries":[
{sensor01},{sensor02},{sensor03} etc....
]};
</code>```

Where each {sensor0x} is filtered using

```<code>{"startkey": [sensors[i],{}],"endkey": [sensors[i]],"limit": 5}
</code>```

This way I can order documents using ?descending=true
I implemented it and it works. I have my doubts should I use this if I have 1000 sensors with 10000 data points each.
And for hundreds of sensors I need to send a very large POST request.

Something better?

Is my architecture even correct?
Storing sensor data individual documents, and then fill the UI by fetching all data through REST API.

Thank you very much!

答:
There's nothing wrong with your method of storing one reading per document, but there's no truly efficient way of getting "the last n data points" for a number of sensors.

We could create a MapReduce function:

```<code>function (doc) {
  if (doc.name && doc.temperature && doc.date) {
    emit([doc.name, doc.date], doc.temperature);
  }
}
</code>```

This creates an indexed ordered on name and date.

We can access the most recent readings for a single sensor by querying the view:

```<code>/_design/mydesigndoc/_view/myview?startkey=["Sensor01","2020-01-01"]&descending=true&limit=10
</code>```

This fetches readings for "Sensor01" in newest-first order:

startkey & endkey are reveresed when doing descending=true

descending= true means in reverese order

limit - the number of readings required (or n in your parlance)

This is a very efficient use of Cloudant/CouchDB but it only returns the last n readings for single sensor. To retrieve other sensors' data, additional API calls would be required.

Creating an index like this:

```<code>function (doc) {
  if (doc.name && doc.temperature && doc.date) {
    emit(doc.date, doc.temperature);
  }
}
</code>```

orders each reading by date. You can then retrieve the newest n readings with:

```<code>/_design/mydesigndoc/_view/myview?startkey="2020-01-01"&descending=true&limit=200
</code>```

If all of your sensors are saving data at the same rate, then simply using a larger limit should get your the latest readings of all sensors.

This too is an efficient use of CouchDB/Cloudant.

You may also want to look at the built-in reducers (_count, _sum and _stats) to get the database to aggregate readings for you. They are a great way to create year/month/day groupings of IoT data.

In general, I would recommend not using custom reducers they are many times more inefficient than the built-in reducers which are written in Erlang.

Body:
TL;DR: MapReduce or POST request?

What is the correct(=most efficient) way to fetch the latest n data points of multiple sensors, from Cloudant or equivalent database?

Sensor data is stored in individual documents like this:

{
  "_id": "2d26dbd8e655ae02bdab611afc92b6cf",
  "_rev": "1-a64448521f05935b915e4bee12328e84",
  "date": "2017-06-20T15:59:50.509Z",
  "name": "Sensor01",
  "temperature": 24.5,
  "humidity": 45.3,
  "rssi": -33
}

I want the fetch the latest 10 documents from sensor01-sensor99 so I can feed it to UI.

I have discovered few options:

1. Use map reduce function

Reduce each sensor data to array under sensor01, sensor02, etc...

E.g.
Map:

function (doc) {
  if (doc.name && doc.temperature) emit(doc.name, doc.temperature);
}

Reduce:

function (keys, values, rereduce) {
  var temp_arr=[];

  for (i=0;i<values.length;i++)
  {
    temp_arr.push(values);
  }
  return temp_arr;
}

I couldn't get this to work, but I think the method should be viable.

2. Multi-document fetching

{
"queries":[
{sensor01},{sensor02},{sensor03} etc....
]};

Where each {sensor0x} is filtered using

{"startkey": [sensors[i],{}],"endkey": [sensors[i]],"limit": 5}

This way I can order documents using ?descending=true
I implemented it and it works. I have my doubts should I use this if I have 1000 sensors with 10000 data points each.
And for hundreds of sensors I need to send a very large POST request.

Something better?

Is my architecture even correct?
Storing sensor data individual documents, and then fill the UI by fetching all data through REST API.

Thank you very much!

Body:
There's nothing wrong with your method of storing one reading per document, but there's no truly efficient way of getting "the last n data points" for a number of sensors.

We could create a MapReduce function:

function (doc) {
  if (doc.name && doc.temperature && doc.date) {
    emit([doc.name, doc.date], doc.temperature);
  }
}

This creates an indexed ordered on name and date.

We can access the most recent readings for a single sensor by querying the view:

/_design/mydesigndoc/_view/myview?startkey=["Sensor01","2020-01-01"]&descending=true&limit=10

This fetches readings for "Sensor01" in newest-first order:

startkey & endkey are reveresed when doing descending=true

descending= true means in reverese order

limit - the number of readings required (or n in your parlance)

This is a very efficient use of Cloudant/CouchDB but it only returns the last n readings for single sensor. To retrieve other sensors' data, additional API calls would be required.

Creating an index like this:

function (doc) {
  if (doc.name && doc.temperature && doc.date) {
    emit(doc.date, doc.temperature);
  }
}

orders each reading by date. You can then retrieve the newest n readings with:

/_design/mydesigndoc/_view/myview?startkey="2020-01-01"&descending=true&limit=200

If all of your sensors are saving data at the same rate, then simply using a larger limit should get your the latest readings of all sensors.

This too is an efficient use of CouchDB/Cloudant.

You may also want to look at the built-in reducers (_count, _sum and _stats) to get the database to aggregate readings for you. They are a great way to create year/month/day groupings of IoT data.

In general, I would recommend not using custom reducers they are many times more inefficient than the built-in reducers which are written in Erlang.


问:
moment Uncaught TypeError: Cannot read property 'format' of undefined at time
I have this error for this line of code

```<code>var FullDate = moment(1499153561479).add(currentSeconds, 'seconds').tz(citiesT[id]).format("DD-MM-YYYY HH:mm:ss a");
</code>```

How can I fix it?

答:
You need to include moment-timezone library, CDN is http://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.1/moment-timezone-with-data-2010-2020.min.js and moment.min.js library, CDN is https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js

Then your code will work when you have all the variables defined like

```<code>currentSeconds = 10000;
var citiesT = ["America/Los_Angeles"];
var id= 0;
var FullDate = moment(1499153561479).add(currentSeconds, 'seconds').tz(citiesT[id]).format("DD-MM-YYYY HH:mm:ss a");
alert(FullDate);
</code>```

For you simplicity and work around here is the working link to JSFIDDLE

Body:
I have this error for this line of code

var FullDate = moment(1499153561479).add(currentSeconds, 'seconds').tz(citiesT[id]).format("DD-MM-YYYY HH:mm:ss a");

How can I fix it?

Body:
You need to include moment-timezone library, CDN is http://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.1/moment-timezone-with-data-2010-2020.min.js and moment.min.js library, CDN is https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js

Then your code will work when you have all the variables defined like

currentSeconds = 10000;
var citiesT = ["America/Los_Angeles"];
var id= 0;
var FullDate = moment(1499153561479).add(currentSeconds, 'seconds').tz(citiesT[id]).format("DD-MM-YYYY HH:mm:ss a");
alert(FullDate);

For you simplicity and work around here is the working link to JSFIDDLE


问:
Jquery How to automatically assign an ascending integer for each row starting from 1
Right now, when the rows no is entered and the button is clicked, respective no of rows will be added.

Now, i'd like to assign an ascending integer for each row starting from 1,
any idea guys?

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

    additionalRows = new Array(numNewRows + 0).join($row[0].outerHTML);

    $tbody.append(additionalRows);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>
    <tr>
      <td><input type="text" style="width: 100px" name="vaccineid[]"> </td>
      <td><input type="text" style="width: 160px" name="vaccinename1[]"></td>

    </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

答:
Do with while. They will help to iterate the value

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
var i =0;
  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

while(i<numNewRows){
    additionalRows =$row[0].outerHTML
    $tbody.append(additionalRows);
    i++;
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>
    <tr>
      <td><input type="text" style="width: 100px" name="vaccineid[]"> </td>
      <td><input type="text" style="width: 160px" name="vaccinename1[]"></td>

    </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

Body:
Right now, when the rows no is entered and the button is clicked, respective no of rows will be added.

Now, i'd like to assign an ascending integer for each row starting from 1,
any idea guys?

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

    additionalRows = new Array(numNewRows + 0).join($row[0].outerHTML);

    $tbody.append(additionalRows);
  }
});

<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>

      <input type="text" style="width: 100px" name="vaccineid[]">
      <input type="text" style="width: 160px" name="vaccinename1[]">

Body:
Do with while. They will help to iterate the value

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
var i =0;
  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

while(i<numNewRows){
    additionalRows =$row[0].outerHTML
    $tbody.append(additionalRows);
    i++;
    }
  }
});

<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>
    <tr>
      <td><input type="text" style="width: 100px" name="vaccineid[]"> </td>
      <td><input type="text" style="width: 160px" name="vaccinename1[]"></td>

    </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>


问:
How does the non executeable exploit work?
Hello the question is how works non executable exploit's, when i say non executable i mean those who don't have the file extension .exe, like word exploits .doc or other. How did they make some executable action if they are not compiled?</p>

答:
That varies from exploit to exploit.

While .doc isn't an executable format it does contain interpreted vba code which is generally where the malicious content was hidden.  When you opened the document there would be an onOpen event or some such fired which would execute the malicious payload.  Hence why most office installations have macro's disabled by default these days, far too much scope for abuse.

There are also plenty of things that will run on your system without being a .exe for example .com, .vbs, .hta

Then there are formats which have no normal executable content but can be attacked in other ways, usually taking advantage of poorly written routines to load the files which can allow things like buffer overflows


问:
How to create a IntentService to check if GoogleApiClient is not null android
In my project I'm using the "GoogleApiClient" to make locations requests each 5 seconds, the problem is, if I turn the GPS off and then reopen the App, it crushes because the mGoogleApiClient object is current null! I'm just doing a simple check on onRestart

```<code>protected void onRestart() {
    super.onRestart();
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected()){
        startLocationUpdate();
    }
}
</code>```

What I want is create something that I could call every time the object mGoogleApiClient is null so it could try in background until be fine to go on! Inside of  startLocationUpdate(); I'm using this :

```<code>mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(5000);
    mlocationRequest.setFastestInterval(2000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }
</code>```

It could be something like :

```<code>if(mGoogleApiClient != null){
   LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
  }else {
   callServiceToTryConnection();
}
</code>```

I already use IntentService with Geocoder to get the address!

答: put the handler in on connection suspended or connection failed  method that tries to check and re-connect if not null.</p>

Body:
In my project I'm using the "GoogleApiClient" to make locations requests each 5 seconds, the problem is, if I turn the GPS off and then reopen the App, it crushes because the mGoogleApiClient object is current null! I'm just doing a simple check on onRestart

protected void onRestart() {
    super.onRestart();
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected()){
        startLocationUpdate();
    }
}

What I want is create something that I could call every time the object mGoogleApiClient is null so it could try in background until be fine to go on! Inside of  startLocationUpdate(); I'm using this :

mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(5000);
    mlocationRequest.setFastestInterval(2000);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    try{
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
    }catch (SecurityException ex){
        Toast.makeText(this, ex.toString(), Toast.LENGTH_SHORT).show();
    }

It could be something like :

if(mGoogleApiClient != null){
   LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mlocationRequest,MainActivity.this);
  }else {
   callServiceToTryConnection();
}

I already use IntentService with Geocoder to get the address!


问:
How to replace missing with previous missing with in 7 days
Hi I have df as below which value column has NA value
        how to replace NA values previous values with in last 7 days . if non NA value not found in last 7 days then no replacement for eg: there is no values for 10-01-2016 in last 7 days with that day

```<code> Name   value   new_col
01-01-2016  NA     *NA*
02-01-2016  43
03-01-2016  NA     *43*
04-01-2016  NA     *43*
05-01-2016  NA     *43*
06-01-2016  NA     *43*
07-01-2016  NA     *43*
08-01-2016  NA     *43*
09-01-2016  NA     *43*
10-01-2016  NA     *NA*
11-01-2016  12
12-01-2016  33
13-01-2016  NA     *33*
14-01-2016  NA     *33*
</code>```

we can fill with NA previous valu using ZOO lib

df<- transform(df, value  = na.locf(value))

df$new_col = ifelse(is.na(df$value) & (df$Name-7), na.locf(df$value), df$value)

答:
You can use na.locf from zoo package, with argument maxgap:

(Note that we assume your data is arranged by date without missing holes in the serie)

```<code>library(zoo)
df$new_col <- na.locf(df$value, maxgap = 7, na.rm = FALSE)
</code>```

Body:
Hi I have df as below which value column has NA value
        how to replace NA values previous values with in last 7 days . if non NA value not found in last 7 days then no replacement for eg: there is no values for 10-01-2016 in last 7 days with that day

 Name   value   new_col
01-01-2016  NA     *NA*
02-01-2016  43
03-01-2016  NA     *43*
04-01-2016  NA     *43*
05-01-2016  NA     *43*
06-01-2016  NA     *43*
07-01-2016  NA     *43*
08-01-2016  NA     *43*
09-01-2016  NA     *43*
10-01-2016  NA     *NA*
11-01-2016  12
12-01-2016  33
13-01-2016  NA     *33*
14-01-2016  NA     *33*

we can fill with NA previous valu using ZOO lib

df<- transform(df, value  = na.locf(value))

df$new_col = ifelse(is.na(df$value) & (df$Name-7), na.locf(df$value), df$value)

Body:
You can use na.locf from zoo package, with argument maxgap:

(Note that we assume your data is arranged by date without missing holes in the serie)

library(zoo)
df$new_col <- na.locf(df$value, maxgap = 7, na.rm = FALSE)


问:
How to convert set of tags to belongness tuple ("multi-hot" encoding) in Python easy?
I have a set of tags tags and an ordered list of all possible tags taglist. Now I want to convert set of tags into "multi-hot" encoding, i.e. get a list or tuple with the same length as taglist and which has ones in places, where belonging tag resides and zeros in other placess.

Currently I do traightforward:

```<code>        multihot = []
        for i in range(len(taglist)):
            tag = taglist[i]
            if tag in tags:
                multihot.append(1)
            else:
                multihot.append(0)
</code>```

Is it possible to write one-liner?

答:
```<code>multihot = [(tag in tags) for tag in tag_list]
</code>```

multihot now contains entries of True or False. In Python, True behaves exactly the same as 1, and False as 0; so this is equivalent to your solution.

Body:
I have a set of tags tags and an ordered list of all possible tags taglist. Now I want to convert set of tags into "multi-hot" encoding, i.e. get a list or tuple with the same length as taglist and which has ones in places, where belonging tag resides and zeros in other placess.

Currently I do traightforward:

        multihot = []
        for i in range(len(taglist)):
            tag = taglist[i]
            if tag in tags:
                multihot.append(1)
            else:
                multihot.append(0)

Is it possible to write one-liner?

Body:
multihot = [(tag in tags) for tag in tag_list]

multihot now contains entries of True or False. In Python, True behaves exactly the same as 1, and False as 0; so this is equivalent to your solution.


问:
Why is a simple query on larger table much slower?
I run a simple update query on a table:

```<code>UPDATE table_x SET col_a = (col_b AT TIME ZONE 'UTC') AT TIME ZONE col_tz;
</code>```

When table_x consists of 100 entries, the query takes some milliseconds.

-> 100'000 entries = 2 seconds.

-> 1'000'000 entries = 20 seconds.

So far so good. But when the table consists of 20M entries, the query runs forever! Does anybody know the reason for this? And what can be done to overcome this?

Maybe I should add that I have only around 13 GB free disk space on my computer.

答:
It is the normal behaviour, that update performance degrades. The problem is, that the index needs to be updated after every update. If you import data into the database, you should use a batch feature of your database, which disables the index temporarily and rebuilds it afterwards.

Same for Sqlite for example: Sqlite appending data performance linear degradation, is this solvable?

Body:
I run a simple update query on a table:

UPDATE table_x SET col_a = (col_b AT TIME ZONE 'UTC') AT TIME ZONE col_tz;

When table_x consists of 100 entries, the query takes some milliseconds.

-> 100'000 entries = 2 seconds.

-> 1'000'000 entries = 20 seconds.

So far so good. But when the table consists of 20M entries, the query runs forever! Does anybody know the reason for this? And what can be done to overcome this?

Maybe I should add that I have only around 13 GB free disk space on my computer.


问:
How to adjust my code to this situation for SAX XML parsing in Android
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

```<code><Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>
</code>```

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

```<code>@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }
</code>```

So how must I adjust it?

答: The depth should not be a problem. I have more levels and the exact code works fine for me. Could it be that you have several nodes with the same name? "Name" in Personal, and "Name" in those insurances nodes?</p>

Body:
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

<Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

So how must I adjust it?


答:
You can reach it with list comprehension, adding condition whether tag is in tags, if yes, insert 1 else 0.</p>

```<code>multihot = [1 if tag in tags else 0 for tag in taglist]
</code>```

Title: How to convert set of tags to belongness tuple ("multi-hot" encoding) in Python easy?

Body:
You can reach it with list comprehension, adding condition whether tag is in tags, if yes, insert 1 else 0.

multihot = [1 if tag in tags else 0 for tag in taglist]


问:
How to take STDIN in Swift playground
I know that to program in STDIN and STDOUT, we need to make an command line project in Xcode.
But how do I take a standard input in playground.

Whenever I try to run such code in playground

```<code>var input = readLine()!
</code>```

I always get this error

Execution was interrupted, reason: EXC_BAD_INSTRUCTION
  (Code=EXC_l386_INVOP, subcode=0x0)

Is it possible to take STDIN in playground or not?

UPDATE

I know this error is because of nil input variable but want to know how to overcome this nil value.

答:
Fixed Solution for SWIFT 3

To make it work, Create a new command line tool project.

Go to "File" -> "New" -> "Project" -> "macOS" -> "Command Line Tool".

```<code>import Foundation

print("Hello, World!")

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

func input() -> String {
    let keyboard = FileHandle.standardInput
    let inputData = keyboard.availableData
    return NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

print("Addition of numbers is :  \(solveMefirst(firstNo: IntNum1!, secondNo: IntNum2!))")
</code>```

And run the project using CMD + R

Title: How to take STDIN in Swift playground

Body:
I know that to program in STDIN and STDOUT, we need to make an command line project in Xcode.
But how do I take a standard input in playground.

Whenever I try to run such code in playground

var input = readLine()!

I always get this error

Execution was interrupted, reason: EXC_BAD_INSTRUCTION
  (Code=EXC_l386_INVOP, subcode=0x0)

Is it possible to take STDIN in playground or not?

UPDATE

I know this error is because of nil input variable but want to know how to overcome this nil value.

Body:
Fixed Solution for SWIFT 3

To make it work, Create a new command line tool project.

Go to "File" -> "New" -> "Project" -> "macOS" -> "Command Line Tool".

import Foundation

print("Hello, World!")

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

func input() -> String {
    let keyboard = FileHandle.standardInput
    let inputData = keyboard.availableData
    return NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

print("Addition of numbers is :  \(solveMefirst(firstNo: IntNum1!, secondNo: IntNum2!))")

And run the project using CMD + R


问:
android webview displaying blank page
I have an android application that I am developing using the emulator running on android 2.3.3 with an embedded WebView in a framelayout nested in a linearlayout (vertical). No matter what code I use it never actually does anything. I have Permissions on the android application set to INTERNET.
Even when trying to load just the HTML code. I get a blank white page, no errors no nothing. Nothing in logcat as well.

```<code>WebView wview = (WebView)findViewById(R.id.webView1);
wview.getSettings().setJavaScriptEnabled(true);
</code>```

I have tried all three of these to attempt to load anything into the webview:

```<code>wview.loadUrl("http://www.google.com");
wview.loadData("<HTML><BODY><H3>Test</H3></BODY></HTML>","text/html","utf-8");
wview.loadDataWithBaseURL(null, "<HTML><BODY><H3>Test</H3></BODY></HTML>","text/html","utf-8",null);
</code>```

All three give me the same results. Nothing.

Any ideas?

答:
Try increasing the RAM for your emulated device. That solved the problem for me.

I found this out by looking at the logcat messages in Android Monitor (Android Studio). The messages below gave me the idea about what was wrong to increasing RAM :

```<code>W/art: Throwing OutOfMemoryError "Failed to allocate a 6635532 byte allocation with 1170528 free bytes and 1143KB until OOM"

W/JavaBrowserViewRendererHelper: Error allocating bitmap

E/chromium: [ERROR:java_browser_view_renderer_helper.cc(132)] Error unlocking java bitmap pixels.
</code>```

Title: android webview displaying blank page

Body:
I have an android application that I am developing using the emulator running on android 2.3.3 with an embedded WebView in a framelayout nested in a linearlayout (vertical). No matter what code I use it never actually does anything. I have Permissions on the android application set to INTERNET.
Even when trying to load just the HTML code. I get a blank white page, no errors no nothing. Nothing in logcat as well.

WebView wview = (WebView)findViewById(R.id.webView1);
wview.getSettings().setJavaScriptEnabled(true);

I have tried all three of these to attempt to load anything into the webview:

wview.loadUrl("http://www.google.com");
wview.loadData("
Test
","text/html","utf-8");
wview.loadDataWithBaseURL(null, "
Test
","text/html","utf-8",null);

All three give me the same results. Nothing.

Any ideas?

Body:
Try increasing the RAM for your emulated device. That solved the problem for me.

I found this out by looking at the logcat messages in Android Monitor (Android Studio). The messages below gave me the idea about what was wrong to increasing RAM :

W/art: Throwing OutOfMemoryError "Failed to allocate a 6635532 byte allocation with 1170528 free bytes and 1143KB until OOM"

W/JavaBrowserViewRendererHelper: Error allocating bitmap

E/chromium: [ERROR:java_browser_view_renderer_helper.cc(132)] Error unlocking java bitmap pixels.


问:
Is SceneKit's SCNMatrix4 stored as column or row-major?
The source of my confusion is the documentation on SCNMatrix4 from Apple:

SceneKit uses matrices to represent coordinate space transformations,
  which in turn can represent the combined position, rotation or
  orientation, and scale of an object in three-dimensional space.
  SceneKit matrix structures are in row-major order, so they are
  suitable for passing to shader programs or OpenGL APIs that accept matrix parameters.

This seems contradictory since OpenGL uses column-major transformation matrices!

In general the documentation of Apple on this topic is poor:

GLKMatrix4 does not talk about column vs. row major at all, but
I am certain from all discussions online that GLKMatrix is plain and
simple column-major.

simd_float4x4 does not talk about the
topic, but at least the variable names make it clear that it is
stored as columns:

From simd/float.h:

```<code>typedef struct { simd_float4 columns[4]; } simd_float4x4;
</code>```

Some discussion online about SCNMatrix4 talk as if SCNMatrix4 is different from GLKMatrix4, but looking at the code for SCNMatrix4 give some hints that it might just be column-order as expected:

```<code>/* Returns a transform that translates by '(tx, ty, tz)':
 * m' =  [1 0 0 0; 0 1 0 0; 0 0 1 0; tx ty tz 1]. */
NS_INLINE SCNMatrix4 SCNMatrix4MakeTranslation(float tx, float ty, float tz) {
    SCNMatrix4 m = SCNMatrix4Identity;
    m.m41 = tx;
    m.m42 = ty;
    m.m43 = tz;
    return m;
}
</code>```

So is SCNMatrix4 row-major (storing translations in m14, m24, m34) or column-major (storing translations in m41, m42, m43)?

答:
SCNMatrix4 stores the translation in m41, m42 and m43, as is GLKMatrix4. This little Playground confirms it as well as its definition.

```<code>import SceneKit

let translation = SCNMatrix4MakeTranslation(1, 2, 3)

translation.m41
// 1
translation.m42
// 2
translation.m43
// 3
</code>```

I have no idea why this is wrong in the documentation though, probably just a mistake.

Body:
The source of my confusion is the documentation on SCNMatrix4 from Apple:

SceneKit uses matrices to represent coordinate space transformations,
  which in turn can represent the combined position, rotation or
  orientation, and scale of an object in three-dimensional space.
  SceneKit matrix structures are in row-major order, so they are
  suitable for passing to shader programs or OpenGL APIs that accept matrix parameters.

This seems contradictory since OpenGL uses column-major transformation matrices!

In general the documentation of Apple on this topic is poor:

GLKMatrix4 does not talk about column vs. row major at all, but
I am certain from all discussions online that GLKMatrix is plain and
simple column-major.

simd_float4x4 does not talk about the
topic, but at least the variable names make it clear that it is
stored as columns:

From simd/float.h:

typedef struct { simd_float4 columns[4]; } simd_float4x4;

Some discussion online about SCNMatrix4 talk as if SCNMatrix4 is different from GLKMatrix4, but looking at the code for SCNMatrix4 give some hints that it might just be column-order as expected:

/* Returns a transform that translates by '(tx, ty, tz)':
 * m' =  [1 0 0 0; 0 1 0 0; 0 0 1 0; tx ty tz 1]. */
NS_INLINE SCNMatrix4 SCNMatrix4MakeTranslation(float tx, float ty, float tz) {
    SCNMatrix4 m = SCNMatrix4Identity;
    m.m41 = tx;
    m.m42 = ty;
    m.m43 = tz;
    return m;
}

So is SCNMatrix4 row-major (storing translations in m14, m24, m34) or column-major (storing translations in m41, m42, m43)?

Body:
SCNMatrix4 stores the translation in m41, m42 and m43, as is GLKMatrix4. This little Playground confirms it as well as its definition.

import SceneKit

let translation = SCNMatrix4MakeTranslation(1, 2, 3)

translation.m41
// 1
translation.m42
// 2
translation.m43
// 3

I have no idea why this is wrong in the documentation though, probably just a mistake.


问:
Retrieve relationship items from a collection
In a controller I create a collection with:

```<code>$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();
</code>```

and call my view with:

```<code>        return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));
</code>```

In my Team model I've:

```<code>    public function players(){
        return $this->belongsToMany(User::class, 'team_users');
}
</code>```

The collection is created:

But I don't know how to retrieve "players" item in my view.
I try with:

```<code>@foreach($playershome->players as $player)
</code>```

But I got:

```<code>Invalid argument supplied for foreach()
</code>```

What wrong?

UPDATE view:

```<code>                                            <div class="mt-body">
                                            <h3 class="mt-body-title"> {{$session->team1Id->name}} </h3>
                                            <p class="mt-body-description"> It is a long established fact that a reader will be distracted </p>
                                            <ul class="mt-body-stats">
                                                @foreach($playershome->players as $player)

                                                    <li class="font-green">
                                                        <img src="/storage/{{$player->avatar}}"></li>
                                                @endforeach
                                            </ul>
                                            <div class="mt-body-actions">
                                                <div class="btn-group btn-group btn-group-justified">
                                                    <a href="javascript:;" class="btn">
                                                        <i class="icon-bubbles"></i> Punti </a>
                                                    <a href="javascript:;" class="btn ">
                                                        <i class="icon-social-twitter"></i> K/D </a>
                                                </div>
                                            </div>
                                        </div>
</code>```

答:
Looking at your chat that you had in the comments I see that you are using the same name for an attribute called players in your teams table, and also the relation to the users is called players. Try renaming the relation to something else, change it in your query and also in your foreach.

EDIT: Found stackoverflow question to the same issue as you: Laravel get Eloquent relation by same name as its attribute

Body:
In a controller I create a collection with:

$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();

and call my view with:

        return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));

In my Team model I've:

    public function players(){
        return $this->belongsToMany(User::class, 'team_users');
}

The collection is created:

But I don't know how to retrieve "players" item in my view.
I try with:

@foreach($playershome->players as $player)

But I got:

Invalid argument supplied for foreach()

What wrong?

UPDATE view:

 {{$session->team1Id->name}}

 It is a long established fact that a reader will be distracted

                                                @foreach($playershome->players as $player)

                                                        avatar}}">

                                                @endforeach

                                                         Punti

                                                         K/D


问:
How to remove all but the last 3 parts of FQDN?
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

```<code>$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1
</code>```

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

答:
Version which uses only bash:

```<code>echo $(expr "$string" : '.*\.\(.*\..*\..*\)')
</code>```

To use it with a file you can iterate with xargs:

File:

```<code>head list.dat
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
98.254.34.56.broad.kkk.76onepi.co.cn
98.254.237.114.polst.a65dal.com.cn
</code>```

iterating the whole file:

```<code>cat list.dat | xargs -I^ -L1 expr "^" : '.*\.\(.*\..*\..*\)'
</code>```

Notice: it won't be very efficient in large scale, so you need to consider by your own whether it is good enough for you.

Regexp explanation:

```<code>.*  \.  \(  .*  \.  .*  \.  .*   \)
\___|    |       |       |        |
    |    \------------------------/> brakets shows which part we extract
    |            |       |
    |            \-------/> the \. indicates the dots to separate specific number of words
    |
    |
    -> the rest and the final dot which we are not interested in (out of brakets)
</code>```

details:
http://tldp.org/LDP/abs/html/string-manipulation.html -> Substring Extraction

Body:
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

Body:
Version which uses only bash:

echo $(expr "$string" : '.*\.\(.*\..*\..*\)')

To use it with a file you can iterate with xargs:

File:

head list.dat
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
98.254.34.56.broad.kkk.76onepi.co.cn
98.254.237.114.polst.a65dal.com.cn

iterating the whole file:

cat list.dat | xargs -I^ -L1 expr "^" : '.*\.\(.*\..*\..*\)'

Notice: it won't be very efficient in large scale, so you need to consider by your own whether it is good enough for you.

Regexp explanation:

.*  \.  \(  .*  \.  .*  \.  .*   \)
\___|    |       |       |        |
    |    \------------------------/> brakets shows which part we extract
    |            |       |
    |            \-------/> the \. indicates the dots to separate specific number of words
    |
    |
    -> the rest and the final dot which we are not interested in (out of brakets)

details:
http://tldp.org/LDP/abs/html/string-manipulation.html -> Substring Extraction


问:
Pentaho Spoon: Set SQL script result to value of new field
I currently have tried multiple ways (Execute SQL script, Table input, Database joins) to accomplish what I am trying to do. I need the sum and count respectively that my sql scripts below create to be put into a brand new field, or have these value be set as constants. I am trying to use each result in a calculator step later on in my transformation. Currently I have been trying to define fields using add constants and then played with the settings of the Execute SQL script (turning on or off variable substitution, putting the field name in the "Field to Contain Read stats"). But nothing has worked. If anyone knows of a good way to accomplish this it would greatly help! </p>

```<code>Select sum(days_in_hospital) days_in_hospital_sum from hospital_days
where unique_stay_id in
(select unique_stay_id from hospital_days group by unique_stay_id having COUNT(unique_stay_id)=1);

SELECT COUNT(DISTINCT member_id) as "Total_Employees" from Hospital_days
</code>```

答:
There are two handsome Group by step in the Statistic folder. I usually use the Memory Group by.

For your second question: Import data with an Input table with SELECT * FROM Hospital_day and direct the stream into a Memory Group By with no Group field, and one Aggregate named Total-Employees with an type of Number of Distinct Values, on the subject member_id.

For the first question: you ask to filter the unique_stay which appears once in hospital_days, and get the sum of days for those.

SELECT * FROM Hospital-day which you (Memory) Group by unique stay to get the Number_of_unique_stay. Then Filter out the row you want, that is the rows with a Filter Number_of_unique_stay=1. Then sum the days_in_hospital with a second (Memory) Group by.

At that point, you discover that this column was removed by the first Group by. Bogger! Open again this step! And try to add this column somewhere. You can add it on the Group field or to the Aggregates. But adding it to the group field will damage the count based on the unique_stay only. So you have to add day_in_hospital to the aggregates. And the aggregation is obviously a sum, since the sum of a sum is the sum (answer would be different for an average).

Body:
I currently have tried multiple ways (Execute SQL script, Table input, Database joins) to accomplish what I am trying to do. I need the sum and count respectively that my sql scripts below create to be put into a brand new field, or have these value be set as constants. I am trying to use each result in a calculator step later on in my transformation. Currently I have been trying to define fields using add constants and then played with the settings of the Execute SQL script (turning on or off variable substitution, putting the field name in the "Field to Contain Read stats"). But nothing has worked. If anyone knows of a good way to accomplish this it would greatly help!

Select sum(days_in_hospital) days_in_hospital_sum from hospital_days
where unique_stay_id in
(select unique_stay_id from hospital_days group by unique_stay_id having COUNT(unique_stay_id)=1);

SELECT COUNT(DISTINCT member_id) as "Total_Employees" from Hospital_days


问:
Refactoring session variables
I'm visiting an app that's been in use for the past 2+ years and it is in desperate need of refactoring.  It is of my own work, but you know what it's like when you visit old code again.

Anyway I've been using the excellent advice at sourcemaking to refactor and the code is already looking much better.

The problem now is there are loads of Session["variable"] sprinkled throughout the code, so what's the most accepted way to refactor these out?  I found this article at code project but apparently it can be quite dangerous.

答:
The best way to refactor random session usage like this is to create a static SessionWrapper with static properties that encapsulate the ASP.NET session store:

```<code>static class SessionWrapper
{
    public static string Variable
    {
        get { return Session["variable"]; }
        set { Session["variable"] = value; }
    }
}
</code>```

This will also allow you to put some logic around the getting and setting of these values and keep them in a centralized place.

I would also strongly recommend that you have some integration tests in place before you start this process so that you can be sure you haven't missed anything.

Title: Refactoring session variables

Body:
The best way to refactor random session usage like this is to create a static SessionWrapper with static properties that encapsulate the ASP.NET session store:

static class SessionWrapper
{
    public static string Variable
    {
        get { return Session["variable"]; }
        set { Session["variable"] = value; }
    }
}

This will also allow you to put some logic around the getting and setting of these values and keep them in a centralized place.

I would also strongly recommend that you have some integration tests in place before you start this process so that you can be sure you haven't missed anything.


问:
routing urls not correctly django 1.8
Help! I have a simple problem.

I made links in my templates, like this:

```<code><a href="students">students</a>
</code>```

When i go to alumni.html and i click on the link directing to students.html, it directs to alumni/students

but i want to click and see /students.

I dont understand why its routing to alumni/students instead.

I only changed one aspect of settings.py into: 'DIRS': [os.path.join(BASE_DIR, "templates")],

urls.py

```<code>from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^students/$', 'assignments.views.students', name='students'),
    url(r'^alumni/$', 'assignments.views.alumni', name='alumni'),
]
</code>```

views.py

```<code>from django.shortcuts import render

def students(request):
    return render(request, "students.html", {})

def alumni(request):
    return render(request, "alumni.html", {})
</code>```

What am i doing wrong?

答:
change the url in the template to this</p>

```<code><a href="{% url 'students' %}">students</a>
</code>```

Title: routing urls not correctly django 1.8

Body:
Help! I have a simple problem.

I made links in my templates, like this:

students

When i go to alumni.html and i click on the link directing to students.html, it directs to alumni/students

but i want to click and see /students.

I dont understand why its routing to alumni/students instead.

I only changed one aspect of settings.py into: 'DIRS': [os.path.join(BASE_DIR, "templates")],

urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^students/$', 'assignments.views.students', name='students'),
    url(r'^alumni/$', 'assignments.views.alumni', name='alumni'),
]

views.py

from django.shortcuts import render

def students(request):
    return render(request, "students.html", {})

def alumni(request):
    return render(request, "alumni.html", {})

What am i doing wrong?

Body:
change the url in the template to this

<a href="{% url 'students' %}">students</a>