问:
How to compare and sort the variables that include the name of the teams and the chance of goals in percent
I have a few variables. The first variable always contains the name of the football club, and the next one – the chance of a goal as a percentage.

Example:

a="Man City", b=45.55%, c="Barcelona", d=57.6%, e="Everton", f=38.53%; etc.

I need to compare the chances of goal among all the teams, and sort them in descending order, with an indication of which team this or that chance belongs to.

When I use alert() command, I want that the output be similar to:

```<code>1.Barcelona: Chance 57.6%
2.Man City: Chance 45.55%
3.Everton: Chance 38.53%
</code>```

答:
There may be a more optimal way to do this, but here is the solution I used:

Compose your given values into an Array

Separate the values into 2 separate Arrays based on whether even or not

Loop through one of the new arrays (assuming they are both the same length)

Create an Array of Objects with keys of city and chance

Sort the Array of Objects by chance value

Loop through the Array of Objects to output the desired results (I simplified the output considerably from a production version)

const a="Man City";
const b=45.55;
const c="Barcelona";
const d=57.6;
const e="Everton";
const f=38.53;

const vars = [a,b,c,d,e,f];
const city = [];
const chance = [];
const results = [];

vars.forEach((x,i) => {
  if (i % 2) {
    chance.push(x);
  } else {
    city.push(x);
  }
});

city.forEach((x,i) => {
  results.push({city: x, chance: chance[i]})
});

results.sort((a,b) => {
  if (a.chance > b.chance) {
    return -1;
  }
  if (a.chance  {document.write(
(i + 1) + '. ' + x.city + ': Chance ' + x.chance + '%' + '
'
)});```

Body:
I have a few variables. The first variable always contains the name of the football club, and the next one – the chance of a goal as a percentage.

Example:

a="Man City", b=45.55%, c="Barcelona", d=57.6%, e="Everton", f=38.53%; etc.

I need to compare the chances of goal among all the teams, and sort them in descending order, with an indication of which team this or that chance belongs to.

When I use alert() command, I want that the output be similar to:

1.Barcelona: Chance 57.6%
2.Man City: Chance 45.55%
3.Everton: Chance 38.53%

Body:
There may be a more optimal way to do this, but here is the solution I used:

Compose your given values into an Array

Separate the values into 2 separate Arrays based on whether even or not

Loop through one of the new arrays (assuming they are both the same length)

Create an Array of Objects with keys of city and chance

Sort the Array of Objects by chance value

Loop through the Array of Objects to output the desired results (I simplified the output considerably from a production version)

const a="Man City";
const b=45.55;
const c="Barcelona";
const d=57.6;
const e="Everton";
const f=38.53;

const vars = [a,b,c,d,e,f];
const city = [];
const chance = [];
const results = [];

vars.forEach((x,i) => {
  if (i % 2) {
    chance.push(x);
  } else {
    city.push(x);
  }
});

city.forEach((x,i) => {
  results.push({city: x, chance: chance[i]})
});

results.sort((a,b) => {
  if (a.chance > b.chance) {
    return -1;
  }
  if (a.chance < b.chance) {
   return 1;
  }

  return 0;
});

results.forEach((x,i) => {document.write(
(i + 1) + '. ' + x.city + ': Chance ' + x.chance + '%' + '<br>'
)});


来源: stackexchange

问:
Flutter debug Apk decompile to get the source code
I have lost the source code of my flutter application due to drive corruption, but I have my debug.apk in my android phone.
How can I decompile the Flutter apk to get source code?
I have tried decompiling it using decompilers but it is not giving my source code
as the Flutter source code is in Dart language.

答:
If your debug.apk is in debug mode then you can use apktool in order to extract the components of the apk (I'm using the word extracting since apk is a zip file).

Flutter, in debug mode, keeps the source code (with comments!) in the file kernel_blob.bin. Thus, using the following command should help you extract the code into a file:

```<code>strings /path/to/extracted/apk/assets/flutter_assets/kernel_blob.bin > extracted_code.dart
</code>```

Please, pay attention - You'll need to clean 'extracted_code.dart', from irrelevant/garbage strings.

Try to search strings like "dart", "import", "void" and other keywords in 'extracted_code.dart', it will help you find the code itself.

Here's an example from my Ubuntu:

If the apk is compiled in "release" mode, extracting the code will be much harder, since the code is compiled into isolate_snapshot_instr file, which is not a raw arm assembly, and is only deserialized using the Flutter engine in run-time. You can read more about it here

ContentLicense: CC BY-SA 4.0

Body:
If your debug.apk is in debug mode then you can use apktool in order to extract the components of the apk (I'm using the word extracting since apk is a zip file).

Flutter, in debug mode, keeps the source code (with comments!) in the file kernel_blob.bin. Thus, using the following command should help you extract the code into a file:

strings /path/to/extracted/apk/assets/flutter_assets/kernel_blob.bin > extracted_code.dart

Please, pay attention - You'll need to clean 'extracted_code.dart', from irrelevant/garbage strings.

Try to search strings like "dart", "import", "void" and other keywords in 'extracted_code.dart', it will help you find the code itself.

Here's an example from my Ubuntu:

If the apk is compiled in "release" mode, extracting the code will be much harder, since the code is compiled into isolate_snapshot_instr file, which is not a raw arm assembly, and is only deserialized using the Flutter engine in run-time. You can read more about it here


问:
Windows Registry Key Check Fails in C#
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }
```

I expect the result to be true but it returns false.

答:
it looks like you are checking the wrong thing. You ask if the registry key at that path is null, and if it is, then Java is installed. I believe that you want to check that the key is not null. If they key is not null, then the Java registry key was found, and hence Java is installed.

Also, I want to mention that you need to dispose the intermediary key in the event that it is found. So, your code should look like:

```<code>RegistryKey key = null;
try
{
  key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment\\");
  if (key != null)
  {
    return true;
  }
}
finally
{
  if (key != null)
  {
    key.Dispose();
  }
}
</code>```

Title: Windows Registry Key Check Fails in C#

Body:
I am doing a java installation + version check but the installation check is failing.

I tried changing JavaKey and when I added a key that includes a space in it, it fails and returns false.

        bool checkIfJavaInstalled()
        {
            string JavaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
            bool installed = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(JavaKey) == null;
            return installed;
        }

I expect the result to be true but it returns false.

Body:
it looks like you are checking the wrong thing. You ask if the registry key at that path is null, and if it is, then Java is installed. I believe that you want to check that the key is not null. If they key is not null, then the Java registry key was found, and hence Java is installed.

Also, I want to mention that you need to dispose the intermediary key in the event that it is found. So, your code should look like:

RegistryKey key = null;
try
{
  key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment\\");
  if (key != null)
  {
    return true;
  }
}
finally
{
  if (key != null)
  {
    key.Dispose();
  }
}


问:
Camouflage product id's on website
I'm currently building a retail e-shop for a jewellery manufacturer which also sells wholesale to other shops and I'm looking for an efficient way to "hide"/"camouflage" the product id's for all products so that other competitors wont be able to see the product's barcodes and find out that the manufacturer is doing direct sales at lower prices.

All products on the website have a 4-5 digit id which is also the name of the products' images, ie for Product #1234 image filename is 1234.jpg

One thought was to add a 3-digit random int before and after the product ID that would make it quite hard for someone to figure out the product id. Another thought would be to reverse the id's or perform some sort of scrambling. This would work fine for all the links within the site and all i'd have to do would be to strip off the first and last 3 digits off the product id's or de-scramble before using in the queries but what can I do when it comes to displaying product images? I don't want visitors to be able to see the filenames, that would completely blow the cover for a ll product id's.

Suggestions and ideas are very welcome.

答:
You shouldn't allow direct access to your images like that. Instead, use a php wrapper which translates your fake product id to the actual image file and return that.

Ie http://.../getimage.php?fakeid=1337 which translates that into the actual product id 123 and then readfile("/path/to/123.png");

ContentLicense: CC BY-SA 3.0

Title: Camouflage product id's on website


问:
Adding selfmade factor levels to ggplot legends
I have data of the following type:

```<code>df <- data.frame(A=runif(100),
                 B=rep(seq(1,50), each=2),
                 C=factor(c(rep(c("X1", "X2"), 50))))
</code>```

I then proceed to scatterplot A vs B and add a stat_smooth layer according to C.

```<code>p1 <- ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C))
</code>```

I however want to show the relation between B and A disregarding the grouping factor C.

```<code>p1 + stat_smooth(col="black")
</code>```

I would like to add this new, selfmade factor (X1+X2) to the legend. Is there a way to achieve this?

答:
You can try:</p>

```<code>ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C)) +

  scale_colour_manual(name="Line Color",
                      values=c(X1="red", X2="blue", "X1-X2"="black"),
                      limits = c("X1","X2","X1-X2")) +
  stat_smooth(col = "black")
</code>```

Body:
I have data of the following type:

df <- data.frame(A=runif(100),
                 B=rep(seq(1,50), each=2),
                 C=factor(c(rep(c("X1", "X2"), 50))))

I then proceed to scatterplot A vs B and add a stat_smooth layer according to C.

p1 <- ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C))

