问:
getting data from 2 tables in inner join
I am  not new in inner join but i don't know why i am getting data from two tables

Look i have some tables

Table One

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionD
</code>```

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

Table Two

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionP
</code>```

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

table three

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionS
</code>```

TransactionMId    ModelNumber EmeiNo  Color

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

now i want to show the data which is in table one and two but not in table three

Here is my Inner Join

```<code>SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
INNER JOIN dbo.tblTransactionS AS TS
ON
TP.EmeiNo != TS.EmeiNo
</code>```

but the executed result is showing data like this

```<code>BrandId Color   EmeiNo
1   grey    10001
1   black   10005
</code>```

the record of 10001 should not be shown in the query because it is in table three

what is wrong in my inner join

答:
If I understand your question correctly, you can try like this;

```<code>SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);
</code>```

As your description tblTransactionS (three table) join is not necessary.

Body:
I am  not new in inner join but i don't know why i am getting data from two tables

Look i have some tables

Table One

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionD

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

Table Two

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionP

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

table three

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionS

TransactionMId    ModelNumber EmeiNo  Color

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

now i want to show the data which is in table one and two but not in table three

Here is my Inner Join

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
INNER JOIN dbo.tblTransactionS AS TS
ON
TP.EmeiNo != TS.EmeiNo

but the executed result is showing data like this

BrandId Color   EmeiNo
1   grey    10001
1   black   10005

the record of 10001 should not be shown in the query because it is in table three

what is wrong in my inner join

Body:
If I understand your question correctly, you can try like this;

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);

As your description tblTransactionS (three table) join is not necessary.


来源: stackexchange

问:
How to run code in firebase without signing user in
Below is the JS code i aim to run :

```<code>var orderedPlayers = databaseService.s.child("playerweek2").orderByChild("id");
    $firebaseArray(orderedPlayers)
            .$loaded(function(loadedPlayers) {
            var normalizedPlayers = loadedPlayers.reduce(function(acc, next) { acc[next.id] = next; return acc; }, {});
            var selectedPlayers = $scope.pick.map(function(num){
                return normalizedPlayers[num];
            });
            $scope.players = selectedPlayers;

                        $scope.sum = function(items, prop){
                        return items.reduce( function(a, b){
                        return a + b[prop];
                        }, 0);
                        };
                        $scope.$watch('players', function (newValue, oldValue) {
    $scope.totalPoints = $scope.sum(newValue, 'goals');
    userRef.set($scope.totalPoints);

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

Is there a way to have this code run at a set time in the week every week without the user being signed in? The issue is the user needs to be signed in for the code to run but I aim to have the code run irrespective of if the user is signed in or not. Is this possible on firebase?

Below is what I tried unsuccessfully:

```<code>   exports.update = functions.database.ref('/Player')
   .onWrite(event=>{
    var pick=firebase.database().ref("users").child(user.uid).child("selection");
     $firebaseArray(Players)
        .$loaded(function(loadedPlayers) {
        var normalizedPlayers = loadedPlayers.reduce(function(acc, next)
         { acc[next.id] = next; return acc; }, {});
        var selectedPlayers = $scope.pick.map(function(num){
            return normalizedPlayers[num];
        });
    });
</code>```

答:
Cloud Functions is a part of Firebase that allows you to run code on a server, so the code is independent of any users.

Natively, there isn't a way to "schedule" a function to run (the functions are triggered by database changes, https requests, etc), but this blog post offers a solution: https://firebase.googleblog.com/2017/03/how-to-schedule-cron-jobs-with-cloud.html

ContentLicense: CC BY-SA 3.0

Body:
Below is the JS code i aim to run :

var orderedPlayers = databaseService.s.child("playerweek2").orderByChild("id");
    $firebaseArray(orderedPlayers)
            .$loaded(function(loadedPlayers) {
            var normalizedPlayers = loadedPlayers.reduce(function(acc, next) { acc[next.id] = next; return acc; }, {});
            var selectedPlayers = $scope.pick.map(function(num){
                return normalizedPlayers[num];
            });
            $scope.players = selectedPlayers;

                        $scope.sum = function(items, prop){
                        return items.reduce( function(a, b){
                        return a + b[prop];
                        }, 0);
                        };
                        $scope.$watch('players', function (newValue, oldValue) {
    $scope.totalPoints = $scope.sum(newValue, 'goals');
    userRef.set($scope.totalPoints);

},true);

Is there a way to have this code run at a set time in the week every week without the user being signed in? The issue is the user needs to be signed in for the code to run but I aim to have the code run irrespective of if the user is signed in or not. Is this possible on firebase?

Below is what I tried unsuccessfully:

   exports.update = functions.database.ref('/Player')
   .onWrite(event=>{
    var pick=firebase.database().ref("users").child(user.uid).child("selection");
     $firebaseArray(Players)
        .$loaded(function(loadedPlayers) {
        var normalizedPlayers = loadedPlayers.reduce(function(acc, next)
         { acc[next.id] = next; return acc; }, {});
        var selectedPlayers = $scope.pick.map(function(num){
            return normalizedPlayers[num];
        });
    });


问:
What is the purpose of "Macros for minimum-width integer constants"
In C99 standard Section 7.18.4.1 "Macros for minimum-width integer constants", some macros defined as [U]INT[N]_C(x) for casting constant integers to least data types where N = 8, 16, 32, 64. Why are these macros defined since I can use L, UL, LL or ULL modifiers instead? For example, when I want to use at least 32 bits unsigned constant integer, I can simply write 42UL instead of UINT32_C(42). Since long data type is at least 32 bits wide it is also portable.

So, what is the purpose of these macros?

答:
The macros essentially possibly add an integer constant suffix such as
L, LL, U, UL, o UL to their argument, which basically makes them almost equivalent to the corresponding cast, except that the suffix won't ever downcast.

E.g.,
UINT32_C(42000000000) (42 billion) on an LLP64 architecture will turn into 42000000000U, which will have type UL subject to the rules explained here. The corresponding cast, on the other hand ((uint32_t)42000000000), would truncate it down to uint32_t (unsigned int on LLP64).

I can't think of a good use case, but I imagine it could be usable in some generic bit-twiddling macros that need at least X bits to work, but don't want to remove any extra bits if the user passes in something bigger.


问:
Why am I getting errors with my JavaScript?
I am trying to practice JavaScript with basic DOM manipulation but I keep getting 2 errors:

1.SyntaxError: missing ; before statement

2.TypeError: size is not a function

function size() {
  var height = document.body.getElementById('hover1').style.height: 500 px;
  var width = document.body.getElementById('hover1').style.width: 500 px;
}
console.log(hover);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <title>javascript practice</title>
  <meta charset="utf-8" />
  <style>
    body {
      margin: 7em auto;
      background-color: green;
      width: 90%;
    }

    #size1 {
      background-color: blue;
      width: 150px;
      height: 150px;
      margin: 3em auto;
    }
  </style>
</head>
<body>
  <div id="size1"></div>
  <input type="button" value="size" onclick="size();">
</body></code>```

答:
There is nothing called document.body.getElementById instead change this to document.getElementById use as below

```<code>var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";
</code>```

function size1() {
console.log("test")
var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";

 }

    //console.log(hover);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>javascript practice</title>
<meta charset="utf-8"/>

<style>

  body {
    margin: 7em auto;
    background-color: green;
    width: 90%;
  }

  #size1 {
    background-color: blue;
    width: 150px;
    height: 150px;
    margin: 3em auto;
  }

</style>
  </head>
  <body>

<div id="size1">

</div>

   <input type="button" value="size" onclick="size1()">

   </body></code>```

Body:
I am trying to practice JavaScript with basic DOM manipulation but I keep getting 2 errors:

1.SyntaxError: missing ; before statement

2.TypeError: size is not a function

function size() {
  var height = document.body.getElementById('hover1').style.height: 500 px;
  var width = document.body.getElementById('hover1').style.width: 500 px;
}
console.log(hover);

<!DOCTYPE html>

  <title>javascript practice</title>
  <meta charset="utf-8" />

  <input type="button" value="size" onclick="size();">

Body:
There is nothing called document.body.getElementById instead change this to document.getElementById use as below

var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";

function size1() {
console.log("test")
var height = (document.getElementById('hover1'))?document.getElementById('hover1').style.height: "500px";
var width = (document.getElementById('hover1'))?document.getElementById('hover1').style.width: "500px";

 }

    //console.log(hover);

<!DOCTYPE html>
<html>
<head>
<title>javascript practice</title>
<meta charset="utf-8"/>

<style>

  body {
    margin: 7em auto;
    background-color: green;
    width: 90%;
  }

  #size1 {
    background-color: blue;
    width: 150px;
    height: 150px;
    margin: 3em auto;
  }

</style>
  </head>
  <body>

<div id="size1">

</div>

   <input type="button" value="size" onclick="size1()">

   </body>


问:
ASP.NET Core C# Web API POST/PUT relational data
I'm building a simple app for entertainment with ASP.NET Core where I currently just have a Post model and a User model.

Post.cs:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Post
    {
        [Required]
        public int Id { get; set; }

        [Required]
        [MaxLength(16)]
        public string Title { get; set; }

        public string Body { get; set; }

        [Required]
        public Person Author { get; set; }
    }
}
</code>```

Person.cs:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public ICollection<Post> Posts = new List<Post>();
    }
}
</code>```

I used Visual Studio's scaffolding to generate controllers for those models.
When I'm trying to POST /api/posts in order to create a new post, I want also to specify the Author ID for that post.

I tried adding the attribute authorId, I tried "authorId": 1 and also "author": { "id": 1 }, but because the Author is required, I always get back either Author is missing or Email in author is missing etc.

How can I include the authorId for in the post body in order I would be able to successfully create a new post?

答:
I am not sure what is your current controller method, as you havent posted that here to see what is wrong, but to give you a general idea, this is how it should look like

Note : Am unsure why you would want to have the author Id as a query string for HTTPPOST, as the authorId would be part of author property of the post model itself and that you can always verify if(IsValid(postModel.AuthorId))
and if not valid, based on your business logic, create the author first and then the post or else send a response saying badrequest and that the author must exist

```<code>   [HttpPost]
   [Route("{authorid}")]
   public Task<IActionResult> MyPostMethod(string authorid, [FromBody] Post postModel)
    {
            // yourWork
    }
</code>```

Body:
I'm building a simple app for entertainment with ASP.NET Core where I currently just have a Post model and a User model.

Post.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Post
    {
        [Required]
        public int Id { get; set; }

        [Required]
        [MaxLength(16)]
        public string Title { get; set; }

        public string Body { get; set; }

        [Required]
        public Person Author { get; set; }
    }
}

Person.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Person
    {
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public ICollection<Post> Posts = new List<Post>();
    }
}

I used Visual Studio's scaffolding to generate controllers for those models.
When I'm trying to POST /api/posts in order to create a new post, I want also to specify the Author ID for that post.

I tried adding the attribute authorId, I tried "authorId": 1 and also "author": { "id": 1 }, but because the Author is required, I always get back either Author is missing or Email in author is missing etc.

How can I include the authorId for in the post body in order I would be able to successfully create a new post?

Body:
I am not sure what is your current controller method, as you havent posted that here to see what is wrong, but to give you a general idea, this is how it should look like

Note : Am unsure why you would want to have the author Id as a query string for HTTPPOST, as the authorId would be part of author property of the post model itself and that you can always verify if(IsValid(postModel.AuthorId))
and if not valid, based on your business logic, create the author first and then the post or else send a response saying badrequest and that the author must exist

   [HttpPost]
   [Route("{authorid}")]
   public Task<IActionResult> MyPostMethod(string authorid, [FromBody] Post postModel)
    {
            // yourWork
    }


问:
Which part of Id token i can used to identify one domain
The document https://learn.microsoft.com/en-us/outlook/add-ins/inside-the-identity-token, it introduces the content in the outlook AddIn id token, and i found there are two different keys "ISS" and "APPCTXSender", i want to know what's the different usage between them. Also I want to know which part of them i can used to identity one domain/org/tenant. </p>

答:
To uniquely identify a user via identity token, we recommend that you combine the msexchuid and amurl properties in the response (see "Generating a unique ID"
 on this page.) As for the other half of your question, could you tell us more about your scenario and why you are looking for tenant/domain?


问:
Merge multiple variables in R
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
</code>```

How can I merge them to just two columns? so the result is:

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))
</code>```

答:
You could also do this via gather and spread with tidyr and dplyr.  Less concise than @useR's solution, but might be useful if you need to do any intermediate manipulation.

```<code>library(dplyr)
library(tidyr)

df %>%
  gather(variable, value, -ID, -FACT, na.rm = TRUE) %>%
  mutate(variable = gsub("\\_[A-Z]", "", variable)) %>%
  spread(variable, value) %>%
  left_join(df)

  ID FACT DV1 DV2 DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C
1  1    A   1   3     1    NA    NA     3    NA    NA
2  2    B   4   3    NA     4    NA    NA     3    NA
3  3    C   5   5    NA    NA     5    NA    NA     5
</code>```

Title: Merge multiple variables in R

Body:
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

How can I merge them to just two columns? so the result is:

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))

Body:
You could also do this via gather and spread with tidyr and dplyr.  Less concise than @useR's solution, but might be useful if you need to do any intermediate manipulation.

library(dplyr)
library(tidyr)

df %>%
  gather(variable, value, -ID, -FACT, na.rm = TRUE) %>%
  mutate(variable = gsub("\\_[A-Z]", "", variable)) %>%
  spread(variable, value) %>%
  left_join(df)

  ID FACT DV1 DV2 DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C
1  1    A   1   3     1    NA    NA     3    NA    NA
2  2    B   4   3    NA     4    NA    NA     3    NA
3  3    C   5   5    NA    NA     5    NA    NA     5


问:
Processing files with ImageIO from a ZipFile
I got an error trying to read image files from a zipfile using imageio:

```<code>import zipfile
import glob
import imageio
from os.path import splitext

    for database in glob.iglob('Datasets/*.zip'):
        print(database)
        zf = zipfile.ZipFile(database, 'r')
        for file in zf.namelist():
            basename,extension = splitext(file)
            if extension == '.png':
                img = imageio.imread(file)
                print(img.shape, end='')
</code>```

Here is the traceback:

```<code>Datasets/first.zip
Traceback (most recent call last):
  File "testZip.py", line 12, in <module>
    img = imageio.imread(file)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 200, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 117, in get_reader
    request = Request(uri, 'r' + mode, **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 120, in __init__
    self._parse_uri(uri)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 252, in _parse_uri
    raise IOError("No such file: '%s'" % fn)
OSError: No such file: 'first/image_7395.png'
[Finished in 0.2s with exit code 1]
</code>```

答:
The file variable contains a file name, not the actual file data. The error was pretty clear: A file named first/image_7395.png does not exist on the disk - it is in the zip though. You'll need to extract the file from the zip and use the extracted file for imageio. For example:

```<code>for database in glob.iglob('Datasets/*.zip'):
    print(database)
    zf = zipfile.ZipFile(database, 'r')
    for file in zf.namelist():
        basename,extension = splitext(file)
        if extension == '.png':
            ofile = zf.extract(file)
            img = imageio.imread(ofile)
            print(img.shape, end='')
            # if you need to:
            os.remove(ofile)
</code>```

Edit: Looks like imageio can also read from a file-like object, in which case you can use ZipFile.open() and pass that to imageio. For example:

```<code># ...
if extension == '.png':
    with zf.open(file) as img_file:
        img = imageio.read(img_file)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I got an error trying to read image files from a zipfile using imageio:

import zipfile
import glob
import imageio
from os.path import splitext

    for database in glob.iglob('Datasets/*.zip'):
        print(database)
        zf = zipfile.ZipFile(database, 'r')
        for file in zf.namelist():
            basename,extension = splitext(file)
            if extension == '.png':
                img = imageio.imread(file)
                print(img.shape, end='')

Here is the traceback:

Datasets/first.zip
Traceback (most recent call last):
  File "testZip.py", line 12, in <module>
    img = imageio.imread(file)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 200, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 117, in get_reader
    request = Request(uri, 'r' + mode, **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 120, in __init__
    self._parse_uri(uri)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 252, in _parse_uri
    raise IOError("No such file: '%s'" % fn)
OSError: No such file: 'first/image_7395.png'
[Finished in 0.2s with exit code 1]

Body:
The file variable contains a file name, not the actual file data. The error was pretty clear: A file named first/image_7395.png does not exist on the disk - it is in the zip though. You'll need to extract the file from the zip and use the extracted file for imageio. For example:

for database in glob.iglob('Datasets/*.zip'):
    print(database)
    zf = zipfile.ZipFile(database, 'r')
    for file in zf.namelist():
        basename,extension = splitext(file)
        if extension == '.png':
            ofile = zf.extract(file)
            img = imageio.imread(ofile)
            print(img.shape, end='')
            # if you need to:
            os.remove(ofile)

Edit: Looks like imageio can also read from a file-like object, in which case you can use ZipFile.open() and pass that to imageio. For example:

# ...
if extension == '.png':
    with zf.open(file) as img_file:
        img = imageio.read(img_file)


问:
C#: Remove Excess Text From String
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

```<code>void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}
</code>```

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

答:
You use a regular expression with a capturing group:

```<code>Regex r = new Regex("^(?<v>[-0-9 ]+?)");
</code>```

This means "from the start of the input string (^) match [0 to 9 or space or hyphen] and keep going for as many occurrences of these characters as are available (+?) and store it into variable v (?)"

We get it out like this:

```<code>r.Matches(input)[0].Groups["v"].Value
</code>```

Note though that if the input string doesn't match, the match collection will be 0 long and a call to [0] will crash. To this end you might want to robust it up with some extra error checking:

```<code>MatchCollection mc = r.Matches(input);
if(mc.Length > 0)
  MessageBox.Show(mc[0].Groups["v"].Value;
</code>```

Title: C#: Remove Excess Text From String

Body:
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

Body:
You use a regular expression with a capturing group:

Regex r = new Regex("^(?<v>[-0-9 ]+?)");

This means "from the start of the input string (^) match [0 to 9 or space or hyphen] and keep going for as many occurrences of these characters as are available (+?) and store it into variable v (?)"

We get it out like this:

r.Matches(input)[0].Groups["v"].Value

Note though that if the input string doesn't match, the match collection will be 0 long and a call to [0] will crash. To this end you might want to robust it up with some extra error checking:

MatchCollection mc = r.Matches(input);
if(mc.Length > 0)
  MessageBox.Show(mc[0].Groups["v"].Value;


问:
Can experimental features like offscreenanvas be enabled in electron?
A 2d or webgl canvas rendered using OffscreenCanvas could have some interesting performance benefits. I'm wondering if there is a way to enable it in the latest electron.

Setting the experimentalFeatures flag as discussed in this thread did not work.

The following console logs:

```<code>console.log('canvasNode', canvasNode)
console.log('transferControlToOffscreen', canvasNode.transferControlToOffscreen)
console.log('OffscreenCanvas', window.OffscreenCanvas)
</code>```

Output this results:

And the way I am instantiating the browser window which logs this is:

```<code>win = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: { experimentalFeatures: true }
})
</code>```

答:
Two links and a google later I found the answer on this github doc page

Since the offscreencanvas is a canvas related feature it is under a different flag called experimentalCanvasFeatures

In order to enable it I had to instantiate my browser window like so:

```<code>win = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: { experimentalCanvasFeatures: true }
})
</code>```

With experimentalCanvasFeatures instead of experimentalFeatures.

This resulted in the following console output:

Body:
A 2d or webgl canvas rendered using OffscreenCanvas could have some interesting performance benefits. I'm wondering if there is a way to enable it in the latest electron.

Setting the experimentalFeatures flag as discussed in this thread did not work.

The following console logs:

console.log('canvasNode', canvasNode)
console.log('transferControlToOffscreen', canvasNode.transferControlToOffscreen)
console.log('OffscreenCanvas', window.OffscreenCanvas)

Output this results:

And the way I am instantiating the browser window which logs this is:

win = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: { experimentalFeatures: true }
})

Body:
Two links and a google later I found the answer on this github doc page

Since the offscreencanvas is a canvas related feature it is under a different flag called experimentalCanvasFeatures

In order to enable it I had to instantiate my browser window like so:

win = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: { experimentalCanvasFeatures: true }
})

With experimentalCanvasFeatures instead of experimentalFeatures.

This resulted in the following console output:


问:
Spurious rotation events while switching tasks in ios 11
My app is crashing when you return to it after switching away from it using the 4-finger task-switch gesture on an iPad.

When the user does the 4-finger gesture to switch away from my app, I see applicationWillResignActive: then applicationDidEnterBackground: in my app delegate, then (assuming we're currently in portrait orientation) my top-level view controller gets viewWillTransitionToSize:withTransitionCoordinator: with a size that indicates landscape layout (even though the device has not rotated). This of course results in a lot of resizing and rearranging of views for the new orientation. Immediately after that I get viewWillTransitionToSize:withTransitionCoordinator: with a size that indicates portrait (the original orientation of the device). And again, I go through all my layout again for the new (actually, original) orientation.

What I'm finding is that if I wait for all of this to complete, I can switch in and out of my app all day. If, on the other hand, I switch back to my app while this needless work is going on, I get a crash deep in some iOS transition code.

At this point I'm trying to understand why I get these stray rotation events. If I can avoid getting those, I can avoid getting into whatever situation is causing the crash. They don't seem necessary.

答: It turns out there isn't a way to prevent the rotation events from being reported to the app. I suspect that's an iOS bug. However, ignoring viewWillTransitionToSize:withTransitionCoordinator: when the application state is UIApplicationStateBackground and doing the same in the view's layoutSubviews (if present) allowed me to work around the problem.


问:
Event Bubbling and jQuery
I'm trying to capture a click event that bubbles up the DOM to the body, check to see what the selector of the click element is, and then based on that, choose to call a function.

Something like this:

```<code><body>
    <a id="do-default-code">Default code</a>
    <a id="do-override-code">Override code</a>
