问:
PLS HELP ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'r2' Error: Cannot match any routes. URL Segment: 'r2'
Need to Fix this errror, I dont know what to do my syntax is not wrong but if i run it displays the error

my app-routing module

```<code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [

  { path: 'recipes',
  children: [
    {
      path: '',
      loadChildren:
      './recipes/recipes.module#RecipesPageModule'
    },
    {
      path: ':recipeId',
      loadChildren:
      './recipes/recipe-detail/recipe-detail.module#RecipeDetailPageModule'
    }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

</code>```

my recipe-service.ts

```<code>import { Injectable } from '@angular/core';
import { Recipe } from './recipe.model';

@Injectable({
  providedIn: 'root'
})
export class RecipesService {

  private recipes: Recipe[] = [
    {
      id: 'r1',
      title: 'Smoked Fish',
// tslint:disable-next-line: max-line-length
      imageUrl: '../assets/img/sugba.jpg',
      ingredients: ['Fish', 'Salt', 'Lemon Grass']
    },
    {
      id: 'r2',
      title: 'Raw Fish',
// tslint:disable-next-line: max-line-length
      imageUrl: '../assets/img/rawfish.jpg',
      ingredients: ['Fish', 'Salt', 'Onion']
    },
  ];

  constructor() { }
  getAllRecipes(){
    return [...this.recipes];
  }
  getRecipe(recipeId: string){
    return {...this.recipes.find(recipe => {
      return recipe.id === recipeId;
    })};
  }
}

</code>```

my recipes.page.html

```<code><ion-header>
  <ion-toolbar>
    <ion-title color="primary">recipes</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
<ion-list>
  <ion-item *ngFor="let recipe of recipes" [routerLink]="['/', recipe.id]">
    <ion-avatar>
      <ion-img [src] = "recipe.imageUrl">

      </ion-img>
    </ion-avatar>
    <ion-label>
      {{recipe.title}}
    </ion-label>
  </ion-item>
</ion-list>
</ion-content>

</code>```

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'r2'
Error: Cannot match any routes. URL Segment: 'r2'

答:
```<code><ion-item *ngFor="let recipe of recipes" [routerLink]="['/', recipe.id]">
</code>```

[routerLink]="['/', recipe.id]" means you're redirecting to the root route. But your expected route is a child of the route.

Use this instead :

```<code>[routerLink]="recipe.id"
</code>```

Body:
Need to Fix this errror, I dont know what to do my syntax is not wrong but if i run it displays the error