I however want to show the relation between B and A disregarding the grouping factor C.

p1 + stat_smooth(col="black")

I would like to add this new, selfmade factor (X1+X2) to the legend. Is there a way to achieve this?

Body:
You can try:

ggplot(df, aes(B,A)) +
  geom_point(aes(col=C)) +
  stat_smooth(aes(col=C)) +

  scale_colour_manual(name="Line Color",
                      values=c(X1="red", X2="blue", "X1-X2"="black"),
                      limits = c("X1","X2","X1-X2")) +
  stat_smooth(col = "black")


问:
Seperate AngularJS controller files with local HTML page
I am trying to run a local webpage with AngularJS with dynamically driven controllers.  I'd like a URL variable to drive which particular javascript file is loaded with data to drive my page.

HTML File

```<code><html>
    <head >
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js'></script>
        <script>
            var app = angular.module("myApp", []);
        </script>

        <script>
            var url = new URL(window.location.href);
            var t_var= url.searchParams.get("t_var");
            var x = document.createElement('script');
            x.src = t_var +'.js';
            document.getElementsByTagName("head")[0].appendChild(x);
        </script>
    </head>
    <body ng-app='myApp' ng-controller='Ctrl1'>
        {{sub1Variable}}
    </body>
</html>
</code>```

AngularJS controller

```<code>app.controller("Ctrl1", function($scope) {
    $scope.sub1Variable = 'sub1'
});
</code>```

I have been able to get this to work if I include the below tag in the HTML file.

```<code><script src="sub1.js"></script>
</code>```

I keep receiving an error that a controller with this name is not referenced.

答:
In principle what you are doing here should be fine. See below.

app.controller("Ctrl1", function($scope) {
    $scope.sub1Variable = 'sub1'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head >
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js'></script>
        <script>
            var app = angular.module("myApp", []);
        </script>
    </head>
    <body ng-app='myApp' ng-controller='Ctrl1'>
        {{sub1Variable}}
    </body>
</html></code>```

If you run that you should see 'sub1' in the output.

So, if you are receiving the error saying that your controller isn't registered then almost certainly the problem is you aren't loading the JavaScript file that contains your controller registration. Make sure the script that contains the app.controller... line is included through a

        {{sub1Variable}}

```

Body:
I am trying to run a local webpage with AngularJS with dynamically driven controllers.  I'd like a URL variable to drive which particular javascript file is loaded with data to drive my page.

HTML File

        {{sub1Variable}}

AngularJS controller

app.controller("Ctrl1", function($scope) {
    $scope.sub1Variable = 'sub1'
});

I have been able to get this to work if I include the below tag in the HTML file.

I keep receiving an error that a controller with this name is not referenced.

Body:
In principle what you are doing here should be fine. See below.

app.controller("Ctrl1", function($scope) {
    $scope.sub1Variable = 'sub1'
});

<html>
    <head >
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js'></script>
        <script>
            var app = angular.module("myApp", []);
        </script>
    </head>
    <body ng-app='myApp' ng-controller='Ctrl1'>
        {{sub1Variable}}
    </body>
</html>

If you run that you should see 'sub1' in the output.

So, if you are receiving the error saying that your controller isn't registered then almost certainly the problem is you aren't loading the JavaScript file that contains your controller registration. Make sure the script that contains the app.controller... line is included through a <script> element at some point after loading angular and registering the module.

(Remember the SO Snippet and CodePen etc will implicitly include the JavaScript for convenience, in real code we need to do it ourselves).

In fact, if this is just a quick local app maybe you can just include it in the same script element as the module registration, like so:

<html>
    <head >
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js'></script>
        <script>
            var app = angular.module("myApp", []);
            app.controller("Ctrl1", function($scope) {
                 $scope.sub1Variable = 'sub1'
            });
        </script>
    </head>
    <body ng-app='myApp' ng-controller='Ctrl1'>
        {{sub1Variable}}
    </body>
</html>


问:
Evaluate lazily with spring-data
I would like to have the roles set fetch lazily. Hibernate fetchType.Lazy doesn't work for this cases, where spring data is used. I 've been trying lots of possibilities like Entitygraph but none of them works on this, or I'm using them wrong.
I have the next classes:

A class User:

```<code>@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}
</code>```

A class Role:

```<code>    @Entity
    @JsonRootName(value = "roles")
    @Table(name = "web_roles", schema = "t_dw_comercial")
    public class Role {

       @Id
       private int roleId;

       private String roleName;

    }
</code>```

Service:

```<code> @Service
    public class UserService implements IUserService{

        @Autowired
        UserRepository repository;

        public User findUserByLdapId(String loginName) {

            return repository.findUserByLdapId(loginName);
        }
    }
</code>```

Repository:

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}
</code>```

Controller:

```<code>@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}
</code>```

So a json would looks like:

```<code>{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "roles":[]
    }
}
</code>```

Thanks in advance!

答:
It seems you're asking for two different things: how to fetch @OneToMany association lazily (which should work out of the box) and how to make your JSON look like the above (which has nothing to do with how your JPA entity fetching is configured).

If you serialize your entity using Jackson, by default all the fields will get serialized, including those that are fetched lazily. If the persistence context is still open when you begin to serialize the entities, Jackson will simply trigger lazy loading by accessing the property. As a result, regardless of whether you use FetchType.EAGER or FetchType.LAZY, roles will be included in the result (I assume it is the case, since you'd be getting a LazyInitializationException if the context was closed).

The solution is, simply, to tell Jackson to refrain from serializing roles using @JsonIgnore if you don't want the property in the result.

Title: Evaluate lazily with spring-data

Body:
I would like to have the roles set fetch lazily. Hibernate fetchType.Lazy doesn't work for this cases, where spring data is used. I 've been trying lots of possibilities like Entitygraph but none of them works on this, or I'm using them wrong.
I have the next classes:

A class User:

@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}

A class Role:

    @Entity
    @JsonRootName(value = "roles")
    @Table(name = "web_roles", schema = "t_dw_comercial")
    public class Role {

       @Id
       private int roleId;

       private String roleName;

    }

Service:

 @Service
    public class UserService implements IUserService{

        @Autowired
        UserRepository repository;

        public User findUserByLdapId(String loginName) {

            return repository.findUserByLdapId(loginName);
        }
    }

Repository:

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}

Controller:

@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}

So a json would looks like:

{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "roles":[]
    }
}

Thanks in advance!


问:
Error reading file share paths as arguments
I am receiving the following error when I execute the below script.

Test-Path : A positional parameter cannot be found that accepts
  argument 'input.dat'.

```<code>.\FL.ps1 \\flamingdev\analytics\source\INBOUND   \\flamingdev\analytics\source\OUTBOUND