</body>
</code>```

And I'm picturing (psuedo-code) like this. I am using jQuery:

```<code>$('body').bind('click', function() {
    if ($(this) === $('#do-override-code')) {
        overrideCode();
    } else {

    }
});
</code>```

I realize that I don't fully understand event bubbling in this context, and that the above code is not correct, so I am looking to the community for guidance.

答:
You'll need to pass in the event on your function and check the event.

This link gives all the information you could want to know http://www.quirksmode.org/js/events_properties.html such as

Which HTML element is the target of the event?

from which you can easily extract whatever semantic info you wanted

ContentLicense: CC BY-SA 2.5

Title: Event Bubbling and jQuery

Body:
I'm trying to capture a click event that bubbles up the DOM to the body, check to see what the selector of the click element is, and then based on that, choose to call a function.

Something like this:

    Default code
    Override code

And I'm picturing (psuedo-code) like this. I am using jQuery:

$('body').bind('click', function() {
    if ($(this) === $('#do-override-code')) {
        overrideCode();
    } else {

    }
});

I realize that I don't fully understand event bubbling in this context, and that the above code is not correct, so I am looking to the community for guidance.


问:
Remove IBOutlet programmatically that is set in interface builder and add it again with same constraints
Lets say I have a ViewController in a .nib file with an IBOutlet imageView as subView with constraints, the imageView is connected to the ViewController class associated with the nib file. Now I remove the imageView with the following code:

```<code>imageView.removeFromSuperview()
</code>```

And later I want to add it again to the ViewController View with the same constraints as I set in the interface builder before I removed the imageView. My questions are:

Is it possible to do that in code without initialising the ViewController again?

If I add the imageView as SubView to the VC programmatically after I have removed it the constraints are no longer available. I would really like to skip setting the constraints again in code since they already exist in the interface builder, is that possible?

答:
One way is to save your constraints in a var and set them back programatically. By the way since IBOutlet is weak, once you remove it you can't add the imageView back. So you'll have to maintain a strong reference. Also removing the imageView will disturb other views that have dependent constraints. However if other views' constraints are independent of your imageView it won't be a problem.

The other way is have a reference to your imageView's height or width constraint and change its constant to zero to virtually make it disappear from your view. This way you'll just have to change the constraint back to its original value to unhide it and also makes sure that other views' constraints get adjusted automatically.

Body:
Lets say I have a ViewController in a .nib file with an IBOutlet imageView as subView with constraints, the imageView is connected to the ViewController class associated with the nib file. Now I remove the imageView with the following code:

imageView.removeFromSuperview()

And later I want to add it again to the ViewController View with the same constraints as I set in the interface builder before I removed the imageView. My questions are:

Is it possible to do that in code without initialising the ViewController again?

If I add the imageView as SubView to the VC programmatically after I have removed it the constraints are no longer available. I would really like to skip setting the constraints again in code since they already exist in the interface builder, is that possible?


问:
Clock Offset CDH 5.10 (with Kudu in particular)
Prior to the CDH 5.10 release all aspects seem to work OK with the Cloudera VMs that I installed. With CDH 5.10 all components are at various times suffering clock-offset issues. I am a bit surprised. Restarting and issuing clock reset commands are rather annoying. Any pointers out there? Reading documentation does not seem to help in that all aspects do not remedy what is going on once and for all.</p>

答:
http://community.cloudera.com/t5/Interactive-Short-cycle-SQL/kudu-service-are-getting-down-frequently/td-p/55644

So as to prove the point that others have experienced this as well. Low view count tells me something as well.


答:
If you are going to set the height of the element and assign the height to var height then you need to do the following:

```<code>var height = document.getElementById("size1").style.height = "500px";
</code>```

If you are going to just assign the height of the element to var height then you need to do the following:

```<code>var height = document.getElementById("size1").style.height;
</code>```

If you are just going to set the height of the element then you just need to do:

```<code>document.getElementById("size1").style.height = "500px";
</code>```

You should also make your 500px with quotes as numbers do not need " " around them but once you add text...it all becomes text. So either way you should have "500px"

I would also make your button into this:

```<code><button type="button" value="size" onclick="size()">Size</button>
</code>```

Based on a belief that you are trying to make the div larger onclick of Size button then you should have the following:

Style

```<code>body {
    margin: 7em auto;
    background-color: green;
    width: 90%;
}