my app-routing module

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [

  { path: 'recipes',
  children: [
    {
      path: '',
      loadChildren:
      './recipes/recipes.module#RecipesPageModule'
    },
    {
      path: ':recipeId',
      loadChildren:
      './recipes/recipe-detail/recipe-detail.module#RecipeDetailPageModule'
    }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

my recipe-service.ts

import { Injectable } from '@angular/core';
import { Recipe } from './recipe.model';

@Injectable({
  providedIn: 'root'
})
export class RecipesService {

  private recipes: Recipe[] = [
    {
      id: 'r1',
      title: 'Smoked Fish',
// tslint:disable-next-line: max-line-length
      imageUrl: '../assets/img/sugba.jpg',
      ingredients: ['Fish', 'Salt', 'Lemon Grass']
    },
    {
      id: 'r2',
      title: 'Raw Fish',
// tslint:disable-next-line: max-line-length
      imageUrl: '../assets/img/rawfish.jpg',
      ingredients: ['Fish', 'Salt', 'Onion']
    },
  ];

  constructor() { }
  getAllRecipes(){
    return [...this.recipes];
  }
  getRecipe(recipeId: string){
    return {...this.recipes.find(recipe => {
      return recipe.id === recipeId;
    })};
  }
}

my recipes.page.html

<ion-header>
  <ion-toolbar>
    <ion-title color="primary">recipes</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
<ion-list>
  <ion-item *ngFor="let recipe of recipes" [routerLink]="['/', recipe.id]">
    <ion-avatar>
      <ion-img [src] = "recipe.imageUrl">

      </ion-img>
    </ion-avatar>
    <ion-label>
      {{recipe.title}}
    </ion-label>
  </ion-item>
</ion-list>
</ion-content>

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'r2'
Error: Cannot match any routes. URL Segment: 'r2'

Body:
<ion-item *ngFor="let recipe of recipes" [routerLink]="['/', recipe.id]">

[routerLink]="['/', recipe.id]" means you're redirecting to the root route. But your expected route is a child of the route.

Use this instead :

[routerLink]="recipe.id"


来源: stackexchange

问:
VBConsole - Transfer Result from Query to Batch Script and Run the batch file
I have a loader to load data automatically which run using script (the loader containing the script named was batchautoload.cmd).

```<code>cd C:\file\loader\
C:\file\loader\load.exe /appID=1234 /username=admin /process="load" /initialDate=T1 /finalDate=T2
</code>```

I have a query to determine in which there is no data loaded using above process due to failure or etc as below.

declare @initdate as varchar(20)
declare @lastdate as varchar(20)
declare @location as varchar(20)

set @initdate = CONVERT(date,GETDATE()-1);
set @lastdate = CONVERT(date,GETDATE());
set @location = 'xxxx%'

;with q(a, c) as
(
    select MIN(date), MAX(date)
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
    union all
    select DATEADD(hour,1,a), c
    from q
    where a < c
)
select *
from q
where a not in
(
    select date
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
)
order by a asc
OPTION (MAXRECURSION 0)
"
```

<p>Now, my question is, is it possible to somehow transfer results from query to script where the script "/initialdate=queryresulttime /finaldate=queryresulttime+1"?</p>

<p>I have some general idea on using VB console, where:</p>

<ol>
<li>my console will run query from DB</li>
<li>transfer result query to script (stuck in here)</li>
<li>will automatically run the script created from step #2.</li>
</ol>

<p>Step #1</p>

<pre class="lang-vb prettyprint-override"><code>Module Module1
    Dim sqCon As New SqlClient.SqlConnection("Server=10.10.111.11;Database=DataBaseMain1;Connection Timeout=50;Trusted_Connection=Yes;")
    Dim sqCmd As New SqlClient.SqlCommand
    Dim sdrRow As SqlClient.SqlDataReader

    Sub Main()
        sqCmd.Connection = sqCon
        sqCmd.CommandText =
            "
            declare @initdate as varchar(20)
            declare @lastdate as varchar(20)
            declare @location as varchar(20)

            set @initdate = CONVERT(date,GETDATE()-1);
            set @lastdate = CONVERT(date,GETDATE());
            set @location = 'xxxx%'

            ;with q(a, c) as
            (
            select MIN(date), MAX(date)
            from Table_Loader
            where nameplace like @location
            and date >= @initdate
            and date <= @lastdate
            union all
            select DATEADD(hour,1,a), c
            from q
            where a < c
            )
            select *
            from q
            where a not in
            (
                select date
                from Table_Loader
                where nameplace like @location
                and date >= @initdate
                and date <= @lastdate
            )
            order by a asc
            OPTION (MAXRECURSION 0)
            "
        sqCon.Open()
        sqCmd.ExecuteNonQuery()
        sdrRow = sqCmd.ExecuteReader()

        For Each itm In sdrRow
            Dim column0 As String = sdrRow.GetValue(0)
            MsgBox(column0)
        Next

        sdrRow.Close()
        sqCon.Close()
    End Sub

End Module
</code>```

Now I can generate the process #1 but not #2 and #3. Since the data will be used in script, I am thinking of creating temporary file of batch (appear when only this console running, deleted after the console finished process). Since I don't want to create many file from the console.

I am new in VB console thus limit my idea to get this solved. I heard about "pipe" but I do not know on how to do that. I am still thinking on continuing For Each loop or For loop, but am stuck on this. Please advise me. Just to inform, I am planning to implement this console to run on daily-basis.

答:
I think the best solution for you is to write a little winforms application that runs forever until closed and which contains a big multiline text control to log to, and a timer to check when an import is due and which calls the loader.exe to do it. (That assumes that loader.exe is a third party tool and not written by you, otherwise just implement the code to import within the same application - and also assuming that this import does not need to run unattended, otherwise a windows service would be the right choice).

The timer event waits until the process ends, and if the import is not successful sleeps 30 seconds and tries again, logging everything to screen.

Or why does step #2 fail sometimes?

ContentLicense: CC BY-SA 4.0

Body:
I have a loader to load data automatically which run using script (the loader containing the script named was batchautoload.cmd).

cd C:\file\loader\
C:\file\loader\load.exe /appID=1234 /username=admin /process="load" /initialDate=T1 /finalDate=T2

I have a query to determine in which there is no data loaded using above process due to failure or etc as below.

declare @initdate as varchar(20)
declare @lastdate as varchar(20)
declare @location as varchar(20)

set @initdate = CONVERT(date,GETDATE()-1);
set @lastdate = CONVERT(date,GETDATE());
set @location = 'xxxx%'

;with q(a, c) as
(
    select MIN(date), MAX(date)
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
    union all
    select DATEADD(hour,1,a), c
    from q
    where a < c
)
select *
from q
where a not in
(
    select date
    from Table_Loader
    where nameplace like @location
    and date >= @initdate
    and date <= @lastdate
)
order by a asc
OPTION (MAXRECURSION 0)
"

Now, my question is, is it possible to somehow transfer results from query to script where the script "/initialdate=queryresulttime /finaldate=queryresulttime+1"?

I have some general idea on using VB console, where:

my console will run query from DB

transfer result query to script (stuck in here)

will automatically run the script created from step #2.

Step #1

Module Module1
    Dim sqCon As New SqlClient.SqlConnection("Server=10.10.111.11;Database=DataBaseMain1;Connection Timeout=50;Trusted_Connection=Yes;")
    Dim sqCmd As New SqlClient.SqlCommand
    Dim sdrRow As SqlClient.SqlDataReader

    Sub Main()
        sqCmd.Connection = sqCon
        sqCmd.CommandText =
            "
            declare @initdate as varchar(20)
            declare @lastdate as varchar(20)
            declare @location as varchar(20)

            set @initdate = CONVERT(date,GETDATE()-1);
            set @lastdate = CONVERT(date,GETDATE());
            set @location = 'xxxx%'

            ;with q(a, c) as
            (
            select MIN(date), MAX(date)
            from Table_Loader
            where nameplace like @location
            and date >= @initdate
            and date <= @lastdate
            union all
            select DATEADD(hour,1,a), c
            from q
            where a < c
            )
            select *
            from q
            where a not in
            (
                select date
                from Table_Loader
                where nameplace like @location
                and date >= @initdate
                and date <= @lastdate
            )
            order by a asc
            OPTION (MAXRECURSION 0)
            "
        sqCon.Open()
        sqCmd.ExecuteNonQuery()
        sdrRow = sqCmd.ExecuteReader()

        For Each itm In sdrRow
            Dim column0 As String = sdrRow.GetValue(0)
            MsgBox(column0)
        Next

        sdrRow.Close()
        sqCon.Close()
    End Sub

End Module

Now I can generate the process #1 but not #2 and #3. Since the data will be used in script, I am thinking of creating temporary file of batch (appear when only this console running, deleted after the console finished process). Since I don't want to create many file from the console.

I am new in VB console thus limit my idea to get this solved. I heard about "pipe" but I do not know on how to do that. I am still thinking on continuing For Each loop or For loop, but am stuck on this. Please advise me. Just to inform, I am planning to implement this console to run on daily-basis.


问:
Maven error :Perhaps you are running on a JRE rather than a JDK?
I've never worked with Maven before and I am following the instructions here. When I run the command

```<code>mvn integration-test -Pamp-to-war
</code>```

It initially downloaded a whole bunch of dependencies, and in the end it showed,

```<code>COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
</code>```

I am on ubuntu 13.04.

If there's anything you want me to tell you, let me know. Thanks.

EDIT

When I do echo $JAVA_HOME I get /usr/lib/jvm/java-7-openjdk-i386/

When I do mvn -version

I get,

```<code>Apache Maven 3.0.4
Maven home: /usr/share/maven
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-7-openjdk-i386/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.8.0-26-generic", arch: "i386", family: "unix"
</code>```

Also, I found out this problem faced by someone else. But I am not sure how to go about the solution that is specified?

Further edits.

```<code>kraken@kraken-Inspiron-1545:/usr/lib/jvm/java-7-openjdk-i386$ ls -l
total 12
drwxr-xr-x 2 root root 4096 Sep  9 10:44 bin
lrwxrwxrwx 1 root root   41 Jul  4  2013 docs -> ../../../share/doc/openjdk-7-jre-    headless
drwxr-xr-x 5 root root 4096 Oct 13  2013 jre
drwxr-xr-x 4 root root 4096 Oct 13  2013 man
</code>```

答:
I was facing the same issue in eclipse maven project, all i did was

right click on the project

maven --> update project

or just press ALT+ F5

ContentLicense: CC BY-SA 3.0

Body:
I've never worked with Maven before and I am following the instructions here. When I run the command

mvn integration-test -Pamp-to-war

It initially downloaded a whole bunch of dependencies, and in the end it showed,

COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error

I am on ubuntu 13.04.

If there's anything you want me to tell you, let me know. Thanks.

EDIT

When I do echo $JAVA_HOME I get /usr/lib/jvm/java-7-openjdk-i386/

When I do mvn -version

I get,

Apache Maven 3.0.4
Maven home: /usr/share/maven
Java version: 1.7.0_25, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-7-openjdk-i386/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.8.0-26-generic", arch: "i386", family: "unix"

Also, I found out this problem faced by someone else. But I am not sure how to go about the solution that is specified?

Further edits.

kraken@kraken-Inspiron-1545:/usr/lib/jvm/java-7-openjdk-i386$ ls -l
total 12
drwxr-xr-x 2 root root 4096 Sep  9 10:44 bin
lrwxrwxrwx 1 root root   41 Jul  4  2013 docs -> ../../../share/doc/openjdk-7-jre-    headless
drwxr-xr-x 5 root root 4096 Oct 13  2013 jre
drwxr-xr-x 4 root root 4096 Oct 13  2013 man


问:
Converting TimeZone Date Object without Changing Time
I want to convert the date from one timeZone into another TimeZone

For Eg: "Sun May 01 2019 00:00:00 GMT+0530 (India Standard Time)" is the current date object , i want to convert the date based on timeZone Offset. consider the offset is '+4.0', Then i want the desired output such as "Sun May 01 2019 00:00:00 +04:00", i have used moment utcOffset
but it gives result such as "Sun May 19 2019 22:30:00 GMT+0530".

答:
Try https://momentjs.com/docs/

If you want more control and internalization. But the Date object will be relative to browser that instantiates it. To represent time use the unix epoch, (new Date).getTime() / 1000;.

See https://en.wikipedia.org/wiki/Unix_time


问:
VS2019: Extension or default behaviour to link a bookmark to the current git branch
Environment: Visual Studio (2019)

Point of intrest: Bookmarks (Ctrl + K, Ctrl + K)

I'm looking for either an extension or the setting to link a bookmark (hotkey Ctrl + K, Ctrl + K) to the current git branch that is beeing worked on, in order to keep bookmarks branch specific.

For instance: Creating a bookmark while working on branch Feature1 will cause this bookmark to only exist in the branch Feature1. If I checkout the branch Feature2 the bookmark is removed. Upon switing back to Feature1 all previous bookmarks are restored.

答:
I'm afraid the answer is negative. For the (Ctrl+K,Ctrl+K) bookmark, the info of bookmark is not stored in the files which have been included in the several branches. Which makes different branch has the same bookmark.

And It seems no existing setting in vs for this option(Can't meet your needs: different bookmark for different git branch). Sorry for this inconvenience.

And i think your needs is reasonable and this option is meaningful. So I suggest you could report this issue by Help=>Send Feedback=>Post a suggestion about this option if possible. Then please post it here, we who interested in it could vote for it.

And as for extension, not sure if this one could help.

Feature request link if you're interested in it.


问:
How to convert the column in US million dollars in pandas?
I have a column called collection as follow

collection : $5,345,677, 46836214, $533,316,061, " ", 29200000

Column values have both in US dollar and without dollars. Also, it has NAN. I want to change into US Dollar in million

I used to convert as follow but not successful

```<code>df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)
</code>```

Getting this error: could not convert string to float: '$5,345,677'

Please advise

答:
<pre class="lang-py prettyprint-override"><code># remove the '$' and ',' from the strings so it can be converted to numerics
# -> notice: the series is converted to strings to handle numerics (eg. 29200000)
collection_tmp = df2['collection'].astype(str).str.replace('[$,]', '')
# convert to numerics (floats) and then to millions
# -> errors='coerce' sets NaN for invalid values
millions = pd.to_numeric(collection_tmp, errors='coerce')/1e6
# create 'Boxoffice in US$ (mil)'
df['Boxoffice in US$ (mil)'] = millions.round(2).astype('str')
</code>```

Body:
I have a column called collection as follow

collection : $5,345,677, 46836214, $533,316,061, " ", 29200000

Column values have both in US dollar and without dollars. Also, it has NAN. I want to change into US Dollar in million

I used to convert as follow but not successful

df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)

Getting this error: could not convert string to float: '$5,345,677'

Please advise


问:
Linq Unit Test Suite
There are a set of 101 samples for LINQ here

I am sure I've seen someone make reference to a set of unit tests that test this functionality. It's primarily for someone creating a LINQ provider to make sure they implement everything correctly.

Can anyone provide a link to these unit tests if they exist?

答:
You may be looking for Jon Skeet's EduLINQ.

Note that he's writinga LINQ to Objects implementation; some of his tests will not be applicable to DB-based implementations.

Title: Linq Unit Test Suite


问:
Session Cookie never set in asp.net core
I am trying to configure sessions for an asp.net core 2.0 website, but the session cookie is never set.

I call ..

```<code>app.UseSession();
</code>```

...in Startup.Configure and ...

```<code>        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(10);
            options.Cookie.HttpOnly = false;
            options.Cookie.Name = "WS_AUTH_ID";
        });
</code>```

... in the ConfigureServices method.

In the Controller I can acess ...

```<code>HttpContext.Session.Id;
</code>```

... but the id is always different for every request.

Am I missing something?

Update: I should metion that I can set cookies "manually" and the browser will "receive" them.

```<code>HttpContext.Response.Cookies.Append("Test_cookie", "yo");
</code>```

答:
For me the problem was solved by one of the comments on the question:

The cookie isn't written unless you add something to the session.

So just requesting the Session.Id won't help, you actually have to set something.

In my case it was a variable that was only set after some condition, and before that condition was met, it would create a new session ID over and over again.

Body:
I am trying to configure sessions for an asp.net core 2.0 website, but the session cookie is never set.

I call ..

app.UseSession();

...in Startup.Configure and ...

        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(10);
            options.Cookie.HttpOnly = false;
            options.Cookie.Name = "WS_AUTH_ID";
        });

... in the ConfigureServices method.

In the Controller I can acess ...

HttpContext.Session.Id;

... but the id is always different for every request.

Am I missing something?

Update: I should metion that I can set cookies "manually" and the browser will "receive" them.

HttpContext.Response.Cookies.Append("Test_cookie", "yo");


问:
Rounding is inconsistent after floating point math
Take the following example (with contrived numbers):

```<code>double a = 9.0, b = 2.0;
double c = a / b;
int d = RoundAndCastToInt(c);
</code>```

Across multiple runs, the value of d isn't consistent. Here are two contrived ways the math gets performed:

Execution 1:

9.0 / 2.0 == 4.49999...

RoundAndCastToInt(4.49999...) == 4

Execution 2:

9.0 / 2.0 == 4.5

RoundAndCastToInt(4.5) == 5

I want to get the same value consistently across different executions and different machines. In the example above, a result of either 4 or 5 is fine as long as it is always 4 or always 5.

答:
This might be stupid with a lot of unsolved details, but I guess it can work when you know the precision of the solution you want...</p>

```<code>#include <stdio.h>
#include <math.h>

int main(int argc, char * argv[]) {
  float i = 5.3 / 4.7;
  float j = 5.3 / 4.7;

  printf("i %f \n", round(i * 10000.0) / 10000.0);
  printf("j %f \n", round(j * 10000.0) / 10000.0);

  return 0;
}
</code>```

Body:
Take the following example (with contrived numbers):

double a = 9.0, b = 2.0;
double c = a / b;
int d = RoundAndCastToInt(c);

Across multiple runs, the value of d isn't consistent. Here are two contrived ways the math gets performed:

Execution 1:

9.0 / 2.0 == 4.49999...

RoundAndCastToInt(4.49999...) == 4

Execution 2:

9.0 / 2.0 == 4.5

RoundAndCastToInt(4.5) == 5

I want to get the same value consistently across different executions and different machines. In the example above, a result of either 4 or 5 is fine as long as it is always 4 or always 5.

Body:
This might be stupid with a lot of unsolved details, but I guess it can work when you know the precision of the solution you want...

#include <stdio.h>
#include <math.h>

int main(int argc, char * argv[]) {
  float i = 5.3 / 4.7;
  float j = 5.3 / 4.7;

  printf("i %f \n", round(i * 10000.0) / 10000.0);
  printf("j %f \n", round(j * 10000.0) / 10000.0);

  return 0;
}


问:
What are the lesser known but useful data structures?
There are some data structures around that are really useful but are unknown to most programmers. Which ones are they?

Everybody knows about linked lists, binary trees, and hashes, but what about Skip lists and Bloom filters for example. I would like to know more data structures that are not so common, but are worth knowing because they rely on great ideas and enrich a programmer's tool box.

PS: I am also interested in techniques like Dancing links which make clever use of properties of a common data structure.

EDIT:
Please try to include links to pages describing the data structures in more detail. Also, try to add a couple of words on why a data structure is cool (as Jonas Kölker already pointed out).  Also, try to provide one data-structure per answer. This will allow the better data structures to float to the top based on their votes alone.

答:
Binary decision diagram is one of my favorite data structures, or in fact Reduced Ordered Binary Decision Diagram (ROBDD).

These kind of structures can for instance be used for:

Representing sets of items and performing very fast logical operations on those sets.

Any boolean expression, with the intention of finding all solutions for the expression

Note that many problems can be represented as a boolean expression. For instance the solution to a suduku can be expressed as a boolean expression. And building a BDD for that boolean expression will immediately yield the solution(s).

LastEditorDisplayName: Simucal

OwnerDisplayName: Zuu

ContentLicense: CC BY-SA 2.5


问:
mysql password not working

Possible Duplicate:

  How to reset mysql root password ?

I executed the query

```<code>UPDATE mysql.users set password= PASSWORD('123456') WHERE users='root' and host='localhost';
flush priviledges;
</code>```

and after this mysql is not running. phpmyadmin and mysql console both are not working

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

答:
There's a typo here:

```<code>flush priviledges;
</code>```

should be

```<code>flush privileges;
</code>```

Title: mysql password not working

Body:
Possible Duplicate:

  How to reset mysql root password ?

I executed the query

UPDATE mysql.users set password= PASSWORD('123456') WHERE users='root' and host='localhost';
flush priviledges;

and after this mysql is not running. phpmyadmin and mysql console both are not working

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Body:
There's a typo here:

flush priviledges;

should be

flush privileges;


问:
Retrofit returns null
I want to retrieve user details from an API, but when i place the text in a textview, it becomes blank.

My Object class

```<code>public class Obj {
/**
 * settings : {"success":"1","message":"You have successfully logged in.","fields":["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]}
 * data : [{"user_id":"108","email":"jk@grr.la","status":"Active","profile_image":"http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png","access_token":"144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635","phone":"","user_name":"Jack Kalsan","plate_number":"ABC1234","state_id":"2722","state":"Abakan","is_social":"","is_notification_enabled":"Yes","search_report_count":"69","remove_add":"0"}]
 */

private SettingsBean settings;
private List<DataBean> data;

public SettingsBean getSettings() {
    return settings;
}

public void setSettings(SettingsBean settings) {
    this.settings = settings;
}

public List<DataBean> getData() {
    return data;
}

public void setData(List<DataBean> data) {
    this.data = data;
}

public static class SettingsBean {
    /**
     * success : 1
     * message : You have successfully logged in.
     * fields : ["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]
     */

    private String success;
    private String message;
    private List<String> fields;

    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<String> getFields() {
        return fields;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }
}

public static class DataBean {
    /**
     * user_id : 108
     * email : jk@grr.la
     * status : Active
     * profile_image : http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png
     * access_token : 144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635
     * phone :
     * user_name : Jack Kalsan
     * plate_number : ABC1234
     * state_id : 2722
     * state : Abakan
     * is_social :
     * is_notification_enabled : Yes
     * search_report_count : 69
     * remove_add : 0
     */

    private String user_id;
    private String email;
    private String status;
    private String profile_image;
    private String access_token;
    private String phone;
    private String user_name;
    private String plate_number;
    private String state_id;
    private String state;
    private String is_social;
    private String is_notification_enabled;
    private String search_report_count;
    private String remove_add;

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getProfile_image() {
        return profile_image;
    }

    public void setProfile_image(String profile_image) {
        this.profile_image = profile_image;
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getPlate_number() {
        return plate_number;
    }

    public void setPlate_number(String plate_number) {
        this.plate_number = plate_number;
    }

    public String getState_id() {
        return state_id;
    }

    public void setState_id(String state_id) {
        this.state_id = state_id;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getIs_social() {
        return is_social;
    }

    public void setIs_social(String is_social) {
        this.is_social = is_social;
    }

    public String getIs_notification_enabled() {
        return is_notification_enabled;
    }

    public void setIs_notification_enabled(String is_notification_enabled) {
        this.is_notification_enabled = is_notification_enabled;
    }

    public String getSearch_report_count() {
        return search_report_count;
    }

    public void setSearch_report_count(String search_report_count) {
        this.search_report_count = search_report_count;
    }

    public String getRemove_add() {
        return remove_add;
    }

    public void setRemove_add(String remove_add) {
        this.remove_add = remove_add;
    }
}}
</code>```

My MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    proImg=(ImageView)findViewById(R.id.userProfilePic);
    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<Obj.DataBean> call=login.getUserDetails();

    call.enqueue(new Callback<Obj.DataBean>() {
        @Override
        public void onResponse(Call<Obj.DataBean> call, Response<Obj.DataBean> response) {
            if(response.isSuccessful()) {

                Obj.DataBean obj=response.body();

                name=obj.getUser_name();
                userName.setText(name);

            }
        }

        @Override
        public void onFailure(Call<Obj.DataBean> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}}
</code>```

My interface

```<code>interface Login {

     @GET("user_login_v1")
   Call<Obj.DataBean> getUserDetails();}
</code>```

My layout

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#e9edf6"
android:scrollbars="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<com.mikhaellopez.circularimageview.CircularImageView
    android:id="@+id/userProfilePic"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:layout_width="150dp"
    android:layout_height="150dp"
    />

    <TextView
        android:id="@+id/userName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyNameText"
        android:layout_marginTop="50dp"

        />

    <TextView
        android:id="@+id/userID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyUserIDText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/emailID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyEmailText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStatusText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userPlateNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyPlateNumText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStateName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStateNameText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStateID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStateIDText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userSearchReportCount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummySearchReportCountText"
        android:layout_marginTop="20dp"
        />
    </LinearLayout>
</ScrollView>
</code>```

I want to display the details(like name,id,plate number etc) in different textviews. But it returns a blank string,ie null.

Here's my API in JSON format

Can someone help me?

答:
Try this interface method.

```<code>   @GET("user_login_v1")
   Call<Obj> getUserDetails(@Query("email") String email,
                                             @Query("password") String password);
</code>```

and Call method in your MainActivity like this.

```<code> Call<Obj> call=login.getUserDetails(email,password);//email and password which user enter when he login in your device.
</code>```

Feel free to ask more questions.

Title: Retrofit returns null

Body:
I want to retrieve user details from an API, but when i place the text in a textview, it becomes blank.

My Object class

public class Obj {
/**
 * settings : {"success":"1","message":"You have successfully logged in.","fields":["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]}
 * data : [{"user_id":"108","email":"jk@grr.la","status":"Active","profile_image":"http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png","access_token":"144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635","phone":"","user_name":"Jack Kalsan","plate_number":"ABC1234","state_id":"2722","state":"Abakan","is_social":"","is_notification_enabled":"Yes","search_report_count":"69","remove_add":"0"}]
 */

private SettingsBean settings;
private List<DataBean> data;

public SettingsBean getSettings() {
    return settings;
}

public void setSettings(SettingsBean settings) {
    this.settings = settings;
}

public List<DataBean> getData() {
    return data;
}

public void setData(List<DataBean> data) {
    this.data = data;
}

public static class SettingsBean {
    /**
     * success : 1
     * message : You have successfully logged in.
     * fields : ["user_id","email","status","profile_image","access_token","phone","user_name","plate_number","state_id","state","is_social","is_notification_enabled","search_report_count","remove_add"]
     */

    private String success;
    private String message;
    private List<String> fields;

    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<String> getFields() {
        return fields;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }
}

public static class DataBean {
    /**
     * user_id : 108
     * email : jk@grr.la
     * status : Active
     * profile_image : http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png
     * access_token : 144d44efa92327ed0c1b6d98bb866563a7cc95680c136603bbf0eca4832da635
     * phone :
     * user_name : Jack Kalsan
     * plate_number : ABC1234
     * state_id : 2722
     * state : Abakan
     * is_social :
     * is_notification_enabled : Yes
     * search_report_count : 69
     * remove_add : 0
     */

    private String user_id;
    private String email;
    private String status;
    private String profile_image;
    private String access_token;
    private String phone;
    private String user_name;
    private String plate_number;
    private String state_id;
    private String state;
    private String is_social;
    private String is_notification_enabled;
    private String search_report_count;
    private String remove_add;

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getProfile_image() {
        return profile_image;
    }

    public void setProfile_image(String profile_image) {
        this.profile_image = profile_image;
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getPlate_number() {
        return plate_number;
    }

    public void setPlate_number(String plate_number) {
        this.plate_number = plate_number;
    }

    public String getState_id() {
        return state_id;
    }

    public void setState_id(String state_id) {
        this.state_id = state_id;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getIs_social() {
        return is_social;
    }

    public void setIs_social(String is_social) {
        this.is_social = is_social;
    }

    public String getIs_notification_enabled() {
        return is_notification_enabled;
    }

    public void setIs_notification_enabled(String is_notification_enabled) {
        this.is_notification_enabled = is_notification_enabled;
    }

    public String getSearch_report_count() {
        return search_report_count;
    }

    public void setSearch_report_count(String search_report_count) {
        this.search_report_count = search_report_count;
    }

    public String getRemove_add() {
        return remove_add;
    }

    public void setRemove_add(String remove_add) {
        this.remove_add = remove_add;
    }
}}

My MainActivity.java

public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    proImg=(ImageView)findViewById(R.id.userProfilePic);
    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<Obj.DataBean> call=login.getUserDetails();

    call.enqueue(new Callback<Obj.DataBean>() {
        @Override
        public void onResponse(Call<Obj.DataBean> call, Response<Obj.DataBean> response) {
            if(response.isSuccessful()) {

                Obj.DataBean obj=response.body();

                name=obj.getUser_name();
                userName.setText(name);

            }
        }

        @Override
        public void onFailure(Call<Obj.DataBean> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}}

My interface

interface Login {

     @GET("user_login_v1")
   Call<Obj.DataBean> getUserDetails();}

My layout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#e9edf6"
android:scrollbars="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<com.mikhaellopez.circularimageview.CircularImageView
    android:id="@+id/userProfilePic"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:layout_width="150dp"
    android:layout_height="150dp"
    />

    <TextView
        android:id="@+id/userName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyNameText"
        android:layout_marginTop="50dp"

        />

    <TextView
        android:id="@+id/userID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyUserIDText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/emailID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyEmailText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStatusText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userPlateNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyPlateNumText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStateName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStateNameText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userStateID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummyStateIDText"
        android:layout_marginTop="20dp"
        />

    <TextView
        android:id="@+id/userSearchReportCount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/fnavyblue"
        android:textSize="20sp"
        android:text="DummySearchReportCountText"
        android:layout_marginTop="20dp"
        />
    </LinearLayout>
</ScrollView>

I want to display the details(like name,id,plate number etc) in different textviews. But it returns a blank string,ie null.

Here's my API in JSON format

Can someone help me?

Body:
Try this interface method.

   @GET("user_login_v1")
   Call<Obj> getUserDetails(@Query("email") String email,
                                             @Query("password") String password);

and Call method in your MainActivity like this.

 Call<Obj> call=login.getUserDetails(email,password);//email and password which user enter when he login in your device.

Feel free to ask more questions.


问:
How do I create a new table taking columns from information_schema.columns with scale and precision?
I'm trying to create a table from information_schema.columns. I need precision and scale so that it helps me with decimal datatype. The problem I face here is for INT I get precision and scale, which cannot be inserted. Can someone help me with selecting the columns?
Eg:
I need select statement which gives such a output
I'm selecting from table A, it has 3 columns

```<code>name varchar(10),
price decimal(5,2),
Id int,
</code>```

What I get from the query I framed

```<code>name varchar(10),
price decimal(5,2),
Id int(10,0)
</code>```

current query:

```<code>SELECT COLUMN_NAME +' ' + DATA_TYPE + ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','') + ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')+ISNULL(','+CAST(NUMERIC_SCALE)AS VARCHAR)+')','')+',' FROM INFORMATION_SCHEMA.COLUMNS
</code>```

答:
This work for me

```<code>SELECT COLUMN_NAME +' ' + DATA_TYPE +

case DATA_TYPE when 'VARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

 when 'nVARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

when 'decimal'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

else
''
end

FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='A'
</code>```

but you should add your case if you have more then what I did

Body:
I'm trying to create a table from information_schema.columns. I need precision and scale so that it helps me with decimal datatype. The problem I face here is for INT I get precision and scale, which cannot be inserted. Can someone help me with selecting the columns?
Eg:
I need select statement which gives such a output
I'm selecting from table A, it has 3 columns

name varchar(10),
price decimal(5,2),
Id int,

What I get from the query I framed

name varchar(10),
price decimal(5,2),
Id int(10,0)

current query:

SELECT COLUMN_NAME +' ' + DATA_TYPE + ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','') + ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')+ISNULL(','+CAST(NUMERIC_SCALE)AS VARCHAR)+')','')+',' FROM INFORMATION_SCHEMA.COLUMNS

Body:
This work for me

SELECT COLUMN_NAME +' ' + DATA_TYPE +

case DATA_TYPE when 'VARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

 when 'nVARCHAR'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

when 'decimal'  then

ISNULL('('+CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(10))+') ','')
+ ISNULL('('+CAST(NUMERIC_PRECISION AS VARCHAR),'')
+ ISNULL(','+CAST(NUMERIC_SCALE AS VARCHAR)+')','')+','

else
''
end

FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='A'

but you should add your case if you have more then what I did


问:
How to initialize dynamic array in constructor using initializer_ist?
I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

```<code>#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor
    return 0;
}
</code>```

答:
Use a standard std::vector container instead of a raw pointer. std::vector is a wrapper for a dynamic array, and it has a constructor that accepts a std::initializer_list as input.

#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;

class vec {
private:
    vector<double> data;

public:
    vec(initializer_list<double> ilist) : data(ilist) {}
};
```

Body:
I am trying to initialize the dynamic array in the constructor using initialize_list in C++. How can I achieve this?

#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <utility>

using namespace std;

class vec {
private:
    // Variable to store the number of elements contained in this vec.
    size_t elements;
    // Pointer to store the address of the dynamically allocated memory.
    double *data;

public:
    /*
      * Constructor to create a vec variable with the contents of 'ilist'.
    */
    vec(initializer_list<double> ilist);
}

int main() {
    vec x = { 1, 2, 3 };  // should call to the constructor
    return 0;
}


问:
In Sendgrid Design template, how to use handlebar iteration for table?
I'm using SendGrid online "Design" template, with a module "code".

In their documentation (https://sendgrid.com/docs/ui/sending-email/editor/#code-modules), they say that de code editor does not modify or validate any HTML.

If I write this piece of code inside the code module:

```<code><ul>
{{#each items}}
    <li>test</li>
{{/each}}
</ul>
<table>
<tbody>
{{#each items}}
    <tr>
        <td>Col 1</td>
        <td>Col 2</td>
    </tr>
{{/each}}
</tbody>
</table>
</code>```

it results in:

```<code><ul>
{{#each items}}
    <li>test</li>
{{/each}}
</ul>
{{#each items}}{{/each}}
<table>
<tbody><tr>
        <td>Col 1</td>
        <td>Col 2</td>
    </tr></tbody>
</table>
</code>```

We can see that the {{each}} function stays in the right place for the ul, but is remove from inside of the table. Is this a temporary bug? How can I do this simple operation?

Thanks for your help

答:
I found a undocumented way to make this works. You will need to comment out the each helper like this:

```<code><table>
<tbody>
<!-- {{#each items}} -->
    <tr>
        <td>Col 1</td>
        <td>Col 2</td>
    </tr>
<!-- {{/each}} -->
</tbody>
</table>
</code>```

Body:
I'm using SendGrid online "Design" template, with a module "code".

In their documentation (https://sendgrid.com/docs/ui/sending-email/editor/#code-modules), they say that de code editor does not modify or validate any HTML.

If I write this piece of code inside the code module:

{{#each items}}

test

{{/each}}

{{#each items}}

        Col 1
        Col 2

{{/each}}

it results in:

{{#each items}}

test

{{/each}}

{{#each items}}{{/each}}

        Col 1
        Col 2

We can see that the {{each}} function stays in the right place for the ul, but is remove from inside of the table. Is this a temporary bug? How can I do this simple operation?

Thanks for your help

Body:
I found a undocumented way to make this works. You will need to comment out the each helper like this:

<table>
<tbody>
<!-- {{#each items}} -->
    <tr>
        <td>Col 1</td>
        <td>Col 2</td>
    </tr>
<!-- {{/each}} -->
</tbody>
</table>


问:
NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)
I am stuck with this error no matter what directory I am in, and what I type after "npm" in cmd.exe. Here is the npm-debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js' ]
2 info using npm@2.14.12
3 info using node@v4.2.6
4 verbose stack Error: EISDIR: illegal operation on a directory, read
4 verbose stack     at Error (native)
5 verbose cwd C:\Users\me
6 error Windows_NT 6.1.7601
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"
8 error node v4.2.6
9 error npm  v2.14.12
10 error code EISDIR
11 error errno -4068
12 error syscall read
13 error eisdir EISDIR: illegal operation on a directory, read
13 error eisdir This is most likely not a problem with npm itself
13 error eisdir and is related to npm not being able to find a package.json in
13 error eisdir a package you are trying to install.
14 verbose exit [ -4068, true ]
</code>```

I have tried and uninstalling/reinstalling nodejs multiple times, I even deleted npm and npm-cache folders in C:\Users\me\AppData\Roaming. I'm not sure what went wrong to cause this. One second it was working fine, and now I can't get rid of this error. The explanation in the log does not make sense, as it gives this error in any directory. I should note that running a command prompt as administrator does not give this error. I'm pulling my hair out this Friday evening trying to get this fixed, any help would be greatly appreciated!

答:
In my case these steps solved my problem:

terminating npm process (CTRL + C)

deleting entire folder

creating new one

running npm again

Body:
I am stuck with this error no matter what directory I am in, and what I type after "npm" in cmd.exe. Here is the npm-debug.log:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js' ]
2 info using npm@2.14.12
3 info using node@v4.2.6
4 verbose stack Error: EISDIR: illegal operation on a directory, read
4 verbose stack     at Error (native)
5 verbose cwd C:\Users\me
6 error Windows_NT 6.1.7601
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"
8 error node v4.2.6
9 error npm  v2.14.12
10 error code EISDIR
11 error errno -4068
12 error syscall read
13 error eisdir EISDIR: illegal operation on a directory, read
13 error eisdir This is most likely not a problem with npm itself
13 error eisdir and is related to npm not being able to find a package.json in
13 error eisdir a package you are trying to install.
14 verbose exit [ -4068, true ]

I have tried and uninstalling/reinstalling nodejs multiple times, I even deleted npm and npm-cache folders in C:\Users\me\AppData\Roaming. I'm not sure what went wrong to cause this. One second it was working fine, and now I can't get rid of this error. The explanation in the log does not make sense, as it gives this error in any directory. I should note that running a command prompt as administrator does not give this error. I'm pulling my hair out this Friday evening trying to get this fixed, any help would be greatly appreciated!


问:
C++ macros with define or inline?

Possible Duplicate:

  Inline functions vs Preprocessor macros

Inline functions were introduced in C++ to replace C style macros (#define macroname...), still, I see lots of C++ code using old C style macros rather than inlined functions, are inlined function inferior to old C style macros?

答:
The one of the only things I can imagine still using macros for are for the LINE and FILE macros to be incorporated into a logging statement

for example:

```<code>#DEFINE TRACE(S) vGenericLogStatement(__FILE__,__LINE__, s)
</code>```

where the definition of vGenericLogStatement was something like:

```<code>void vGenericLogStatement(char* fileName, int line, char* traceMesg);
</code>```

They are also useful quick and dirty string concatenation.

Title: C++ macros with define or inline?

Body:
The one of the only things I can imagine still using macros for are for the LINE and FILE macros to be incorporated into a logging statement

for example:

#DEFINE TRACE(S) vGenericLogStatement(__FILE__,__LINE__, s)

where the definition of vGenericLogStatement was something like:

void vGenericLogStatement(char* fileName, int line, char* traceMesg);

They are also useful quick and dirty string concatenation.


问:
SQL Grouping with Multiple Column Criteria
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

```<code>ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800
</code>```

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

```<code>PersonID     TotalAmount
       1             100
       2             200
       3            -300
</code>```

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

答:
Try this-

```<code>SELECT
CASE
    WHEN A.GiverPersonID IS NULL THEN B.TakerPersonId
    ELSE A.GiverPersonID
END PersonID,
B.Take - A.Give TotalAmount
FROM
(
    SELECT GiverPersonID, SUM(Amount)  Give
    FROM your_tabel A
    GROUP BY GiverPersonID
)A
FULL JOIN
(
    SELECT TakerPersonId, SUM(Amount)  Take
    FROM your_tabel A
    GROUP BY TakerPersonId
) B
ON A.TakerPersonId= B.TakerPersonId
</code>```

Output is-

```<code>PersonID    TotalAmount
1           100
2           200
3           -300
</code>```

Body:
I have a table like below. GiverID and TakerID are both foreign keys to another table, say Person Table. GiverID and TakerID won't be same within a row.

ID  GiverPersonID  TakerPersonID  Amount
 1              1              3     100
 2              2              1     200
 3              2              3     400
 4              3              2     800

The first row for that table means that Person with ID 1 gives 100 to Person with ID 3.

I need a query to get the result like below

PersonID     TotalAmount
       1             100
       2             200
       3            -300

Basically, computing the final amount of each person.
For person with ID 1, he gives 100 to person with ID 3, but take 200 from person with ID 2, so his final amount is 200 - 100, which is 100.

I've reading about pivoting, but I think pivoting is not the correct step.

What is the efficient SQL to calculate that result?

Body:
Try this-

SELECT
CASE
    WHEN A.GiverPersonID IS NULL THEN B.TakerPersonId
    ELSE A.GiverPersonID
END PersonID,
B.Take - A.Give TotalAmount
FROM
(
    SELECT GiverPersonID, SUM(Amount)  Give
    FROM your_tabel A
    GROUP BY GiverPersonID
)A
FULL JOIN
(
    SELECT TakerPersonId, SUM(Amount)  Take
    FROM your_tabel A
    GROUP BY TakerPersonId
) B
ON A.TakerPersonId= B.TakerPersonId

Output is-

PersonID    TotalAmount
1           100
2           200
3           -300


问:
Positive Number to Negative Number in JavaScript?
Basically, the reverse of abs. If I have:

```<code>if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  slideNum = -slideNum
}
console.log(slideNum)
</code>```

No matter what console always returns a positive number. How do I fix this?

If I do:

```<code>if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  _selector.animate({
    left: (-slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
} else {
  _selector.animate({
    left: (slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
}
</code>```

it works tho, but it's not "DRY" and just stupid to have an entire block of code JUST for a -.

答:
```<code>num * -1
</code>```

This would do it for you.

Body:
Basically, the reverse of abs. If I have:

if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  slideNum = -slideNum
}
console.log(slideNum)

No matter what console always returns a positive number. How do I fix this?

If I do:

if ($this.find('.pdxslide-activeSlide').index() < slideNum - 1) {
  _selector.animate({
    left: (-slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
} else {
  _selector.animate({
    left: (slideNum * sizes.images.width) + 'px'
  }, 750, 'InOutPDX')
}

it works tho, but it's not "DRY" and just stupid to have an entire block of code JUST for a -.

Body:
num * -1

This would do it for you.


问:
Angular get response after subscribe loops end
thanks in advance for your time.

I am looping 2 services endpoints to get data, the problem that I am facing is that I would like to wait for the first subscribe to finish in order to loop the other one, but the result outside of the first subscribe is empty and if I place the second loop within the previous subscribe, I am facing duplications and/or undefined variables.

I have tried two ways

The first solution i have tried is looping the service endpoint and then looping the other service endpoint inside the first subscribe. The problem with this solution is that i am facing duplicates and/or undefinend variables.

The second solution i tried is using forkJoin, but i have two problems with this one.

The first problem i have using forkJoin is that i am getting a Pageable from my backend (using java - spring boot) to manage the pagination, so i cannot do a proper pagination because the forkJoin retrieve the Pagination in an Array, so the details are no longer useful, since it is splitted in the array.

The second problem i have using forkJoin is that everytime i click again to fetch the data it is adding the result to the old one, making endless duplicates (even when i set my arry to empty everytime i press the button)

I will share with you guys both examples i have tried and the service endpoints i am using

Service 1:

```<code>getAllQuestionsEvaluation(page: number, level: number, profu: number, idComponent: number): Observable<any> {
    return this.http.get(this.urlEndpoint + 'page/' + page + '/' + level + '/' + profu + '/' + idComponent, {headers: this.headerService.addAuthHeader()}).pipe(
      catchError((e) => {
        this.headerService.serverError(e);
        if (this.headerService.isNoAuth(e)) {
          this.appDialogService.confirm();
        }
        return throwError(e);
      })
    );
  }
</code>```

I first loop that endpoint and then i need to loop the result for the next service to get the other data:

Service 2:

```<code>getAllByIdQuestion(idQuestion: number): Observable<any> {
    return this.http.get(this.urlEndpoint + 'findbyidq/' + idQuestion, {headers: this.headerService.addAuthHeader()}).pipe(
      catchError((e) => {
        this.headerService.serverError(e);
        if (this.headerService.isNoAuth(e)) {
          this.appDialogService.confirm();
        }
        return throwError(e);
      })
    );
  }
</code>```

The first code i have been trying is the following, however i and facing duplicates and problems with the result:

jsonComponentsResult is the array result of components, however that service is not looping, so i am facing no problems with it and that is why i am not sharing that code.

```<code>this.questions = [];
this.questionsToCompare = [];

for (let com of jsonComponentsResult) {
  this.questionService.getAllQuestionsEvaluation(0, this.evaluation.level, this.evaluation.profu, com.idComponent.idComponent).subscribe(
    (jsonQuestions) => {

      this.questionsToCompare = this.questionsToCompare.concat(jsonQuestions.content);

      for (let i = 0; i < this.questionsToCompare.length; i++) {
        this.questionsGradeService.getAllByIdQuestion(this.questionsToCompare[i].idQuestion).subscribe(
          (response) => {
            this.questionsGrades = this.questionsGrades.concat(response);

            for (let p of this.questionsGrades) {
              if (this.evaluation.idGrade.idGrade === p.idGrade.idGrade) {
                this.questions = this.questions.concat(p.idQuestion);
              }
            }

            this.dataSource = new MatTableDataSource < Questions > (this.questions);
          }
        );
      }

      this.pageIndex = jsonQuestions.number;
      this.pageSize = jsonQuestions.size;
      this.length = jsonQuestions.totalElements;

    },
    (error) => {
      console.log(error);
    }
  );
}
</code>```

My second solution is to use ForkJoin, however as i mentioned before, i am not able to manage my pagination and i am getting duplicates everytime i press the button even though i am setting the arrays to empty []:

```<code>observables: Observable < Questions > [] = [];
observablePG: Observable < QuestionsGrade > [] = [];

this.questions = [];
this.questionsToCompare = [];
this.questionsGrades = [];

for (let i = 0; i < jsonComponentResult.length; i++) {
  this.observables.push(this.questionService.getAllQuestionsEvaluation(0, this.evaluation.level, this.evaluation.profu, jsonComponentResult[i].idComponent.idComponent));
}
Observable.forkJoin(this.observables).subscribe(
  (response) => {
    for (let x of response) {
      this.questionsToCompare = this.questionsToCompare.concat(x);
    }
    this.observables = [];
    this.getQuestions(this.questionsToCompare);
  },
  (e) => {
    console.log(e);
  }
);

private getQuestions(questionsArray: any) {

  for (let i = 0; i < questionsArray.length; i++) {
    this.observablePG.push(this.questionsGradeService.getAllByIdQuestion(questionsArray[i].idQuestion));

    this.questions = [];
    this.questionsToCompare = [];

  }
  Observable.forkJoin(this.observablePG).subscribe(
    (response) => {

      for (let x of response) {
        this.questionsGrades = this.questionsGrades.concat(x);
      }
      this.observablePG = [];

      for (let p of this.questionsGrades) {
        if (this.evaluation.idGrade.idGrade === p.idGrade.idGrade) {
          this.questions = this.questions.concat(p.idQuestion);
        }
      }

      this.dataSource = new MatTableDataSource < Questions > (this.questions);

    },
    (e) => {
      console.log(e);
    }
  );
}
</code>```

I would like to wait for the first subscribe to finish in order to loop the other one, but i haven't been able to find a solution, since it looks like looping those services at the same time are causing troubles, and with the forkJoin i am losing my pagination and i am getting all the list again everytime i press the button.

I would like to get the questions list, then, get the questionsGrades to compare if i should add that question to my questions array.

Sorry for the long post and thank you for your time.

答:
Maybe rxjs operator decision tree page could help you with this.

And the second, I remember that I had a similar issue, the only difference was that the value from the first Observable was used as a param in a second one, and for that I used switchMap operator.

Body:
thanks in advance for your time.

I am looping 2 services endpoints to get data, the problem that I am facing is that I would like to wait for the first subscribe to finish in order to loop the other one, but the result outside of the first subscribe is empty and if I place the second loop within the previous subscribe, I am facing duplications and/or undefined variables.

I have tried two ways

The first solution i have tried is looping the service endpoint and then looping the other service endpoint inside the first subscribe. The problem with this solution is that i am facing duplicates and/or undefinend variables.

The second solution i tried is using forkJoin, but i have two problems with this one.

The first problem i have using forkJoin is that i am getting a Pageable from my backend (using java - spring boot) to manage the pagination, so i cannot do a proper pagination because the forkJoin retrieve the Pagination in an Array, so the details are no longer useful, since it is splitted in the array.

The second problem i have using forkJoin is that everytime i click again to fetch the data it is adding the result to the old one, making endless duplicates (even when i set my arry to empty everytime i press the button)

I will share with you guys both examples i have tried and the service endpoints i am using

Service 1:

getAllQuestionsEvaluation(page: number, level: number, profu: number, idComponent: number): Observable<any> {
    return this.http.get(this.urlEndpoint + 'page/' + page + '/' + level + '/' + profu + '/' + idComponent, {headers: this.headerService.addAuthHeader()}).pipe(
      catchError((e) => {
        this.headerService.serverError(e);
        if (this.headerService.isNoAuth(e)) {
          this.appDialogService.confirm();
        }
        return throwError(e);
      })
    );
  }

I first loop that endpoint and then i need to loop the result for the next service to get the other data:

Service 2:

getAllByIdQuestion(idQuestion: number): Observable<any> {
    return this.http.get(this.urlEndpoint + 'findbyidq/' + idQuestion, {headers: this.headerService.addAuthHeader()}).pipe(
      catchError((e) => {
        this.headerService.serverError(e);
        if (this.headerService.isNoAuth(e)) {
          this.appDialogService.confirm();
        }
        return throwError(e);
      })
    );
  }

The first code i have been trying is the following, however i and facing duplicates and problems with the result:

jsonComponentsResult is the array result of components, however that service is not looping, so i am facing no problems with it and that is why i am not sharing that code.

this.questions = [];
this.questionsToCompare = [];

for (let com of jsonComponentsResult) {
  this.questionService.getAllQuestionsEvaluation(0, this.evaluation.level, this.evaluation.profu, com.idComponent.idComponent).subscribe(
    (jsonQuestions) => {

      this.questionsToCompare = this.questionsToCompare.concat(jsonQuestions.content);

      for (let i = 0; i < this.questionsToCompare.length; i++) {
        this.questionsGradeService.getAllByIdQuestion(this.questionsToCompare[i].idQuestion).subscribe(
          (response) => {
            this.questionsGrades = this.questionsGrades.concat(response);

            for (let p of this.questionsGrades) {
              if (this.evaluation.idGrade.idGrade === p.idGrade.idGrade) {
                this.questions = this.questions.concat(p.idQuestion);
              }
            }

            this.dataSource = new MatTableDataSource < Questions > (this.questions);
          }
        );
      }

      this.pageIndex = jsonQuestions.number;
      this.pageSize = jsonQuestions.size;
      this.length = jsonQuestions.totalElements;

    },
    (error) => {
      console.log(error);
    }
  );
}

My second solution is to use ForkJoin, however as i mentioned before, i am not able to manage my pagination and i am getting duplicates everytime i press the button even though i am setting the arrays to empty []:

observables: Observable < Questions > [] = [];
observablePG: Observable < QuestionsGrade > [] = [];

this.questions = [];
this.questionsToCompare = [];
this.questionsGrades = [];

for (let i = 0; i < jsonComponentResult.length; i++) {
  this.observables.push(this.questionService.getAllQuestionsEvaluation(0, this.evaluation.level, this.evaluation.profu, jsonComponentResult[i].idComponent.idComponent));
}
Observable.forkJoin(this.observables).subscribe(
  (response) => {
    for (let x of response) {
      this.questionsToCompare = this.questionsToCompare.concat(x);
    }
    this.observables = [];
    this.getQuestions(this.questionsToCompare);
  },
  (e) => {
    console.log(e);
  }
);

private getQuestions(questionsArray: any) {

  for (let i = 0; i < questionsArray.length; i++) {
    this.observablePG.push(this.questionsGradeService.getAllByIdQuestion(questionsArray[i].idQuestion));

    this.questions = [];
    this.questionsToCompare = [];

  }
  Observable.forkJoin(this.observablePG).subscribe(
    (response) => {

      for (let x of response) {
        this.questionsGrades = this.questionsGrades.concat(x);
      }
      this.observablePG = [];

      for (let p of this.questionsGrades) {
        if (this.evaluation.idGrade.idGrade === p.idGrade.idGrade) {
          this.questions = this.questions.concat(p.idQuestion);
        }
      }

      this.dataSource = new MatTableDataSource < Questions > (this.questions);

    },
    (e) => {
      console.log(e);
    }
  );
}

I would like to wait for the first subscribe to finish in order to loop the other one, but i haven't been able to find a solution, since it looks like looping those services at the same time are causing troubles, and with the forkJoin i am losing my pagination and i am getting all the list again everytime i press the button.

I would like to get the questions list, then, get the questionsGrades to compare if i should add that question to my questions array.

Sorry for the long post and thank you for your time.


问:
Iterating over keys of nested dictionary and adding tabs
I have a nested dictionary like this {"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}},Now i need to recursively iterate over the nested dictionary and create a list of keys of nested dictionary with tabs prepend to it. </p>

```<code>new_d={"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}}
other_list=[]
child=False
tabb='\t'
def put_tabs(d):
  global tabb,child
  for k, v in d.iteritems():
      if v:
          if child:
              other_list.append("{0}{1}".format(tabb,k))
              tabb+='\t'
          else:
              other_list.append("{0}".format(k))
          child=True
          put_tabs(v)
      else:
          if child:
              other_list.append("{0}{1}".format(tabb,k))

          else:
              other_list.append("{0}:".format(k))
          child=False
put_tabs(new_d)
print other_list

# Expected output ['step2', '\tstep7', '\tstep3', '\t\tstep4', 'step1:']
# current ouput ['step2', '\tstep7', 'step3', '\t\step4', 'step1:']
</code>```

答:
this is a function that will print the keys of a nested dictionary with indentation:

```<code>def indent_dict(d, indent=0):
    for key, value in d.iteritems():  # python 2
    # for key, value in d.items():    # python 3
        print("\t" * indent + str(key))
        if isinstance(value, dict):
            indent_dict(value, indent + 1)
        else:
            print("\t" * (indent + 1) + str(value))
</code>```

for your input

```<code>new_d = {"step1": {}, "step2": {"step3": {"step4": {}}, "step7": {}}}
indent_dict(new_d)
</code>```

it outputs:

```<code>step1
step2
    step3
        step4
    step7
</code>```

(this is more or less the indenting function for xml from here).

Body:
I have a nested dictionary like this {"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}},Now i need to recursively iterate over the nested dictionary and create a list of keys of nested dictionary with tabs prepend to it.

new_d={"step1": {}, "step2": {"step3": {"step4": {}},'step7':{}}}
other_list=[]
child=False
tabb='\t'
def put_tabs(d):
  global tabb,child
  for k, v in d.iteritems():
      if v:
          if child:
              other_list.append("{0}{1}".format(tabb,k))
              tabb+='\t'
          else:
              other_list.append("{0}".format(k))
          child=True
          put_tabs(v)
      else:
          if child:
              other_list.append("{0}{1}".format(tabb,k))

          else:
              other_list.append("{0}:".format(k))
          child=False
put_tabs(new_d)
print other_list

# Expected output ['step2', '\tstep7', '\tstep3', '\t\tstep4', 'step1:']
# current ouput ['step2', '\tstep7', 'step3', '\t\step4', 'step1:']

Body:
this is a function that will print the keys of a nested dictionary with indentation:

def indent_dict(d, indent=0):
    for key, value in d.iteritems():  # python 2
    # for key, value in d.items():    # python 3
        print("\t" * indent + str(key))
        if isinstance(value, dict):
            indent_dict(value, indent + 1)
        else:
            print("\t" * (indent + 1) + str(value))

for your input

new_d = {"step1": {}, "step2": {"step3": {"step4": {}}, "step7": {}}}
indent_dict(new_d)

it outputs:

step1
step2
    step3
        step4
    step7

(this is more or less the indenting function for xml from here).


问:
Correct way to check text of button?
Correct way to check text of button

I  need to check that English text on button is "Start this".

In string.xml

```<code><string name="start">Start this</string>
</code>```

So here Espresso test:

Approach#1

```<code>private val buttonStart = viewWithId(startButton)

    @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText(R.string.start)))
}
</code>```

The test "buttonStartText"  success pass. Nice.

Approach#2

Check hard code text.

```<code> @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText("Start this")))
}
</code>```

The test "buttonStartText"  success pass. Nice.

The question is:
What approach is correct?

What I mean.
Suppose the developer made error and in string.xml change value of key "start" to "Start this 2222".
E.g.

```<code><string name="start">Start this 2222</string>
</code>```

As result the test in approach#1 is still pass. This is NOT CORRECT behavior.

But test in approach#2 is broken. This is a correct behavior.

As result I think test in approach#2 is correct way to check title/text on button.

Is I'm right?

P.S.

But if I has multi language app (e.g. 3 languages). In approach#1 nothing cha nge. But in in approach#2 I need to add two additional tests that check text in specific languages.

答: I think approach #1 is correct as you cover all the local's in that else in approach #2 you only cover english or specific language. </p>

Title: Correct way to check text of button?

Body:
Correct way to check text of button

I  need to check that English text on button is "Start this".

In string.xml

<string name="start">Start this</string>

So here Espresso test:

Approach#1

private val buttonStart = viewWithId(startButton)

    @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText(R.string.start)))
}

The test "buttonStartText"  success pass. Nice.

Approach#2

Check hard code text.

 @Test
    fun buttonStartText() {
        onView(withId(startButton))
                .check(matches(withText("Start this")))
}

The test "buttonStartText"  success pass. Nice.

The question is:
What approach is correct?

What I mean.
Suppose the developer made error and in string.xml change value of key "start" to "Start this 2222".
E.g.

<string name="start">Start this 2222</string>

As result the test in approach#1 is still pass. This is NOT CORRECT behavior.

But test in approach#2 is broken. This is a correct behavior.

As result I think test in approach#2 is correct way to check title/text on button.

Is I'm right?

P.S.

But if I has multi language app (e.g. 3 languages). In approach#1 nothing cha nge. But in in approach#2 I need to add two additional tests that check text in specific languages.


问:
Open native UIViewController in Flutter
I have an application I develop in Flutter, and it has one UIViewController that has to be implemented in native IOS (there is no other workaround, it is a must)

I have implemented it, it works according to the first tests, but I'd like to double check if it is okkey by your opinion, as I am not so experienced in Flutter, and I am afraid a bit a make some mess in my app navigation stack that can cause bugs in the future.

So, I have implemented it by MethodChannel. I have a method, that called from 'Flutter side'. I don't paste my MethodChannel related things here, as they are trivial.

In my AppDelegate didFinishLaunchingWithOptions I added this:

```<code>let flutterViewController = FlutterViewController()
    self.navigationController = UINavigationController(rootViewController: flutterViewController)
    self.navigationController?.isNavigationBarHidden = true

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window.rootViewController = self.navigationController
    self.window.makeKeyAndVisible()
</code>```

And my open method like this:

```<code>private func openNativeUI(result: FlutterResult) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let uiController = sb.instantiateViewController(withIdentifier: "nativeui")

        self.navigationController?.pushViewController(uiController, animated: true)

        result(true)
    }
</code>```

What do you think?

Any advise is highly appreciated and thank you for your help in advance!

答:
It's completely fine to use Native API's while creating a cross platform application but make sure there is no other way to achieve your goal. Many a times(when a cross platform engine/sdk is new) you have no choice other than using the native code to complete your functionality.

Not sure about your goal but the common issue with cross platform engine/sdk's(e.g, Flutter) is that the third party SDK/API's(e.g, Chartboost, Stripe, Twilio) takes some time to translate into that engine/sdk you are using so while its not available you have no choice except to call those API's natively.

Other issue happens is some platform specific API's e.g, Camera, Contacts, In-App, GameCenter etc do not come along with the cross platform  SDK or it takes time to get some wrapper for such API's so in all such cases you can use Native API's.

Title: Open native UIViewController in Flutter

Body:
I have an application I develop in Flutter, and it has one UIViewController that has to be implemented in native IOS (there is no other workaround, it is a must)

I have implemented it, it works according to the first tests, but I'd like to double check if it is okkey by your opinion, as I am not so experienced in Flutter, and I am afraid a bit a make some mess in my app navigation stack that can cause bugs in the future.

So, I have implemented it by MethodChannel. I have a method, that called from 'Flutter side'. I don't paste my MethodChannel related things here, as they are trivial.

In my AppDelegate didFinishLaunchingWithOptions I added this:

let flutterViewController = FlutterViewController()
    self.navigationController = UINavigationController(rootViewController: flutterViewController)
    self.navigationController?.isNavigationBarHidden = true

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window.rootViewController = self.navigationController
    self.window.makeKeyAndVisible()

And my open method like this:

private func openNativeUI(result: FlutterResult) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let uiController = sb.instantiateViewController(withIdentifier: "nativeui")

        self.navigationController?.pushViewController(uiController, animated: true)

        result(true)
    }

What do you think?

Any advise is highly appreciated and thank you for your help in advance!


问:
Is it possible to put two INSERT statements in one SQL query
I'm trying to get two INSERT statement into one SQL query. I tried several things but nothing seems to work. If I look on the internet it seems it has to work. But it doesn't work for me and I get an error. I'm using this code with PDO.

I tried multiple web browsers, multiple types of code and I tried the "BEGIN" and "COMMIT" statement.

```<code>$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2); ".
"INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$pdostatement = $pdo->prepare($sql);
</code>```

答:
That silly concatenation mistake aside, it is technically possible to run two INSERT queries in one call, but there is not a single reason to do so.

Besides, you will need to configure PDO specifically to allow multiple queries which is not advised.

Therefore, just run these two queries as two separate prepared statements.

```<code>$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2)";
$stmt = $pdo->prepare($sql);
$stmt->execute($first_query_data);
$sql = "INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$stmt = $pdo->prepare($sql);
$stmt->execute($second_query_data);
</code>```

Body:
I'm trying to get two INSERT statement into one SQL query. I tried several things but nothing seems to work. If I look on the internet it seems it has to work. But it doesn't work for me and I get an error. I'm using this code with PDO.

I tried multiple web browsers, multiple types of code and I tried the "BEGIN" and "COMMIT" statement.

$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2); ".
"INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$pdostatement = $pdo->prepare($sql);

Body:
That silly concatenation mistake aside, it is technically possible to run two INSERT queries in one call, but there is not a single reason to do so.

Besides, you will need to configure PDO specifically to allow multiple queries which is not advised.

Therefore, just run these two queries as two separate prepared statements.

$sql = "INSERT INTO gebruiker (email, wachtwoord, rol_id) VALUES (?, ?, 2)";
$stmt = $pdo->prepare($sql);
$stmt->execute($first_query_data);
$sql = "INSERT INTO huisarts (voornaam, achternaam, email, straatnaam, huisnummer, postcode, plaats, telefoonnummer, uid, rol_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, LAST_INSERT_ID(), 2);";
$stmt = $pdo->prepare($sql);
$stmt->execute($second_query_data);


问:
How to reduce the length jenkins pipeline script?
I am using the pipeline script to build the jobs parallel when parameter matches, but for each parameter it builds upto 10 to 15 jobs parallely, so the code comes around nearly length 450 lines. is that any way to reduce the code or any other way to configure and build the job?</p>

```<code>#!/usr/bin/env groovy

pipeline {

agent any

    parameters {

        choice(
                choices: 'Job1\nJob2'\nJob3,
                description: '',
                name: 'Project'
        )
    }
 stages {
       stage ('callJob1') {

        when {
             expression { params.Project == 'Job1' }
        }
        steps{
            build job: 'test1'
            build job: 'test2'
            .
            .
            .
            .
            .
            }
        }
      stage('callJob2'){

      when{
            expression { params.Project == 'Job2'}
      }
      steps{
            build job: 'test3'
            build job: 'test4'
            .
            .
            .
            .
            .
            }
      }
      stage('callJob3'){

      when{
            expression { params.Project == 'Job3'}
      }
      steps{
            build job: 'test5'
            build job: 'test6'
            .
            .
            .
            .
            .
            }
      }
    }
}

</code>```

答:
Try extract common parts in steps and define methods in the jenkinsfile. Methods defined in jenkinsfile A can also be called in jenkinsfile B in same project.

ex:

```<code>   def func() {
   }

   .
   .
   stages {
       stage('Job1'){
           steps {
               script {
                   func()
               }
           }
       }
       stage('Job2'){
           steps {
               script {
                   func()
               }
           }
       }
   }
</code>```

Body:
I am using the pipeline script to build the jobs parallel when parameter matches, but for each parameter it builds upto 10 to 15 jobs parallely, so the code comes around nearly length 450 lines. is that any way to reduce the code or any other way to configure and build the job?

#!/usr/bin/env groovy

pipeline {

agent any

    parameters {

        choice(
                choices: 'Job1\nJob2'\nJob3,
                description: '',
                name: 'Project'
        )
    }
 stages {
       stage ('callJob1') {

        when {
             expression { params.Project == 'Job1' }
        }
        steps{
            build job: 'test1'
            build job: 'test2'
            .
            .
            .
            .
            .
            }
        }
      stage('callJob2'){

      when{
            expression { params.Project == 'Job2'}
      }
      steps{
            build job: 'test3'
            build job: 'test4'
            .
            .
            .
            .
            .
            }
      }
      stage('callJob3'){

      when{
            expression { params.Project == 'Job3'}
      }
      steps{
            build job: 'test5'
            build job: 'test6'
            .
            .
            .
            .
            .
            }
      }
    }
}

Body:
Try extract common parts in steps and define methods in the jenkinsfile. Methods defined in jenkinsfile A can also be called in jenkinsfile B in same project.

ex:

   def func() {
   }

   .
   .
   stages {
       stage('Job1'){
           steps {
               script {
                   func()
               }
           }
       }
       stage('Job2'){
           steps {
               script {
                   func()
               }
           }
       }
   }


问:
How to select and show thousands of records
I have an SQLite query that, potentially, returns thousands of records. I need to show these records in a ListView but, obviously, I cannot show them all together. Which is the Android-way to solve this problem?</p>

答: Check out the Endless Adapter by Mark Murphy</p>


问:
Let user select multiple elements in cmd
I am in the process of developing a command line application (cmd.exe) with Java and need an input mask in which the user can select several elements of a list with the arrow keys and select or deselect them with the space bar.

I need something like

```<code>Select elements:

( ) element 1
(*) element 2
( ) element 3
(*) element 4
(*) element 5
</code>```

Do I have to overwrite every line as soon as an input is detected or can I solve it differently?

Edit:
I know how to rewrite lines in the terminal and that is not what my question is about. I'm wondering if there is another solution!

答:
There are some libraries, that provide such functionality like:

javacurses

lanterna

Body:
I am in the process of developing a command line application (cmd.exe) with Java and need an input mask in which the user can select several elements of a list with the arrow keys and select or deselect them with the space bar.

I need something like

Select elements:

( ) element 1
(*) element 2
( ) element 3
(*) element 4
(*) element 5

Do I have to overwrite every line as soon as an input is detected or can I solve it differently?

Edit:
I know how to rewrite lines in the terminal and that is not what my question is about. I'm wondering if there is another solution!