[CmdletBinding()]
param (
  [string] $SrcFolder,
  [string] $FileListPath
)

$SrcFolder
$FileListPath

IF (Test-Path "$FileListPath"\input.dat) {
Remove-Item "$FileListPath"\input.dat
}

Get-ChildItem -File -Path "$SrcFolder"\Extract* | Select-Object - ExpandProperty Name | Add-Content -Path "$FileListPath"\input.dat
</code>```

答:
You meed to take "all path" in double quotes. Like this:</p>

```<code>IF (Test-Path "$FileListPath\input.dat") {
Remove-Item "$FileListPath\input.dat"
}
 Get-ChildItem -File -Path "$SrcFolder\Extract*" | Select-Object -ExpandProperty Name | Add-Content -Path "$FileListPath\input.dat"
</code>```

Body:
I am receiving the following error when I execute the below script.

Test-Path : A positional parameter cannot be found that accepts
  argument 'input.dat'.

.\FL.ps1 \\flamingdev\analytics\source\INBOUND   \\flamingdev\analytics\source\OUTBOUND

[CmdletBinding()]
param (
  [string] $SrcFolder,
  [string] $FileListPath
)

$SrcFolder
$FileListPath

IF (Test-Path "$FileListPath"\input.dat) {
Remove-Item "$FileListPath"\input.dat
}

Get-ChildItem -File -Path "$SrcFolder"\Extract* | Select-Object - ExpandProperty Name | Add-Content -Path "$FileListPath"\input.dat

Body:
You meed to take "all path" in double quotes. Like this:

IF (Test-Path "$FileListPath\input.dat") {
Remove-Item "$FileListPath\input.dat"
}
 Get-ChildItem -File -Path "$SrcFolder\Extract*" | Select-Object -ExpandProperty Name | Add-Content -Path "$FileListPath\input.dat"


问:
Refresh Header after Login in Angular2
So I have a header component that displays either the User's name or "Sign In" depending on whether they are logged in or not.  I also have a Login component that does all of the business logic of logging in.  They currently do not have a parent / child relationship.

When the User logs in, the header does not refresh or change unless a full page refresh is done in the browser.  I've been doing a lot of searching and reading online about different ways to do this.  ngOnChanges, NgZone, ApplicationRef, and ChangeDetectorRef seem to be the most popular.  I'm trying to implement this behavior in ChangeDetectorRef as this seems to be most relevant to my situation.  However, I can't seem to find actual examples of how to use this.

I've coded it up but it does not seem to do anything.  Any advice would be appreciated.  I'd even accept that I'm taking the wrong approach and need to use another solution besides ChangeDetectorRef.

LoginComponent

```<code>import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';

import { AuthenticationService } from '../service/authentication.service';

@Component({
    selector: 'login-component',
    templateUrl: './login.component.html'
})

export class LoginComponent implements OnInit {
    constructor(private router: Router,
                private authenticationService: AuthenticationService) { }

    ngOnInit() {
        // Resets the login service.
        // This is one of the events that should cause the refresh.
        this.authenticationService.logout();
    }

    login() {
        /*
        Authentication code
        This is the other event that should cause the refresh.
        */
    }
}
</code>```

HeaderComponent

```<code>import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';

import { Instance } from '../../entity/instance';

@Component({
    selector: 'header-component',
    templateUrl: './html/header.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class HeaderComponent {

    userName: string;

    constructor(private ref: ChangeDetectorRef) {
        this.ref.markForCheck();
    }

    ngOnInit(): void {
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));

        this.userName = currentUser && currentUser.full_name;

        if (!this.userName) {
            this.userName = "User Name";
        }
    }
}
</code>```

AppComponent

```<code>import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';

import { Instance } from './entity/instance';
import { InstanceService } from './service/instance.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class AppComponent implements OnInit {

    instances: Instance[];

    constructor(private instanceService: InstanceService) { }

    ngOnInit(): void {
    }
}
</code>```

app.component.html

```<code><header-component></header-component>

<router-outlet></router-outlet>
</code>```

答:
I am late here, but I am also trying to update my header component after login, I have followed your approach but it is not updating my Header component.

user.service.ts

```<code>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';

@Injectable()
export class UserService {
constructor(public router: Router) {}
public getLoggedInName = new Subject();

async storeData(data) {
    this.getLoggedInName.next(data);
    localStorage.setItem('userData', JSON.stringify(data));
    return this.router.navigate(['']); // after login we navigate to home component, but I want to display the email in header component
}

getData() {
   return JSON.parse(localStorage.getItem('userData'));
}

logOut() {
   localStorage.setItem('userData', '');
   localStorage.clear();
   return this.router.navigate(['']);
}
}
</code>```

login.component.ts

```<code>public socialSignIn(socialPlatform: string) {
      let socialPlatformProvider;
      if (socialPlatform === 'facebook') {
         socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
      } else if (socialPlatform === 'google') {
         socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
      }

      this.socialAuthService.signIn(socialPlatformProvider).then(userData => {
         this.apiConnection(userData);
      });
  }

  apiConnection(data){
      this.userPostData.email = data.email;
      this.userPostData.name = data.name;
      this.userPostData.provider = data.provider;
      this.userPostData.provider_id = data.id;
      this.userPostData.provider_pic = data.image;
      this.userPostData.token = data.token;
      this.user.storeData(data);

  }