#size1 {
    background-color: blue;
    width: 150px;
    height: 150px;
    margin: 3em auto;
}
</code>```

HTML

```<code><div id="size1"></div>

<button type="button" value="size" onclick="size()">Size</button>
</code>```

JavaScript

```<code>function size() {
  document.getElementById('size1').style.height = "500px";
  document.getElementById('size1').style.width = "500px";
}
</code>```

Title: Why am I getting errors with my JavaScript?

Body:
If you are going to set the height of the element and assign the height to var height then you need to do the following:

var height = document.getElementById("size1").style.height = "500px";

If you are going to just assign the height of the element to var height then you need to do the following:

var height = document.getElementById("size1").style.height;

If you are just going to set the height of the element then you just need to do:

document.getElementById("size1").style.height = "500px";

You should also make your 500px with quotes as numbers do not need " " around them but once you add text...it all becomes text. So either way you should have "500px"

I would also make your button into this:

<button type="button" value="size" onclick="size()">Size</button>

Based on a belief that you are trying to make the div larger onclick of Size button then you should have the following:

Style

body {
    margin: 7em auto;
    background-color: green;
    width: 90%;
}

#size1 {
    background-color: blue;
    width: 150px;
    height: 150px;
    margin: 3em auto;
}

HTML

<div id="size1"></div>

<button type="button" value="size" onclick="size()">Size</button>

JavaScript

function size() {
  document.getElementById('size1').style.height = "500px";
  document.getElementById('size1').style.width = "500px";
}


问:
Optimize Angular application for Production Environment
I'm trying to optimize my Angular application for Production. Currently I'm using Uglify, Compression, ... and I'm compiling in AOT. When I compile the application I'm getting this message:

```<code>Asset     Size  Chunks                    Chunk Names
main.bundle.js  2.66 MB       0  [emitted]  [big]  main
main.bundle.js.gz   530 kB          [emitted]  [big]
../index.html   2.3 kB          [emitted]
</code>```

Looking in the Webpack Bundle Analyzer I have seen the next one:

Here I have seen that:

1.- @angular/material are adding all the components to the bundle but I only use some of this.

2.- In my SRC are being added my *.component.ts files but also my *.component.ngfactory.ts (the same for my CSS)

So, my question is: Is there a way to ask Webpack not to include the components from material that I'm not using? And, what are the ngfactory files and why they are being added?

UPDATE 1: 11/14/2017

Hi, I have been investigating and I have seen that, when I'm compiling for AOT my browser.module.ngfactory.ts contain "import * from ..." for all the dependencies

```<code>import * as i81 from '../+app/+product/product.component';
import * as i82 from '../+app/+term/term.component';
import * as i83 from '../+app/+home/home.component';
import * as i84 from '../+app/+oops/oops.component';
import * as i85 from '@angular/material/toolbar';
import * as i86 from '@angular/material/button';
import * as i87 from '@angular/material/button-toggle';
</code>```

For example, I'm not using angular/material/toolbar, so I don't understand why it is being added.

答:
There's a lot of things that you could do to optimize your production builds (like removing unnecessary material modules). It looks to be like you're not using angular-cli, but their --build-optimizer flag for production builds is very helpful.

Based on your bundle analyzer report, your src modules are quite large, for this I would recommend lazy loading. It will allow you load the modules over time as the user navigates to them instead of all upon app initialization. You can see an example of lazy loading here

Here are some more detailed answers about optimizing angular bundle sizes

Body:
I'm trying to optimize my Angular application for Production. Currently I'm using Uglify, Compression, ... and I'm compiling in AOT. When I compile the application I'm getting this message:

Asset     Size  Chunks                    Chunk Names
main.bundle.js  2.66 MB       0  [emitted]  [big]  main
main.bundle.js.gz   530 kB          [emitted]  [big]
../index.html   2.3 kB          [emitted]

Looking in the Webpack Bundle Analyzer I have seen the next one:

Here I have seen that:

1.- @angular/material are adding all the components to the bundle but I only use some of this.

2.- In my SRC are being added my *.component.ts files but also my *.component.ngfactory.ts (the same for my CSS)

So, my question is: Is there a way to ask Webpack not to include the components from material that I'm not using? And, what are the ngfactory files and why they are being added?

UPDATE 1: 11/14/2017

Hi, I have been investigating and I have seen that, when I'm compiling for AOT my browser.module.ngfactory.ts contain "import * from ..." for all the dependencies

import * as i81 from '../+app/+product/product.component';
import * as i82 from '../+app/+term/term.component';
import * as i83 from '../+app/+home/home.component';
import * as i84 from '../+app/+oops/oops.component';
import * as i85 from '@angular/material/toolbar';
import * as i86 from '@angular/material/button';
import * as i87 from '@angular/material/button-toggle';

For example, I'm not using angular/material/toolbar, so I don't understand why it is being added.


问:
Use of try/except for input validation?
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.</p>

```<code>    list = []
    def users_name():
      while True:
        try:
          name = str(input("Please enter your first name: "))
          list.append(name)
          break
        except TypeError:
          print("Letters only please.")
          continue
        except EOFError:
          print("Please input something....")
          continue

    users_name()