</code>```

socialSignIn() method we call on click on facebook icon.

nav-menu.component.ts my header component where I am expecting my userData variable would have the logged in user details.

```<code>import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent implements OnInit {
  isExpanded = false;
  isLoggedIn = false;
  public userData: any;

  constructor(public user: UserService){
    this.setUserSessionData();
  }

  ngOnInit() {
    this.user.getLoggedInName.subscribe(name => this.userData = name);
 }

  public logOut(){
    debugger;
    this.user.logOut();
  }

  public setUserSessionData(){
    this.userData = this.user.getData();
    this.isLoggedIn = !this.userData;
  }
}
</code>```

my nav-menu.component.html where I will be showing the logged in user email.

```<code> <button class="nav-text" clrDropdownTrigger>
                {{userData?.email}}
                <clr-icon shape="caret down"></clr-icon>
 </button>
</code>```

Title: Refresh Header after Login in Angular2

Body:
So I have a header component that displays either the User's name or "Sign In" depending on whether they are logged in or not.  I also have a Login component that does all of the business logic of logging in.  They currently do not have a parent / child relationship.

When the User logs in, the header does not refresh or change unless a full page refresh is done in the browser.  I've been doing a lot of searching and reading online about different ways to do this.  ngOnChanges, NgZone, ApplicationRef, and ChangeDetectorRef seem to be the most popular.  I'm trying to implement this behavior in ChangeDetectorRef as this seems to be most relevant to my situation.  However, I can't seem to find actual examples of how to use this.

I've coded it up but it does not seem to do anything.  Any advice would be appreciated.  I'd even accept that I'm taking the wrong approach and need to use another solution besides ChangeDetectorRef.

LoginComponent

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';

import { AuthenticationService } from '../service/authentication.service';

@Component({
    selector: 'login-component',
    templateUrl: './login.component.html'
})

export class LoginComponent implements OnInit {
    constructor(private router: Router,
                private authenticationService: AuthenticationService) { }

    ngOnInit() {
        // Resets the login service.
        // This is one of the events that should cause the refresh.
        this.authenticationService.logout();
    }

    login() {
        /*
        Authentication code
        This is the other event that should cause the refresh.
        */
    }
}

HeaderComponent

import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';

import { Instance } from '../../entity/instance';

@Component({
    selector: 'header-component',
    templateUrl: './html/header.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class HeaderComponent {

    userName: string;

    constructor(private ref: ChangeDetectorRef) {
        this.ref.markForCheck();
    }

    ngOnInit(): void {
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));

        this.userName = currentUser && currentUser.full_name;

        if (!this.userName) {
            this.userName = "User Name";
        }
    }
}

AppComponent

import { ChangeDetectorRef, ChangeDetectionStrategy, Component, OnInit } from '@angular/core';

import { Instance } from './entity/instance';
import { InstanceService } from './service/instance.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

export class AppComponent implements OnInit {

    instances: Instance[];

    constructor(private instanceService: InstanceService) { }

    ngOnInit(): void {
    }
}

app.component.html

<router-outlet></router-outlet>

Body:
I am late here, but I am also trying to update my header component after login, I have followed your approach but it is not updating my Header component.

user.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';

@Injectable()
export class UserService {
constructor(public router: Router) {}
public getLoggedInName = new Subject();

async storeData(data) {
    this.getLoggedInName.next(data);
    localStorage.setItem('userData', JSON.stringify(data));
    return this.router.navigate(['']); // after login we navigate to home component, but I want to display the email in header component
}

getData() {
   return JSON.parse(localStorage.getItem('userData'));
}

logOut() {
   localStorage.setItem('userData', '');
   localStorage.clear();
   return this.router.navigate(['']);
}
}

login.component.ts

public socialSignIn(socialPlatform: string) {
      let socialPlatformProvider;
      if (socialPlatform === 'facebook') {
         socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
      } else if (socialPlatform === 'google') {
         socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
      }

      this.socialAuthService.signIn(socialPlatformProvider).then(userData => {
         this.apiConnection(userData);
      });
  }

  apiConnection(data){
      this.userPostData.email = data.email;
      this.userPostData.name = data.name;
      this.userPostData.provider = data.provider;
      this.userPostData.provider_id = data.id;
      this.userPostData.provider_pic = data.image;
      this.userPostData.token = data.token;
      this.user.storeData(data);

  }

socialSignIn() method we call on click on facebook icon.

nav-menu.component.ts my header component where I am expecting my userData variable would have the logged in user details.

import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent implements OnInit {
  isExpanded = false;
  isLoggedIn = false;
  public userData: any;

  constructor(public user: UserService){
    this.setUserSessionData();
  }

  ngOnInit() {
    this.user.getLoggedInName.subscribe(name => this.userData = name);
 }

  public logOut(){
    debugger;
    this.user.logOut();
  }

  public setUserSessionData(){
    this.userData = this.user.getData();
    this.isLoggedIn = !this.userData;
  }
}

my nav-menu.component.html where I will be showing the logged in user email.

 <button class="nav-text" clrDropdownTrigger>
                {{userData?.email}}
                <clr-icon shape="caret down"></clr-icon>
 </button>


问:
ggplot2: Add secondary x label (year below months)
My Problem is related to: Axis labels on two lines with nested x variables (year below months)

However, my data looks a little different.

```<code>library(dplyr)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
</code>```

I would like my line graph too look like this, but without the vertical line if possible:

答:
I can think of two ways to do this, each with their pros and cons:

Data prep:

```<code>library(dplyr)
library(tibble)
library(lubridate)
library(scales)
library(ggplot2)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
df$month <- rep(month.abb, 5, each=21)
df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5"), 1, each=252)

# We first create a "real" date variable with year, month and day. I've chosen to add
# "201" in from of your year, but it really doesn't matter in our case.
df <- df %>%
  group_by(year, month) %>%
  mutate(Date = as.Date(paste0("201", sub("^.+(\\d+)$", "\\1", year),
                               "-", month, "-", row_number()),
                        format = "%Y-%b-%d"))

# Since OP's daily values don't make up full months of data,
# we need this step to show missing data correctly.
df <- expand.grid(Date = seq.Date(from = min(df$Date), to = max(df$Date), by = "days")) %>%
  mutate(year = paste("Year", sub("^\\d{3}(\\d)", "\\1", format(Date, "%Y"))),
         month = format(Date, "%b")) %>%
  left_join(df)
</code>```

Note that I have used month.abb to replace the months provided by OP, since it looks like they are using a non-English locale.

1. Use facet_grid:

```<code>ggplot(df, aes(x = Date, y = value, group = year)) +
  geom_line() +
  facet_grid(. ~ year, scale = "free_x") +
  scale_x_date(labels = date_format("%b"), expand = c(0, 0)) +
  theme(panel.spacing.x = unit(0, "lines")) +
  ylim(c(0, 2.5))
</code>```

I've used expand in scale_x_date to prevent ggplot from adding spaces on both ends of each facet and panel.spacing.x to reduce the spacing between facets. The combination of these two gives us an illusion that the panels are connected, but they are not (the end of each facet does not connect to the beginning of the next even if there are no missing values)

2. Use geom_rect + geom_text:

```<code># Create labels
label_range <- df %>%
  group_by(year) %>%
  summarize(xmin = min(Date),
            xmax = max(Date),
            ymin = -0.5,
            ymax = ymin + 0.15)

ggplot(df) +
  geom_line(aes(x = Date, y = value)) +
  geom_rect(data = label_range, fill = "lightcoral", color = "#f2f2f2",
            aes(xmin = xmin, xmax = xmax,
                ymin = ymin, ymax = ymax,
                group = year)) +
  geom_text(data = label_range,
            aes(x = xmin + 365/2, y = ymin + 0.1,
                group = year, label = year)) +
  coord_cartesian(ylim = c(0, 2.5), clip = "off") +
  scale_x_date(labels = date_format("%b"),
               date_breaks = "1 month",
               expand = c(0.01, 0.01)) +
  theme_bw() +
  theme(plot.margin = unit(c(1,1,3,1), "lines"))
</code>```

This second method is more tedious, but our data will be treated as one continuous series.

Create label_range to determine the coordinates of the four corners of each geom_rect.

Using this dataset, I plotted the "facet boxes" using geom_rect and their labels using geom_text grouped by year.

We want the rectangles to be below the x-axis, so I used coord_cartesian to set the plot at a specific zoom, which prevents our rects from clipping off when we set it outside the plot.

plot.margin adds some spaces below the x-axis for our facet labels

Notice the gaps between Dec and Jan. They are caused by missing values, which is different than the gaps between Dec and Jan in the first method.

Body:
My Problem is related to: Axis labels on two lines with nested x variables (year below months)

However, my data looks a little different.

library(dplyr)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

I would like my line graph too look like this, but without the vertical line if possible:

Body:
I can think of two ways to do this, each with their pros and cons:

Data prep:

library(dplyr)
library(tibble)
library(lubridate)
library(scales)
library(ggplot2)

set.seed(122)
df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
df$month <- rep(month.abb, 5, each=21)
df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5"), 1, each=252)

# We first create a "real" date variable with year, month and day. I've chosen to add
# "201" in from of your year, but it really doesn't matter in our case.
df <- df %>%
  group_by(year, month) %>%
  mutate(Date = as.Date(paste0("201", sub("^.+(\\d+)$", "\\1", year),
                               "-", month, "-", row_number()),
                        format = "%Y-%b-%d"))

# Since OP's daily values don't make up full months of data,
# we need this step to show missing data correctly.
df <- expand.grid(Date = seq.Date(from = min(df$Date), to = max(df$Date), by = "days")) %>%
  mutate(year = paste("Year", sub("^\\d{3}(\\d)", "\\1", format(Date, "%Y"))),
         month = format(Date, "%b")) %>%
  left_join(df)

Note that I have used month.abb to replace the months provided by OP, since it looks like they are using a non-English locale.

1. Use facet_grid:

ggplot(df, aes(x = Date, y = value, group = year)) +
  geom_line() +
  facet_grid(. ~ year, scale = "free_x") +
  scale_x_date(labels = date_format("%b"), expand = c(0, 0)) +
  theme(panel.spacing.x = unit(0, "lines")) +
  ylim(c(0, 2.5))

I've used expand in scale_x_date to prevent ggplot from adding spaces on both ends of each facet and panel.spacing.x to reduce the spacing between facets. The combination of these two gives us an illusion that the panels are connected, but they are not (the end of each facet does not connect to the beginning of the next even if there are no missing values)

2. Use geom_rect + geom_text:

# Create labels
label_range <- df %>%
  group_by(year) %>%
  summarize(xmin = min(Date),
            xmax = max(Date),
            ymin = -0.5,
            ymax = ymin + 0.15)

ggplot(df) +
  geom_line(aes(x = Date, y = value)) +
  geom_rect(data = label_range, fill = "lightcoral", color = "#f2f2f2",
            aes(xmin = xmin, xmax = xmax,
                ymin = ymin, ymax = ymax,
                group = year)) +
  geom_text(data = label_range,
            aes(x = xmin + 365/2, y = ymin + 0.1,
                group = year, label = year)) +
  coord_cartesian(ylim = c(0, 2.5), clip = "off") +
  scale_x_date(labels = date_format("%b"),
               date_breaks = "1 month",
               expand = c(0.01, 0.01)) +
  theme_bw() +
  theme(plot.margin = unit(c(1,1,3,1), "lines"))

This second method is more tedious, but our data will be treated as one continuous series.

Create label_range to determine the coordinates of the four corners of each geom_rect.

Using this dataset, I plotted the "facet boxes" using geom_rect and their labels using geom_text grouped by year.

We want the rectangles to be below the x-axis, so I used coord_cartesian to set the plot at a specific zoom, which prevents our rects from clipping off when we set it outside the plot.

plot.margin adds some spaces below the x-axis for our facet labels

Notice the gaps between Dec and Jan. They are caused by missing values, which is different than the gaps between Dec and Jan in the first method.


问:
case class inheriting another class/trait
I want to have a case class extend a trait

Here are my requirements:

I need to use a case class for the child. This is a hard requirement because of scopt (https://github.com/scopt/scopt)

The parent needs to be a trait. Apologies for not being clear about it earlier

I want the attributes of the parent trait to be accessible to the child, and preferrably not have to specify them again when declaring the child case class. For example, if the parent trait is: trait ParentParams { var name: String = "Al" } then the child should not be case class ChildParams(id: String = "whatever", override val name: String = Parent.defaultName) extends Parent. I would prefer to have it as case class Child(id: String) extends Parent. However, when I try the second approach, I am not able to access the name field when I try to do a .copy() on a case class object. As a workaround I can mutate the value of the name attribute through childObj.name = "newName"

I should (hard requirement) be able to override the attribute values that the child object inherited from the parent. Right now this is possible because I have declared the parent attributes as a var instead of a val. However, ideally I would like to make it immutable and use the copy method for changing values instead.

This is what I have right now, but am unable to use the .copy() method to change the value of an inherited attribute.

```<code>package abcd.wxyz

import org.scalatest.{FlatSpec, Matchers}

trait ParentTrait {
  var name: String = "name"
}

case class TestParams(param1: String = "123") extends ParentTrait

class TestParamsSpec extends FlatSpec with Matchers {
  "TestParams" should "be able to access it's inherited attributes and modify them" in {

    val testParams = TestParams()
    testParams.name = "newName1"
    testParams.param1 should equal("123")
    testParams.name should equal("newName1")

    val modifiedTestParams = testParams.copy(name = "newName2") // cannot resolve symbol name
    modifiedTestParams.name should equal("newName2")

  }
}
</code>```

I get a "Cannot resolve symbol name" on .copy(name = "newName2") for the code above.

The reason behind having this inheritance is to have a function which accepts a Child object and expects it to have a "name" attribute defined. For example, consider a function which will append "Mr." or "Mrs." given a Child object having a name attribute.

Overall background of what is happening:
I am filling a config with command line input values (into a case class) using scopt. If no value is provided, a default is used for that attribute. By attribute I mean the data member inside the case class.
I have a function (let's call it dbReader) which accepts an object of the case class and uses it to establish a connection and read from a database. There are many different parameter case classes in my project and I want each of these parameters to implement a common DatabaseConnectionParameters trait so that the function dbReader can work regardless of which parameter case class is passed to it.

答:
In scala, a default value for a constructor is compiled as a function which evaluates in the context of the companion object, so

```<code>case class CaseClazz(foo: String = super.bar) extends Bar
</code>```

Compiles to something like (I'm not mangling the names in the interest of clarity):

```<code>class Bar { def bar: String = "whatevs" }