</code>```

答:
To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length.

To check if you string has only alphabetic characters you can use the str.isalpha() method to check so.

Therefore, if you check len(name) > 2 and name.isalpha() will help you filter those string that do not match what you want:

```<code>>>> name = "MyName"
>>> len(name) > 2 and name.isalpha()
True
>>> wrong_name = "My42Name"
>>> len(wrong_name) > 2 and wrong_name.isalpha()
False
>>> short_name = "A"
>>> len(short_name) > 2 and short_name.isalpha()
False
</code>```

Title: Use of try/except for input validation?

Body:
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.

    list = []
    def users_name():
      while True:
        try:
          name = str(input("Please enter your first name: "))
          list.append(name)
          break
        except TypeError:
          print("Letters only please.")
          continue
        except EOFError:
          print("Please input something....")
          continue

    users_name()

Body:
To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length.

To check if you string has only alphabetic characters you can use the str.isalpha() method to check so.

Therefore, if you check len(name) > 2 and name.isalpha() will help you filter those string that do not match what you want:

>>> name = "MyName"
>>> len(name) > 2 and name.isalpha()
True
>>> wrong_name = "My42Name"
>>> len(wrong_name) > 2 and wrong_name.isalpha()
False
>>> short_name = "A"
>>> len(short_name) > 2 and short_name.isalpha()
False


问:
tableview header in two rows
i'm italian, so sorry for my "ugly" english!

I'm working with a UITableview and my (dynamic) headers are too long!
So i want to split the headers in two rows... is it possible?

i've tried to uso "label.numberOfLines = 2" (or = 0) but it doesn't works!

this is the code:

```<code>- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   UILabel *label = [[[UILabel alloc] init] autorelease];
    label.backgroundColor = [UIColor clearColor];

    NSString *header1 = [NSString stringWithFormat:@"Between %@ and %@ \n (33ª and 37ª week)", dateString1, dateString2];

    if (section == 0){
            label.text = header1;
            label.frame = CGRectMake(0, 6, 300, 30);
    } else
    //the others header

    label.numberOfLines = 2;

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [view autorelease];
    [view addSubview:label];

    return view;}
</code>```

thank you!!

答:
You should set the frame for your label even on the else, specially because it needs to be bigger to accommodate the two lines of text.

You could do something like this:

```<code>    label.frame = CGRectMake(0, 0, 320, 30); // trying bigger heights
    label.numberOfLines = 2;
    // ...
</code>```

Title: tableview header in two rows

Body:
i'm italian, so sorry for my "ugly" english!

I'm working with a UITableview and my (dynamic) headers are too long!
So i want to split the headers in two rows... is it possible?

i've tried to uso "label.numberOfLines = 2" (or = 0) but it doesn't works!

this is the code:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   UILabel *label = [[[UILabel alloc] init] autorelease];
    label.backgroundColor = [UIColor clearColor];

    NSString *header1 = [NSString stringWithFormat:@"Between %@ and %@ \n (33ª and 37ª week)", dateString1, dateString2];

    if (section == 0){
            label.text = header1;
            label.frame = CGRectMake(0, 6, 300, 30);
    } else
    //the others header

    label.numberOfLines = 2;

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [view autorelease];
    [view addSubview:label];

    return view;}

thank you!!

Body:
You should set the frame for your label even on the else, specially because it needs to be bigger to accommodate the two lines of text.

You could do something like this:

    label.frame = CGRectMake(0, 0, 320, 30); // trying bigger heights
    label.numberOfLines = 2;
    // ...


问:
How to re-merge an already merged branch?
I have a commit graph that looks something like the one below. Commits marked with * represent lots of commits.

```<code>   A*
   |
   B---------
   |        |
   C*       D*    <- old feature branch
   |        |
   E---------
   |
   F*
   |
   G      <- master
</code>```

The merge commit E was done incorrectly and some changes (not all) in C*  have been lost. How can I redo that merge to reintroduce the changes into the current master?

Everything has already been pushed (open source project), so changing history is not an option.

I tried creating a patch from the commits C* and apply that to the master, but because some of the changes from C* have been merged correctly and because the project evolved since that commit, about 80% of the patch fails.

Ideally, we would take all the changes in C*, apply them to master and resolve all conflicts. But because the branches have already been merged, git doesn't detect any changes and won't allow to merge again.

```<code>$ git checkout 5bc5295   # C
HEAD is now at 5bc5295... cleanup

$ git checkout -b "missing-commits"
Switched to a new branch 'missing-commits'

$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

$ git merge missing-commits
Already up-to-date.
</code>```

答:
Git stores snapshots and detects changes on the fly, so the way to work with the difference between a bad commit and a good one is to record the good as  a descendant the bad—pretty much the same as anything, come to think of it.  Use git reset --soft to tell git the correct ancestry:

```<code>git checkout badmerge^1    # generate the right result
git merge badmerge^2

... Fix conflicts ...
git commit

git reset --soft badmerge  # as an improvement on the wrong result
git commit

git checkout master        # merge the difference now that git sees it
git merge HEAD@{1} -m "applying corrections to a bad merge"
</code>```

Body:
I have a commit graph that looks something like the one below. Commits marked with * represent lots of commits.

   A*
   |
   B---------
   |        |
   C*       D*    <- old feature branch
   |        |
   E---------
   |
   F*
   |
   G      <- master

The merge commit E was done incorrectly and some changes (not all) in C*  have been lost. How can I redo that merge to reintroduce the changes into the current master?

Everything has already been pushed (open source project), so changing history is not an option.

I tried creating a patch from the commits C* and apply that to the master, but because some of the changes from C* have been merged correctly and because the project evolved since that commit, about 80% of the patch fails.

Ideally, we would take all the changes in C*, apply them to master and resolve all conflicts. But because the branches have already been merged, git doesn't detect any changes and won't allow to merge again.

$ git checkout 5bc5295   # C
HEAD is now at 5bc5295... cleanup

$ git checkout -b "missing-commits"
Switched to a new branch 'missing-commits'

$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

$ git merge missing-commits
Already up-to-date.

Body:
Git stores snapshots and detects changes on the fly, so the way to work with the difference between a bad commit and a good one is to record the good as  a descendant the bad—pretty much the same as anything, come to think of it.  Use git reset --soft to tell git the correct ancestry:

git checkout badmerge^1    # generate the right result
git merge badmerge^2

... Fix conflicts ...
git commit

git reset --soft badmerge  # as an improvement on the wrong result
git commit

git checkout master        # merge the difference now that git sees it
git merge HEAD@{1} -m "applying corrections to a bad merge"


问:
JSON serialization of array with polymorphic objects
Is it possible with .NET standard JavascriptSerializer/JsonDataContractSerializer or external parsers, to serialize objects array using a wrapper approach including the object type?

For example, to generate this JSON from a List:

```<code>[{ 'dog': { ...dog properties... } },
 { 'cat': { ...cat properties... } }]
</code>```

instead of typical:

```<code>[{ ...dog properties... },
 { ...cat properties... }]