case class CaseClazz(foo: String = CaseClazz.defaultForFoo) extends Bar

object CaseClazz extends Function1[String, CaseClazz] {
  def defaultForFoo: String = super.bar
  def apply(foo: String = defaultForFoo): CaseClazz = new CaseClazz(foo)
}
</code>```

Which doesn't compile because super in the object is CaseClazz$, which doesn't define a bar method.

The clearest way to get the behavior you seek is IMO:

```<code>object Parent {
  val defaultName: String = "Al"
}

class Parent(val name: String = Parent.defaultName) { def parentBehavior: Unit = println("parent!") }

case class Child(id: String = "55", override val name: String = Parent.defaultName) extends Parent(name)
</code>```

Which allows:

```<code>scala> Child(id = "ego").parentBehavior
parent!

scala> Child(id = "ego").name
res12: String = Al

scala> Child().name
res13: String = Al

scala> Child().parentBehavior
parent!
</code>```

Body:
I want to have a case class extend a trait

Here are my requirements:

I need to use a case class for the child. This is a hard requirement because of scopt (https://github.com/scopt/scopt)

The parent needs to be a trait. Apologies for not being clear about it earlier

I want the attributes of the parent trait to be accessible to the child, and preferrably not have to specify them again when declaring the child case class. For example, if the parent trait is: trait ParentParams { var name: String = "Al" } then the child should not be case class ChildParams(id: String = "whatever", override val name: String = Parent.defaultName) extends Parent. I would prefer to have it as case class Child(id: String) extends Parent. However, when I try the second approach, I am not able to access the name field when I try to do a .copy() on a case class object. As a workaround I can mutate the value of the name attribute through childObj.name = "newName"

I should (hard requirement) be able to override the attribute values that the child object inherited from the parent. Right now this is possible because I have declared the parent attributes as a var instead of a val. However, ideally I would like to make it immutable and use the copy method for changing values instead.

This is what I have right now, but am unable to use the .copy() method to change the value of an inherited attribute.

package abcd.wxyz

import org.scalatest.{FlatSpec, Matchers}

trait ParentTrait {
  var name: String = "name"
}

case class TestParams(param1: String = "123") extends ParentTrait

class TestParamsSpec extends FlatSpec with Matchers {
  "TestParams" should "be able to access it's inherited attributes and modify them" in {

    val testParams = TestParams()
    testParams.name = "newName1"
    testParams.param1 should equal("123")
    testParams.name should equal("newName1")

    val modifiedTestParams = testParams.copy(name = "newName2") // cannot resolve symbol name
    modifiedTestParams.name should equal("newName2")

  }
}

I get a "Cannot resolve symbol name" on .copy(name = "newName2") for the code above.

The reason behind having this inheritance is to have a function which accepts a Child object and expects it to have a "name" attribute defined. For example, consider a function which will append "Mr." or "Mrs." given a Child object having a name attribute.

Overall background of what is happening:
I am filling a config with command line input values (into a case class) using scopt. If no value is provided, a default is used for that attribute. By attribute I mean the data member inside the case class.
I have a function (let's call it dbReader) which accepts an object of the case class and uses it to establish a connection and read from a database. There are many different parameter case classes in my project and I want each of these parameters to implement a common DatabaseConnectionParameters trait so that the function dbReader can work regardless of which parameter case class is passed to it.

Body:
In scala, a default value for a constructor is compiled as a function which evaluates in the context of the companion object, so

case class CaseClazz(foo: String = super.bar) extends Bar

Compiles to something like (I'm not mangling the names in the interest of clarity):

class Bar { def bar: String = "whatevs" }

case class CaseClazz(foo: String = CaseClazz.defaultForFoo) extends Bar

object CaseClazz extends Function1[String, CaseClazz] {
  def defaultForFoo: String = super.bar
  def apply(foo: String = defaultForFoo): CaseClazz = new CaseClazz(foo)
}

Which doesn't compile because super in the object is CaseClazz$, which doesn't define a bar method.

The clearest way to get the behavior you seek is IMO:

object Parent {
  val defaultName: String = "Al"
}

class Parent(val name: String = Parent.defaultName) { def parentBehavior: Unit = println("parent!") }

case class Child(id: String = "55", override val name: String = Parent.defaultName) extends Parent(name)

Which allows:

scala> Child(id = "ego").parentBehavior
parent!

scala> Child(id = "ego").name
res12: String = Al

scala> Child().name
res13: String = Al

scala> Child().parentBehavior
parent!


问:
Could reinterpret_cast turn an invalid pointer value into a valid one?
Consider this union:

```<code>union A{
  int a;
  struct{
    int b;
    } c;
  };