</code>```

This is doable in Java with Jackson using JsonTypeInfo.As.WRAPPER_OBJECT attribute.

答:
I got this done as per the question. Wasn't exactly straightforward, but here goes. There is not an easy way to do this in Json.NET. Would be awesome if it supported a pre-serialization callback where you could insert your own type information, but that is another story.

I have an interface (IShape) that the polymorphic classes implement. One of the classes is a container (composite pattern) and contains a list of contained objects. I did this with interfaces but the same concept applies to base classes.

```<code>public class Container : IShape
{
    public virtual List<IShape> contents {get;set;}
    // implement interface methods
</code>```

As per the question, I want this to serialize as:

```<code>  "container": {
    "contents": [
      {"box": { "TopLeft": {"X": 0.0,"Y": 0.0},"BottomRight": {"X": 1.0, "Y": 1.0} } },
      {"line": {"Start": { "X": 0.0,"Y": 0.0},"End": {"X": 1.0,"Y": 1.0 }} },
</code>```

etc.

To do this I wrote a wrapper class. Each of the objects that implement the interface has a property in the wrapper. This sets the property name in the serializer. Conditional serialization ensures the correct property is used. All interface methods are delegated to the wrapped class, and visitor Accept() calls are directed to the wrapped class. This means in contexts using the interface, the Wrapped or unwrapped classes will behave the same.

```<code>    public class SerializationWrapper : IShape
    {
        [JsonIgnore]
        public IShape Wrapped { get; set; }
        // Accept method for the visitor - redirect visitor to the wrapped class
        // so visitors will behave the same with wrapped or unwrapped.
        public void Accept(IVisitor visitor) => Wrapped.Accept(visitor);

        public bool ShouldSerializeline() => line != null;
        // will serialize as line : { ...
        public Line line { get =>Wrapped as Line;}

        public bool ShouldSerializebox() => box != null;
        public Box box { get => Wrapped as Box; }

        public bool ShouldSerializecontainer() => container != null;
        public Container container { get => Wrapped as Container; }

        // IShape methods delegated to Wrapped
        [JsonIgnore]
        public Guid Id { get => Wrapped.Id; set => Wrapped.Id = value; }
</code>```

I also have a visitor pattern implemented to traverse the object graph. I had this already due to the rest of the software design, but if you just have a simple collection you could just iterate the collection and add the wrapper.

```<code>    public class SerializationVisitor : IVisitor
    {
        public void Visit(IContainer shape)
        {
            // replace list items with wrapped list items
            var wrappedContents = new List<IShape>();
            shape.Contents.ForEach(s => { wrappedContents.Add(new SerializationWrapper(){ Wrapped = s}); s.Accept(this); });
            shape.Contents = wrappedContents;
        }

        public void Visit(ILine shape){}
        public void Visit(IBox shape){}
    }
</code>```

The visitor replaces the content of the Container class with wrapped versions of the classes.

Serialize, and it produces the required output.

```<code>        SerializationVisitor s = new SerializationVisitor();
        s.Visit(label);
</code>```

Since I already have the Visitor and am doing everything through interfaces it is probably just as easy to do my own serializer, anyway.......

Body:
Is it possible with .NET standard JavascriptSerializer/JsonDataContractSerializer or external parsers, to serialize objects array using a wrapper approach including the object type?

For example, to generate this JSON from a List:

[{ 'dog': { ...dog properties... } },
 { 'cat': { ...cat properties... } }]

instead of typical:

[{ ...dog properties... },
 { ...cat properties... }]

This is doable in Java with Jackson using JsonTypeInfo.As.WRAPPER_OBJECT attribute.

Body:
I got this done as per the question. Wasn't exactly straightforward, but here goes. There is not an easy way to do this in Json.NET. Would be awesome if it supported a pre-serialization callback where you could insert your own type information, but that is another story.

I have an interface (IShape) that the polymorphic classes implement. One of the classes is a container (composite pattern) and contains a list of contained objects. I did this with interfaces but the same concept applies to base classes.

public class Container : IShape
{
    public virtual List<IShape> contents {get;set;}
    // implement interface methods

As per the question, I want this to serialize as:

  "container": {
    "contents": [
      {"box": { "TopLeft": {"X": 0.0,"Y": 0.0},"BottomRight": {"X": 1.0, "Y": 1.0} } },
      {"line": {"Start": { "X": 0.0,"Y": 0.0},"End": {"X": 1.0,"Y": 1.0 }} },

etc.

To do this I wrote a wrapper class. Each of the objects that implement the interface has a property in the wrapper. This sets the property name in the serializer. Conditional serialization ensures the correct property is used. All interface methods are delegated to the wrapped class, and visitor Accept() calls are directed to the wrapped class. This means in contexts using the interface, the Wrapped or unwrapped classes will behave the same.

    public class SerializationWrapper : IShape
    {
        [JsonIgnore]
        public IShape Wrapped { get; set; }
        // Accept method for the visitor - redirect visitor to the wrapped class
        // so visitors will behave the same with wrapped or unwrapped.
        public void Accept(IVisitor visitor) => Wrapped.Accept(visitor);

        public bool ShouldSerializeline() => line != null;
        // will serialize as line : { ...
        public Line line { get =>Wrapped as Line;}

        public bool ShouldSerializebox() => box != null;
        public Box box { get => Wrapped as Box; }

        public bool ShouldSerializecontainer() => container != null;
        public Container container { get => Wrapped as Container; }

        // IShape methods delegated to Wrapped
        [JsonIgnore]
        public Guid Id { get => Wrapped.Id; set => Wrapped.Id = value; }

I also have a visitor pattern implemented to traverse the object graph. I had this already due to the rest of the software design, but if you just have a simple collection you could just iterate the collection and add the wrapper.

    public class SerializationVisitor : IVisitor
    {
        public void Visit(IContainer shape)
        {
            // replace list items with wrapped list items
            var wrappedContents = new List<IShape>();
            shape.Contents.ForEach(s => { wrappedContents.Add(new SerializationWrapper(){ Wrapped = s}); s.Accept(this); });
            shape.Contents = wrappedContents;
        }

        public void Visit(ILine shape){}
        public void Visit(IBox shape){}
    }

The visitor replaces the content of the Container class with wrapped versions of the classes.

Serialize, and it produces the required output.

        SerializationVisitor s = new SerializationVisitor();
        s.Visit(label);

Since I already have the Visitor and am doing everything through interfaces it is probably just as easy to do my own serializer, anyway.......


问:
disabled.bind not changing after DOM load
Below is the HTML snippet for a button that I would like to be disabled while no files, from a UI list of files, are selected:

```<code><button id="downloadButton" disabled.bind="selectedFileCount() == 0" click.trigger="downloadFiles()" type="button">Download Selected</button>
</code>```

The conditional function for whether the button is disabled or not:

```<code>selectedObjects = [];
selectedFileCount() {
    return this.selectedObjects.length;
}
</code>```

When a file is selected, the following is triggered:

```<code>rowSelected($event) {
    this.selectedObjects.push($event.detail.row);
}
</code>```

I know that rowSelected works properly as I can console.log(selectedObjects.length) and get the correct length. I know that selectedFileCount() works because I can return boolean values which are reflected in whether the button is disabled or not.

It appears that once disabled.bind is set on DOM load, it cannot be changed. Is this assumption correct? What should I do?

答:
Aurelia treats any function calls in a binding as being pure function calls. Since your selectedFileCount function doesn't take any parameters, this means that Aurelia assumes the output value of the function will never change. That is why your disabled binding never changes.

My recommendation for how to fix it is to simply put the check in the binding.

```<code> <button id="downloadButton" disabled.bind="selectedObjects.length == 0"
         click.trigger="downloadFiles()" type="button">
    Download Selected
 </button>
</code>```

Body:
Below is the HTML snippet for a button that I would like to be disabled while no files, from a UI list of files, are selected:

<button id="downloadButton" disabled.bind="selectedFileCount() == 0" click.trigger="downloadFiles()" type="button">Download Selected</button>

The conditional function for whether the button is disabled or not:

selectedObjects = [];
selectedFileCount() {
    return this.selectedObjects.length;
}

When a file is selected, the following is triggered:

rowSelected($event) {
    this.selectedObjects.push($event.detail.row);
}

I know that rowSelected works properly as I can console.log(selectedObjects.length) and get the correct length. I know that selectedFileCount() works because I can return boolean values which are reflected in whether the button is disabled or not.

It appears that once disabled.bind is set on DOM load, it cannot be changed. Is this assumption correct? What should I do?

Body:
Aurelia treats any function calls in a binding as being pure function calls. Since your selectedFileCount function doesn't take any parameters, this means that Aurelia assumes the output value of the function will never change. That is why your disabled binding never changes.

My recommendation for how to fix it is to simply put the check in the binding.

 <button id="downloadButton" disabled.bind="selectedObjects.length == 0"
         click.trigger="downloadFiles()" type="button">
    Download Selected
 </button>


问:
Configuring Jackson for Spring Integration
Another question for the same project once mentioned in this question. We have now developed quite a few routes to serve a REST/JSON web service from a composite back-end.

The endpoint is an <int-http:inbound-gateway> that performs implicit JSON to object from the request and object to JSON for the response.
Now we really need to tune Jackson to solve a few issues with the JSON we deliver in the responses. Nothing fancy or unusual: mostly, serve dates as String instead of Timestamps, removing null attributes, registering the JSR-310 module.

For the other modules in the platform, we use Java DSL with a @Configuration class and a bean like this:

```<code>@Configuration
public class ControllerConfig {
  @Bean
  @Primary
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    return objectMapper;
  }
}
</code>```

But it seems to have no effect on Spring Integration. I have also tried Spring Boot configuration:

```<code>spring.jackson.default-property-inclusion=NON_NULL
</code>```

and it does not work either. I read very carefully this thread and my understanding from Artem Bilan's answer is that indeed, Spring Integration does not consider the Spring Boot configuration.

So... I'm feeling stupid: what is the canonical way of configuring Jackson globally for Spring Integration ?

jackson 2.8.7 / spring 4.3.7 / spring boot 1.5.2 / spring integration 4.3.8

答:
Correct. Spring Integration is a pure Spring Framework extension and it indeed knows nothing about conventional auto-configuration and injections.

So, what you have to do is don not forget to inject your objectMapper whenever it is necessary.

For example for that <int-http:inbound-gateway> you have to inject a proper set of the HttpMessageConverter. For example I see that Spring Boot provides the HttpMessageConverters bean. I believe that MappingJackson2HttpMessageConverter is injected to that one by the JacksonHttpMessageConvertersConfiguration. So, you can use it for your purpose like this:

```<code><int-http:inbound-gateway
         message-converters="#{messageConverters.converters}">
</code>```

Body:
Another question for the same project once mentioned in this question. We have now developed quite a few routes to serve a REST/JSON web service from a composite back-end.

The endpoint is an <int-http:inbound-gateway> that performs implicit JSON to object from the request and object to JSON for the response.
Now we really need to tune Jackson to solve a few issues with the JSON we deliver in the responses. Nothing fancy or unusual: mostly, serve dates as String instead of Timestamps, removing null attributes, registering the JSR-310 module.

For the other modules in the platform, we use Java DSL with a @Configuration class and a bean like this:

@Configuration
public class ControllerConfig {
  @Bean
  @Primary
  public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    return objectMapper;
  }
}

But it seems to have no effect on Spring Integration. I have also tried Spring Boot configuration:

spring.jackson.default-property-inclusion=NON_NULL

and it does not work either. I read very carefully this thread and my understanding from Artem Bilan's answer is that indeed, Spring Integration does not consider the Spring Boot configuration.

So... I'm feeling stupid: what is the canonical way of configuring Jackson globally for Spring Integration ?

jackson 2.8.7 / spring 4.3.7 / spring boot 1.5.2 / spring integration 4.3.8

Body:
Correct. Spring Integration is a pure Spring Framework extension and it indeed knows nothing about conventional auto-configuration and injections.

So, what you have to do is don not forget to inject your objectMapper whenever it is necessary.

For example for that <int-http:inbound-gateway> you have to inject a proper set of the HttpMessageConverter. For example I see that Spring Boot provides the HttpMessageConverters bean. I believe that MappingJackson2HttpMessageConverter is injected to that one by the JacksonHttpMessageConvertersConfiguration. So, you can use it for your purpose like this:

<int-http:inbound-gateway
         message-converters="#{messageConverters.converters}">


问:
Correct Way of Subscribing to Multiple Intervals of Differing Times
I am building my first Reactive.NET application and am struggling with how to manage two sets of observables.

To start with, I am polling a server in both sets.  I have two "rings" of time (faster and slower): one that fires every second and one that fires every 15 seconds.  I noticed that if the server takes a while to process one of the calls in one of the rings, it will immediately "catch up" and continuously fire the events once the call has completed (via timeout or otherwise).  So, if I am firing every second and there is a 30 second delay, the subscription will resume by firing 30 times once the delay has completed (assuming there are no other further delays).  This is not preferred as I want to keep calls to the server to a minimum, so sticking strictly per frame of time per ring.  That is, if there is a 30 second delay, I do not want to bombarded the server with calls once that delay has elapsed.

I have gotten around this with using Sample. And, actually, everything works well, except now when the application starts, there is a delay on the outer ring and I do not see any output until 15 seconds.  With the 1-second ring I got around this by using the StartsWith(-1) but I cannot seem to get around this with the outer (slower) ring.

Here is my code:

```<code>var fast = TimeSpan.FromSeconds(1);
var slow = TimeSpan.FromSeconds(15);
var application = Observable.Interval(fast)
                            .Sample(fast)
                            .StartWith(-1)
                            .Timestamp()
                            .Window(slow)
                            .Sample(slow)
                            .Subscribe(window =>
                                        {
                                            // Outer (slower) ring: ...

                                            window.Subscribe(x =>
                                                            {
                                                                // Inner (faster) ring: ...
                                                            });
                                        });
</code>```

So, really, the questions are:

Is this the correct/preferred way of creating two rings of subscribed time of differing intervals in Rx?  (This is important going forward as I can see having additional rings of time such as 30 seconds, 1 minute, 5 minutes, etc. and I want to be sure I get this right.)

If not, what is the best/preferred way doing this?

How do I ensure the outer ring fires immediately and does not take 15 seconds to fire on the first attempt?

EDIT:

Based on @yohanmishkin's answer, here is the code that I am using:

```<code>var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));

using (new CompositeDisposable(poll, lessFrequentPoll))
{
    // ...
}
</code>```

As mentioned in the answer there, I actually did use this when I first started Rx, but I was originally thinking (due to my primitive understanding of Rx) that for each subscription I would have to nest the using contexts and wanted to avoid that.  So, if I ended up with 5 "rings" of time, I would have 5 nested using's and that is not pretty to me.  Using the CompositeDisposable alleviates this.

答:
In this case you may want to create two separate observables and subscribe your application to them separately.

Here's an example:

```<code>var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));
</code>```

If you still want to combine the two intervals into a single stream Rx provides plenty of operators for doing so (Merge, Zip, CombineLatest...).

In your case you may want to check out CombineLatest or WithLatestFrom. You can see a visualization of how they work here (CombinedLatest) or here (WithLatestFrom).

An example might be using to WithLatestFrom to create a new stream that emits some object that combines the two interval observables that your application can then subscribe to.

```<code>var combinedPoll =
    poll
        .WithLatestFrom(
            lessFrequentPoll,
            (pollEvent, lessFrequentPollEvent) =>
                new CombinedEvent(pollEvent, lessFrequentEvent)
         );

combinedPoll.Subscribe(o =>
{
    application.UpdateFrequent(o.FrequentEvent);
    application.UpdateLessFrequent(o.LessFrequentEvent);
});
</code>```

Further reading

Combining sequences

Body:
I am building my first Reactive.NET application and am struggling with how to manage two sets of observables.

To start with, I am polling a server in both sets.  I have two "rings" of time (faster and slower): one that fires every second and one that fires every 15 seconds.  I noticed that if the server takes a while to process one of the calls in one of the rings, it will immediately "catch up" and continuously fire the events once the call has completed (via timeout or otherwise).  So, if I am firing every second and there is a 30 second delay, the subscription will resume by firing 30 times once the delay has completed (assuming there are no other further delays).  This is not preferred as I want to keep calls to the server to a minimum, so sticking strictly per frame of time per ring.  That is, if there is a 30 second delay, I do not want to bombarded the server with calls once that delay has elapsed.

I have gotten around this with using Sample. And, actually, everything works well, except now when the application starts, there is a delay on the outer ring and I do not see any output until 15 seconds.  With the 1-second ring I got around this by using the StartsWith(-1) but I cannot seem to get around this with the outer (slower) ring.

Here is my code:

var fast = TimeSpan.FromSeconds(1);
var slow = TimeSpan.FromSeconds(15);
var application = Observable.Interval(fast)
                            .Sample(fast)
                            .StartWith(-1)
                            .Timestamp()
                            .Window(slow)
                            .Sample(slow)
                            .Subscribe(window =>
                                        {
                                            // Outer (slower) ring: ...

                                            window.Subscribe(x =>
                                                            {
                                                                // Inner (faster) ring: ...
                                                            });
                                        });

So, really, the questions are:

Is this the correct/preferred way of creating two rings of subscribed time of differing intervals in Rx?  (This is important going forward as I can see having additional rings of time such as 30 seconds, 1 minute, 5 minutes, etc. and I want to be sure I get this right.)

If not, what is the best/preferred way doing this?

How do I ensure the outer ring fires immediately and does not take 15 seconds to fire on the first attempt?

EDIT:

Based on @yohanmishkin's answer, here is the code that I am using:

var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));

using (new CompositeDisposable(poll, lessFrequentPoll))
{
    // ...
}

As mentioned in the answer there, I actually did use this when I first started Rx, but I was originally thinking (due to my primitive understanding of Rx) that for each subscription I would have to nest the using contexts and wanted to avoid that.  So, if I ended up with 5 "rings" of time, I would have 5 nested using's and that is not pretty to me.  Using the CompositeDisposable alleviates this.

Body:
In this case you may want to create two separate observables and subscribe your application to them separately.

Here's an example:

var poll = Observable.Interval(TimeSpan.FromSeconds(1));
var lessFrequentPoll = Observable.Interval(TimeSpan.FromSeconds(15));

poll.Subscribe(o => application.UpdateFrequent(o));
lessFrequentPoll.Subscribe(o => application.UpdateLessFrequent(o));

If you still want to combine the two intervals into a single stream Rx provides plenty of operators for doing so (Merge, Zip, CombineLatest...).

In your case you may want to check out CombineLatest or WithLatestFrom. You can see a visualization of how they work here (CombinedLatest) or here (WithLatestFrom).

An example might be using to WithLatestFrom to create a new stream that emits some object that combines the two interval observables that your application can then subscribe to.

var combinedPoll =
    poll
        .WithLatestFrom(
            lessFrequentPoll,
            (pollEvent, lessFrequentPollEvent) =>
                new CombinedEvent(pollEvent, lessFrequentEvent)
         );

combinedPoll.Subscribe(o =>
{
    application.UpdateFrequent(o.FrequentEvent);
    application.UpdateLessFrequent(o.LessFrequentEvent);
});

Further reading

Combining sequences


答:
You could theoretically, in your view controller, save the constraints before removing the image view, like so:

```<code>let savedConstraints = view.constraints.filter { (constraint) -> Bool in
    constraint.firstItem as? UIView == myImageView || constraint.secondItem as? UIImageView == myImageView
}
</code>```

... where myImageView is the image view you're going to remove. The above checks reads the constraints connected to your view and returns the ones that are connected to your image view.

Then you could re-add these constraints when creating a new image view:

```<code>let myNewImageView = UIImageView()
view.addSubview(myNewImageView)
savedConstraints.forEach { (constraint) in
    view.addConstraint(NSLayoutConstraint(
            item: view,
            attribute: constraint.firstAttribute,
            relatedBy: constraint.relation,
            toItem: myNewImageView,
            attribute: constraint.secondAttribute,
            multiplier: constraint.multiplier,
            constant: constraint.constant))
}
</code>```

Although I agree with the commenters who recommended just hiding the image view.

Title: Remove IBOutlet programmatically that is set in interface builder and add it again with same constraints

Body:
Lets say I have a ViewController in a .nib file with an IBOutlet imageView as subView with constraints, the imageView is connected to the ViewController class associated with the nib file. Now I remove the imageView with the following code:

imageView.removeFromSuperview()

And later I want to add it again to the ViewController View with the same constraints as I set in the interface builder before I removed the imageView. My questions are:

Is it possible to do that in code without initialising the ViewController again?

If I add the imageView as SubView to the VC programmatically after I have removed it the constraints are no longer available. I would really like to skip setting the constraints again in code since they already exist in the interface builder, is that possible?

Body:
You could theoretically, in your view controller, save the constraints before removing the image view, like so:

let savedConstraints = view.constraints.filter { (constraint) -> Bool in
    constraint.firstItem as? UIView == myImageView || constraint.secondItem as? UIImageView == myImageView
}

... where myImageView is the image view you're going to remove. The above checks reads the constraints connected to your view and returns the ones that are connected to your image view.

Then you could re-add these constraints when creating a new image view:

let myNewImageView = UIImageView()
view.addSubview(myNewImageView)
savedConstraints.forEach { (constraint) in
    view.addConstraint(NSLayoutConstraint(
            item: view,
            attribute: constraint.firstAttribute,
            relatedBy: constraint.relation,
            toItem: myNewImageView,
            attribute: constraint.secondAttribute,
            multiplier: constraint.multiplier,
            constant: constraint.constant))
}

Although I agree with the commenters who recommended just hiding the image view.


问:
How to get the value from Mutator/setter using classes
Good Day! I am trying to get the value of num1 and num2 using (this. operator) but no matter what i do i just cant take the value of this two number and put it on to num3. Im currently new in java programming thats why i`m not familiar yet in the syntax.

My Code:

```<code>public class FinalProject
{

    public  Double num1;
    public  Double num2;
    public  Double num3;

public FinalProject ()
{

    this.num1 = 0.0;

    this.num2 = 0.0;

    this.num3 = 0.0;

}

public void setNum1(Double num1) //setter1
 {

    this.num1= num1;

  }

public void setNum2(Double num2) //setter2
 {

    this.num2= num2;

  }

public void setNum3(Double num3) //setter3
{

   value3 = this.value1 + this.value2;

    this.num3 = num3;

  }

--------------- // GETTER -----------------

public Double getNum1()
 {

    return this.num1;

  }

public Double getNum2()
 {

    return this.num2;

  }

public Double getNum3()
 {

    return this.num3;

  }

}
</code>```