</code>```

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

```<code>A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)
</code>```

Trial 1

For the case below I think that since C++17, I also get an undefined behavior:

```<code>A x;
x.a=10;
auto p = &x.a; //(1)
x.c.b=12;      //(2)
*p+*p;         //(3) UB
</code>```

Let's consider [basic.type]/3:

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value ([conv.ptr]) for that type, or

an invalid pointer value.

Let's call this 4 pointer values categories as pointer value genre.

The value of a pointer may transition from of the above mentioned genre to an other, but the standard is not really explicit about that. Fill free to correct me if I am wrong. So I suppose that at (1) the value of p is a pointer to value. Then in (2) a life ends and the value of p becomes an invalid pointer value. So in (3) I get UB because I try to access the value of an object (a) out of its lifetime.

Trial 2

Now consider this weird code:

```<code>A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = reinterpret_cast<int*>(p); //(2')
*p+*p;                         //(3) UB?
</code>```

Could the reinterpret_cast<int*>(p) change the pointer value genre from invalid pointer value to a pointer to value.

reinterpret_cast<int*>(p) is defined to be equivalent to static_cast<int*>(static_cast<void*>(p)), so let's consider how is defined the static_cast from void* to int*, [expr.static.cast]/13:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

So in our case the original pointer pointed to the object a. So I suppose the reinterpret_cast will not help because a is not within its lifetime. Is my reading to strict? Could this code be well defined?

答:
Every version to date of the C and C++ Standards has been ambiguous or contradictory with regard to what can be done with addresses of union members.  The authors of the C Standard didn't want to require that compilers make pessimistic allowances for the possibility that functions might be invoked by constructs like:

```<code>someFunction(&myUnion.member1, &myUnion.member2);
</code>```

in cases where function would cause the value one member of myUnion would be changed between access made via the other.  While the ability to take union members' addresses would have been pretty useless if code couldn't do things like:

```<code>someFunction1(&myUnion.member1);
someFunction2(&myUnion.member2);
someFunction3(&myUnion.member1);
</code>```

the authors of the Standard expected that quality implementations intended for various purposes would process constructs that Undefined Behavior "in a documented fashion characteristic of the environment" when doing so would best serve those purposes, and thus thought that making support for such constructs be a quality-of-implementation issue would be simpler than trying to formulate precise rules for which patterns must be supported.  A compiler that generated code for the called functions in the second example without knowing their calling context wouldn't be able to interleave accesses performed by the two functions, and a quality compiler that expanded them inline while processing the above code would have no trouble noticing when each pointer was derived from myUnion.

The authors of the C89 Standard didn't think it necessary to define precise rules for how pointers to union members behave, because they thought compiler writers' desire to produce quality implementations would drive them to handle appropriate cases sensibly even without such rules.  Unfortunately, some compiler writers were too lazy to handle cases like the second example above, and rather than recognizing that there was never any reason for quality compilers to be incapable of handling such cases, the authors of later C and C++ Standards have bent over backward to come up with weirdly contorted, ambiguous, and contradictory rules that justify such compiler behavior.

As a result, the address-of operator should only be regarded as meaningfully applicable to union members in cases where the resulting pointer will be used for accessing individual bytes of storage, either using character-types directly, or passing to functions like memcpy that are defined in such fashion.  Unless or until there's a major revamp of the Standard, or an appendix that describes means by which implementations can offer optional guarantees beyond what the Standard requires, it would be best to pretend that union members are--like bitfields--lvalues that don't have addresses.

Body:
Consider this union:

union A{
  int a;
  struct{
    int b;
    } c;
  };

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)

Trial 1

For the case below I think that since C++17, I also get an undefined behavior:

A x;
x.a=10;
auto p = &x.a; //(1)
x.c.b=12;      //(2)
*p+*p;         //(3) UB

Let's consider [basic.type]/3:

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value ([conv.ptr]) for that type, or

an invalid pointer value.

Let's call this 4 pointer values categories as pointer value genre.

The value of a pointer may transition from of the above mentioned genre to an other, but the standard is not really explicit about that. Fill free to correct me if I am wrong. So I suppose that at (1) the value of p is a pointer to value. Then in (2) a life ends and the value of p becomes an invalid pointer value. So in (3) I get UB because I try to access the value of an object (a) out of its lifetime.

Trial 2

Now consider this weird code:

A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = reinterpret_cast<int*>(p); //(2')
*p+*p;                         //(3) UB?

Could the reinterpret_cast<int*>(p) change the pointer value genre from invalid pointer value to a pointer to value.

reinterpret_cast<int*>(p) is defined to be equivalent to static_cast<int*>(static_cast<void*>(p)), so let's consider how is defined the static_cast from void* to int*, [expr.static.cast]/13:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

So in our case the original pointer pointed to the object a. So I suppose the reinterpret_cast will not help because a is not within its lifetime. Is my reading to strict? Could this code be well defined?

Body:
Every version to date of the C and C++ Standards has been ambiguous or contradictory with regard to what can be done with addresses of union members.  The authors of the C Standard didn't want to require that compilers make pessimistic allowances for the possibility that functions might be invoked by constructs like:

someFunction(&myUnion.member1, &myUnion.member2);

in cases where function would cause the value one member of myUnion would be changed between access made via the other.  While the ability to take union members' addresses would have been pretty useless if code couldn't do things like:

someFunction1(&myUnion.member1);
someFunction2(&myUnion.member2);
someFunction3(&myUnion.member1);

the authors of the Standard expected that quality implementations intended for various purposes would process constructs that Undefined Behavior "in a documented fashion characteristic of the environment" when doing so would best serve those purposes, and thus thought that making support for such constructs be a quality-of-implementation issue would be simpler than trying to formulate precise rules for which patterns must be supported.  A compiler that generated code for the called functions in the second example without knowing their calling context wouldn't be able to interleave accesses performed by the two functions, and a quality compiler that expanded them inline while processing the above code would have no trouble noticing when each pointer was derived from myUnion.

The authors of the C89 Standard didn't think it necessary to define precise rules for how pointers to union members behave, because they thought compiler writers' desire to produce quality implementations would drive them to handle appropriate cases sensibly even without such rules.  Unfortunately, some compiler writers were too lazy to handle cases like the second example above, and rather than recognizing that there was never any reason for quality compilers to be incapable of handling such cases, the authors of later C and C++ Standards have bent over backward to come up with weirdly contorted, ambiguous, and contradictory rules that justify such compiler behavior.

As a result, the address-of operator should only be regarded as meaningfully applicable to union members in cases where the resulting pointer will be used for accessing individual bytes of storage, either using character-types directly, or passing to functions like memcpy that are defined in such fashion.  Unless or until there's a major revamp of the Standard, or an appendix that describes means by which implementations can offer optional guarantees beyond what the Standard requires, it would be best to pretend that union members are--like bitfields--lvalues that don't have addresses.


问:
Server Architecture Setup, what type of services should I use?
Let's start with some backstory, I'm not an experience coder at all. I know some HTML & CSS and some simple python, some fundamentals you know. I have decided to start a project to get more familiar with Web Server building. So let me tell what I need help with, I don't know what types of systems I should use, and what system does what thing. So I need kinda of a push in the right direction I should go.

This is how I want my server setup.

Front-End and Back-End needs to separate.

Front-End is supposed to be my personal website that everyone can see but with an login function to control some back-end, like hangfire processing service, or If I just wanna setup some front end stuff that requires to be logged in to see.

I want all my stuff separate through containers which I guess Docker compose will do.

Back-End I want to be able to upload web applications that either I can run through my login function or if I wanna publish my work to anyone through my front-end.

Thats kinda it. I know its alot, but I also wanna say that all I really need help with is like a simple simple list of services to use, like this for example. (Examples are like NGINX, Docker, NodeJs, Kubernetes etc, etc)

Frontend = ?

Login & Auth server= ? (Auth I guess Jws auth server?)

Container = ?

Backend = ?

Frontend & Backend Communicator = ?

MySQL database for login = ?

I would assume that alot of microservices will be involved.

If you have any question feel to ask me. I tried my best explaining my situation, i've tried googling alot. I also know that there is alot alot of work ahead of me, this is project that I will try to finish within 1-3 years honestly, since there is most likely going to involve learning a couple of programming language.

I havent really tried anything since I'm really stuck.

答:
This is what we do in our projects:

we containerize our modules (api, db, ui) and use nginx as gateway between front-end and back-end. nginx rewrite requests based on addresses and point user request to docker-containers which will handle it. this way our structure is not visible to normal users. nginx has also another duty, it will serve front-end files.


问:
Conditional on non-instantiated variable
I am new to Bash scripting, having a lot more experience with C-type languages. I have written a few scripts with a conditional that checks the value of a non-instantiated variable and if it doesn't exist or match a value sets the variable. On top of that the whole thing is in a for loop. Something like this:

```<code>for i in ${!my_array[@]}; do
   if [ "${my_array[i]}" = true ]
   then
      #do something
   else
      my_array[i]=true;
   fi
done
</code>```

This would fail through a null pointer in Java since my_array[i] is not instantiated until after it is checked. Is this good practice in Bash? My script is working the way I designed, but I have learned that just because a kluge works now doesn't mean it will work in the future.

Thanks!

答:
By default, referencing undefined (or "unset") variable names in shell scripts just gives the empty string. But is an exception: if the shell is run with the -u option or set -u has been run in it, expansions of unset variables are treated as errors and (if the shell is not interactive) cause the shell to exit. Bash applies this principle to array elements as well:

```<code>$ array=(zero one two)
$ echo "${array[3]}"

$ echo "array[3] = '${array[3]}'"
array[3] = ''
$ set -u
$ echo "array[3] = '${array[3]}'"
-bash: array[3]: unbound variable
</code>```

There are also modifiers you can use to control what expansions do if a variable (or array element) is undefined and/or empty (defined as the empty string):

```<code>$ array=(zero one '')
$ echo "array[2] is ${array[2]-unset}, array[3] is ${array[3]-unset}"
array[2] is , array[3] is unset
$ echo "array[2] is ${array[2]:-unset or empty}, array[3] is ${array[3]:-unset or empty}"
array[2] is unset or empty, array[3] is unset or empty
</code>```

There are a bunch of other variants, see the POSIX shell syntax standard, section 2.6.2 (Parameter Expansion).

BTW, you do need to use curly braces (as I did above) around anything other than a plain variable reference. $name[2] is a reference to the plain variable name (or element 0 if it's an array), followed by the string "[2]"; ${name[2]}, on the other hand, is a reference to element 2 of the array name. Also, you pretty much always want to wrap variable references in double-quotes (or include them in double-quoted strings), to prevent the shell from "helpfully" splitting them into words and/or expanding them into lists of matching files. For example, this test:

```<code>if [ $my_array[i] = true ]
</code>```

is (mostly) equivalent to:

```<code>if [ ${my_array[0]}[i] = true ]
</code>```

...which isn't what you want at all. But this one:

```<code>if [ ${my_array[i]} = true ]
</code>```

still doesn't work, because if my_array[i] is unset (or empty) it'll expand to the equivalent of:

```<code>if [ = true ]
</code>```

...which is bad test expression syntax. You want this:

```<code>if [ "${my_array[i]}" = true ]
</code>```

Body:
I am new to Bash scripting, having a lot more experience with C-type languages. I have written a few scripts with a conditional that checks the value of a non-instantiated variable and if it doesn't exist or match a value sets the variable. On top of that the whole thing is in a for loop. Something like this:

for i in ${!my_array[@]}; do
   if [ "${my_array[i]}" = true ]
   then
      #do something
   else
      my_array[i]=true;
   fi
done

This would fail through a null pointer in Java since my_array[i] is not instantiated until after it is checked. Is this good practice in Bash? My script is working the way I designed, but I have learned that just because a kluge works now doesn't mean it will work in the future.

Thanks!

Body:
By default, referencing undefined (or "unset") variable names in shell scripts just gives the empty string. But is an exception: if the shell is run with the -u option or set -u has been run in it, expansions of unset variables are treated as errors and (if the shell is not interactive) cause the shell to exit. Bash applies this principle to array elements as well:

$ array=(zero one two)
$ echo "${array[3]}"

$ echo "array[3] = '${array[3]}'"
array[3] = ''
$ set -u
$ echo "array[3] = '${array[3]}'"
-bash: array[3]: unbound variable

There are also modifiers you can use to control what expansions do if a variable (or array element) is undefined and/or empty (defined as the empty string):

$ array=(zero one '')
$ echo "array[2] is ${array[2]-unset}, array[3] is ${array[3]-unset}"
array[2] is , array[3] is unset
$ echo "array[2] is ${array[2]:-unset or empty}, array[3] is ${array[3]:-unset or empty}"
array[2] is unset or empty, array[3] is unset or empty

There are a bunch of other variants, see the POSIX shell syntax standard, section 2.6.2 (Parameter Expansion).

BTW, you do need to use curly braces (as I did above) around anything other than a plain variable reference. $name[2] is a reference to the plain variable name (or element 0 if it's an array), followed by the string "[2]"; ${name[2]}, on the other hand, is a reference to element 2 of the array name. Also, you pretty much always want to wrap variable references in double-quotes (or include them in double-quoted strings), to prevent the shell from "helpfully" splitting them into words and/or expanding them into lists of matching files. For example, this test:

if [ $my_array[i] = true ]

is (mostly) equivalent to:

if [ ${my_array[0]}[i] = true ]

...which isn't what you want at all. But this one:

if [ ${my_array[i]} = true ]

still doesn't work, because if my_array[i] is unset (or empty) it'll expand to the equivalent of:

if [ = true ]

...which is bad test expression syntax. You want this:

if [ "${my_array[i]}" = true ]


问:
How to hide/show HTML table rows at an interval
I am working on HTML tables. Here I have made a table and split into four columns to show up on a display screen, the table is fully dynamic.

Now what I have to do is to show 5 rows at a time on the screen. I am using CSS to do that. What I am doing is creating table in one go and populating the first 5 rows at once; then after 5 seconds that content gets refreshed and I have to show next five rows this will go on until the all the data loads

What I have tried

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("
", {
      "class": "table"
    }),

    $tb = $("
"),
    $trh = $("
");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("
", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden {
  display: none;
}</code>```

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

```

When I am loading the page it is loading 5 rows which is perfect, but after 5 seconds next five rows are rendering but first five are not hiding.

答:
You need to track which rows have already been shown. So, create a new CSS class which is different from "hidden", but also uses display: none. Here I've used "already-shown".

On each interval, apply that class to any rows that are not hidden and not already shown.

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  // Any TRs that are not hidden and not already shown get "already-shown" applied
  $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
  // Then your previous code
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("
", {
      "class": "table"
    }),

    $tb = $("
"),
    $trh = $("
");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("
", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

/* added .already-shown to have the same properties as hidden */
.hidden,
.already-shown {
  display: none;
}</code>```

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

```

Body:
I am working on HTML tables. Here I have made a table and split into four columns to show up on a display screen, the table is fully dynamic.

Now what I have to do is to show 5 rows at a time on the screen. I am using CSS to do that. What I am doing is creating table in one go and populating the first 5 rows at once; then after 5 seconds that content gets refreshed and I have to show next five rows this will go on until the all the data loads

What I have tried

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("
", {
      "class": "table"
    }),

    $tb = $("
"),
    $trh = $("
");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("
", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}

tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden {
  display: none;
}

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

When I am loading the page it is loading 5 rows which is perfect, but after 5 seconds next five rows are rendering but first five are not hiding.

Body:
You need to track which rows have already been shown. So, create a new CSS class which is different from "hidden", but also uses display: none. Here I've used "already-shown".

On each interval, apply that class to any rows that are not hidden and not already shown.

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  // Any TRs that are not hidden and not already shown get "already-shown" applied
  $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
  // Then your previous code
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("<table />", {
      "class": "table"
    }),

    $tb = $("<tbody/>"),
    $trh = $("<tr/>");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("<tr/>", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("<td/>", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}

tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

/* added .already-shown to have the same properties as hidden */
.hidden,
.already-shown {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div id="DisplayTable">
</div>