------------------- // MY MAIN CLASS -----------------

```<code>package finalproject;

import java.util.Scanner;

public class FinalProjectMain {

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        FinalProject output1 = new FinalProject();//num1
        FinalProject output2 = new FinalProject();//num2
        FinalProject output3 = new FinalProject(); //num3

        System.out.print("Enter your 1st number: ");
        output1.setNum1(input.nextDouble());

        System.out.print("Enter your 2nd number: ");
        output2.setNum2(input.nextDouble());

        System.out.print("The sum of two number is: " + output3.getNum3());

    }
}
</code>```

答:
You really need to think about how you want setNum3 to behave. At its current state:

```<code>public void setNum3(Double num3) //setter3 {

    value3 = this.value1 + this.value2;

    this.num3 = num3;

}
</code>```

It does not compile. It seems like you are trying to assign the parameter to num3 while also adding up num1 and num2.

In my opinion, you don't need a setNum3 or a num3 field. Just put the logic of adding num1 and num2 in the getNum3 method:

```<code>public Double getNum3()
 {

    return this.num1 + this.num2;

  }
</code>```

Also, you should just create one instance of FinalProject in your main, like this:

```<code>Scanner input = new Scanner(System.in);

FinalProject output = new FinalProject();

System.out.print("Enter your 1st number: ");
output.setNum1(input.nextDouble());

System.out.print("Enter your 2nd number: ");
output.setNum2(input.nextDouble());

System.out.print("The sum of two number is: " + output.getNum3());
</code>```

Body:
Good Day! I am trying to get the value of num1 and num2 using (this. operator) but no matter what i do i just cant take the value of this two number and put it on to num3. Im currently new in java programming thats why i`m not familiar yet in the syntax.

My Code:

public class FinalProject
{

    public  Double num1;
    public  Double num2;
    public  Double num3;

public FinalProject ()
{

    this.num1 = 0.0;

    this.num2 = 0.0;

    this.num3 = 0.0;

}

public void setNum1(Double num1) //setter1
 {

    this.num1= num1;

  }

public void setNum2(Double num2) //setter2
 {

    this.num2= num2;

  }

public void setNum3(Double num3) //setter3
{

   value3 = this.value1 + this.value2;

    this.num3 = num3;

  }

--------------- // GETTER -----------------

public Double getNum1()
 {

    return this.num1;

  }

public Double getNum2()
 {

    return this.num2;

  }

public Double getNum3()
 {

    return this.num3;

  }

}

------------------- // MY MAIN CLASS -----------------

package finalproject;

import java.util.Scanner;

public class FinalProjectMain {

    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        FinalProject output1 = new FinalProject();//num1
        FinalProject output2 = new FinalProject();//num2
        FinalProject output3 = new FinalProject(); //num3

        System.out.print("Enter your 1st number: ");
        output1.setNum1(input.nextDouble());

        System.out.print("Enter your 2nd number: ");
        output2.setNum2(input.nextDouble());

        System.out.print("The sum of two number is: " + output3.getNum3());

    }
}

Body:
You really need to think about how you want setNum3 to behave. At its current state:

public void setNum3(Double num3) //setter3 {

    value3 = this.value1 + this.value2;

    this.num3 = num3;

}

It does not compile. It seems like you are trying to assign the parameter to num3 while also adding up num1 and num2.

In my opinion, you don't need a setNum3 or a num3 field. Just put the logic of adding num1 and num2 in the getNum3 method:

public Double getNum3()
 {

    return this.num1 + this.num2;

  }

Also, you should just create one instance of FinalProject in your main, like this:

Scanner input = new Scanner(System.in);

FinalProject output = new FinalProject();

System.out.print("Enter your 1st number: ");
output.setNum1(input.nextDouble());

System.out.print("Enter your 2nd number: ");
output.setNum2(input.nextDouble());

System.out.print("The sum of two number is: " + output.getNum3());


问:
SQL: Replace Some Strings with other String Values in One Column and Write to Temp Table
UPDATE: Followed syntax provided by forum answers ... hit errors

```<code>SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a
</code>```

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

```<code>SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a
</code>```

The error I received was: Incorrect syntax near the keyword 'CASE'

答:
There won't be ELSE and When together.. like you did  ELSE WHEN [COL] = 'Art'

```<code>SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             WHEN [COL] = 'Art' THEN 'Artwork'
             ELSE 'Some Default value'    -- or don't add ELSE if not required
        END
    FROM #test_a
</code>```

Here is a tutorial on using CASE in SQL

Body:
UPDATE: Followed syntax provided by forum answers ... hit errors

SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a

The error I received was: Incorrect syntax near the keyword 'CASE'

Body:
There won't be ELSE and When together.. like you did  ELSE WHEN [COL] = 'Art'

SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             WHEN [COL] = 'Art' THEN 'Artwork'
             ELSE 'Some Default value'    -- or don't add ELSE if not required
        END
    FROM #test_a

Here is a tutorial on using CASE in SQL


问:
Animated GIF, should start animating on Button click
I have a problem with making a gif animation playable on click. I found tutorials on how to insert a gif into an app, but all those gifs starts to animate immediately when you open the app, which I don't want.

I want my gif to start animating when I click on it.
I also want to make this gif as a button.. So when I click on this picture/gif it will start animating and it will also send an SMS to a specific number.

I will paste my code for button and my MainActivity code.

答:
What you can do is separate your GIF into PNG frames with a sequential naming convention, if you have too many frames you can use for loop and a string builder to generate your animation-list, something like this:

Split GIF into Frames - ezgif.com

Compile Java Online - compilejava.net

```<code>StringBuilder sBuilder = new StringBuilder();
for(int x = 0;x<=140;x++) {
  sBuilder.append("<item");
  sBuilder.append("\n");
  sBuilder.append("  android:duration=\"500\"");
  sBuilder.append("\n");
  sBuilder.append("  android:drawable=\"@drawable/ic_heart_"+ x + "\"/>");
  sBuilder.append("\n");
}
System.out.print(sBuilder);
</code>```

To create this animation_list_filling.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
    <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
                    android:oneshot="true">

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_1"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_2"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_3"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_4"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_5"/> // etc...

</animation-list>
</code>```

Setup the ImageView on your Activity XML

```<code><ImageView
    android:id="@+id/imageview_animation_list_filling"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/animation_list_filling"
    />
</code>```

Place this code on your onClickListener to start your GIF:

```<code>ImageView mImageViewFilling = (ImageView) findViewById(R.id.imageview_animation_list_filling);
((AnimationDrawable) mImageViewFilling.getBackground()).start();
</code>```

Hope it helps.

Body:
What you can do is separate your GIF into PNG frames with a sequential naming convention, if you have too many frames you can use for loop and a string builder to generate your animation-list, something like this:

Split GIF into Frames - ezgif.com

Compile Java Online - compilejava.net

StringBuilder sBuilder = new StringBuilder();
for(int x = 0;x<=140;x++) {
  sBuilder.append("<item");
  sBuilder.append("\n");
  sBuilder.append("  android:duration=\"500\"");
  sBuilder.append("\n");
  sBuilder.append("  android:drawable=\"@drawable/ic_heart_"+ x + "\"/>");
  sBuilder.append("\n");
}
System.out.print(sBuilder);

To create this animation_list_filling.xml:

<?xml version="1.0" encoding="utf-8"?>
    <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
                    android:oneshot="true">

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_1"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_2"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_3"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_4"/>

    <item
        android:duration="500"
        android:drawable="@drawable/ic_heart_5"/> // etc...

</animation-list>

Setup the ImageView on your Activity XML

<ImageView
    android:id="@+id/imageview_animation_list_filling"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/animation_list_filling"
    />

Place this code on your onClickListener to start your GIF:

ImageView mImageViewFilling = (ImageView) findViewById(R.id.imageview_animation_list_filling);
((AnimationDrawable) mImageViewFilling.getBackground()).start();

Hope it helps.


问:
PHP - Store a SELECT Query and use it inside a INSERT query
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

```<code>   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>
</code>```

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

答:
This error its because the function mysqli_fetch_field return a object, you maybe wants read http://php.net/manual/es/mysqli-result.fetch-field.php
and this function return info of each column.

change this:

```<code>    $value = mysqli_fetch_field($resulty);
    $orderid = $value->orderId;
</code>```

Maybe you need use: fetch_assoc

http://php.net/manual/es/mysqli-result.fetch-assoc.php

good luck

Body:
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

Body:
This error its because the function mysqli_fetch_field return a object, you maybe wants read http://php.net/manual/es/mysqli-result.fetch-field.php
and this function return info of each column.

change this:

    $value = mysqli_fetch_field($resulty);
    $orderid = $value->orderId;

Maybe you need use: fetch_assoc

http://php.net/manual/es/mysqli-result.fetch-assoc.php

good luck