问:
Replacing the values from another data from based on the information in the first column in R
I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data.

I have to dataframes (One is subset of the others with updated info in the last column):

df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))

```<code>  Name val Case
1  A   1   NA
2  B   2    1
3  C   3   NA
4  D   1   NA
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2   NA
9  I   3   NA
</code>```

Some rows in the Case column in df1 have to be changed with the info in the df2 below:

df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")

```<code>    Name val Case
1    A   1    1
2    D   2    1
3    H   3    1
</code>```

So there's nothing important in the val column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples.

Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have df1 as a final data frame.

for a better explanation, I want to see something like this:

```<code>  Name val Case
1  A   1    1
2  B   2    1
3  C   3   NA
4  D   1    1
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2    1
9  I   3   NA
</code>```

Note changed information for A,D and H.

Thanks.

答:
%in% from base-r is there to rescue.

```<code>    df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"), stringsAsFactors = F)

    df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1", stringsAsFactors = F)

    df1$Case <- ifelse(df1$Name %in% df2$Name, df2$Case[df2$Name %in% df1$Name], df1$Case)

df1

Output:

> df1
  Name val Case
1    A   1    1
2    B   2    1
3    C   3   NA
4    D   1    1
5    E   2    1
6    F   3   NA
7    G   1    1
8    H   2    1
9    I   3   NA
</code>```

Body:
I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data.

I have to dataframes (One is subset of the others with updated info in the last column):

df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))

  Name val Case
1  A   1   NA
2  B   2    1
3  C   3   NA
4  D   1   NA
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2   NA
9  I   3   NA

Some rows in the Case column in df1 have to be changed with the info in the df2 below:

df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")

    Name val Case
1    A   1    1
2    D   2    1
3    H   3    1

So there's nothing important in the val column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples.

Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have df1 as a final data frame.

for a better explanation, I want to see something like this:

  Name val Case
1  A   1    1
2  B   2    1
3  C   3   NA
4  D   1    1
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2    1
9  I   3   NA

Note changed information for A,D and H.

Thanks.

Body:
%in% from base-r is there to rescue.

    df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"), stringsAsFactors = F)

    df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1", stringsAsFactors = F)

    df1$Case <- ifelse(df1$Name %in% df2$Name, df2$Case[df2$Name %in% df1$Name], df1$Case)

df1

Output:

> df1
  Name val Case
1    A   1    1
2    B   2    1
3    C   3   NA
4    D   1    1
5    E   2    1
6    F   3   NA
7    G   1    1
8    H   2    1
9    I   3   NA


来源: stackexchange

问:
ORA-00932: inconsistent datatypes: expected - got CLOB in UNOIN
I Have this query that is a UNION of 2 queries, but even I take the same columns in both queries, when I execute it I got an error</p>

```<code>   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE status = 'ACTIVE'
            AND username <> 'SYSTEM' AND username <> 'SYS'
            AND osuser <> 'NT AUTHORITY\SYSTEM'
            AND osuser <> 'SYSTEM'
            AND seconds_in_wait >= 500

 UNION
 SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
from V$SESSION se
    join v$sql sq on sq.ADDRESS = se.SQL_ADDRESS and sq.HASH_VALUE = se.SQL_HASH_VALUE
where blocking_session is not NULL
AND seconds_in_wait >= 500
</code>```

答:
Oracle does not support UNION of columns of type CLOB (sql_fulltext in your case) are involved.

If UNION ALL (instead of UNION) works for your query as well, you can use that.

Update

You might need to modify your query slightly to avoid duplicates with UNION ALL (see last boolean expression in first WHERE clause):

```<code>SELECT username,
        sid,
        serial# serial,
        osuser,
        seconds_in_wait,
        sql_address,
        sql_hash_value,
        sql_fulltext
    FROM V$SESSION se
    JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
    WHERE status = 'ACTIVE'
        AND username <> 'SYSTEM' AND username <> 'SYS'
        AND osuser <> 'NT AUTHORITY\SYSTEM'
        AND osuser <> 'SYSTEM'
        AND seconds_in_wait >= 500
        AND blocking_session is NULL
UNION ALL
SELECT username,
        sid,
        serial# serial,
        osuser,
        seconds_in_wait,
        sql_address,
        sql_hash_value,
        sql_fulltext
FROM V$SESSION se
JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
    AND sq.HASH_VALUE = se.SQL_HASH_VALUE
WHERE blocking_session is not NULL
    AND seconds_in_wait >= 500
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I Have this query that is a UNION of 2 queries, but even I take the same columns in both queries, when I execute it I got an error

   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE status = 'ACTIVE'
            AND username <> 'SYSTEM' AND username <> 'SYS'
            AND osuser <> 'NT AUTHORITY\SYSTEM'
            AND osuser <> 'SYSTEM'
            AND seconds_in_wait >= 500

 UNION
 SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
from V$SESSION se
    join v$sql sq on sq.ADDRESS = se.SQL_ADDRESS and sq.HASH_VALUE = se.SQL_HASH_VALUE
where blocking_session is not NULL
AND seconds_in_wait >= 500

Body:
Oracle does not support UNION of columns of type CLOB (sql_fulltext in your case) are involved.

If UNION ALL (instead of UNION) works for your query as well, you can use that.

Update

You might need to modify your query slightly to avoid duplicates with UNION ALL (see last boolean expression in first WHERE clause):

SELECT username,
        sid,
        serial# serial,
        osuser,
        seconds_in_wait,
        sql_address,
        sql_hash_value,
        sql_fulltext
    FROM V$SESSION se
    JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
    WHERE status = 'ACTIVE'
        AND username <> 'SYSTEM' AND username <> 'SYS'
        AND osuser <> 'NT AUTHORITY\SYSTEM'
        AND osuser <> 'SYSTEM'
        AND seconds_in_wait >= 500
        AND blocking_session is NULL
UNION ALL
SELECT username,
        sid,
        serial# serial,
        osuser,
        seconds_in_wait,
        sql_address,
        sql_hash_value,
        sql_fulltext
FROM V$SESSION se
JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
    AND sq.HASH_VALUE = se.SQL_HASH_VALUE
WHERE blocking_session is not NULL
    AND seconds_in_wait >= 500


问:
XML serialization library interoperability between Java and Python
I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream that would have done it for me. Thrift or such other libraries is not going to work unless they allow the data format to be xml. I am looking for suggestion for any library that can do it. - Thanks</p>

答:
Does it really need to use XML?

For serializing structured data between Java and Python you might want to consider Google Protocol Buffers.

ContentLicense: CC BY-SA 2.5


问:
Add variable prefix to angular routing
I am trying to update an old BackBone.js app to Angular (4/5).
One of the requirements is to keep using the old routes in this new app, which triggers some challenges.

The old routes are build as follows:

```<code>site.com/r/{username}/{route}
</code>```

e.g.

```<code>site.com/r/johndoe/homepage
site.com/r/janedoe/blog
</code>```

I'm now using Angular routing without hash, but every route i build in Angular now consists of a long string:

```<code>{ path: '/r/:username/homepage' }
</code>```

I'm hoping there is a cleaner way to uses routes in here.
The :username variable is only needed when bootstrapping the app, so it would be a lot nicer to strip the first bit off of the Url and start NG route paths after this.

I know base href will compile the app to a potential subdirectory, but this will not work with the variable username.

Is there a way to make this work in Angular?

答:
You can do something like this:

```<code>const appRoutes: Routes = [
 {
   path: 'r',
   component: AppComponent,
   children: [
      { path: ':username/homepage', component: HomePageComponent },
      // other children or you can use loadChildren
   ]
 }
];
</code>```

https://angular.io/guide/router#lazy-loading-route-configuration

Title: Add variable prefix to angular routing

Body:
I am trying to update an old BackBone.js app to Angular (4/5).
One of the requirements is to keep using the old routes in this new app, which triggers some challenges.

The old routes are build as follows:

site.com/r/{username}/{route}

e.g.

site.com/r/johndoe/homepage
site.com/r/janedoe/blog

I'm now using Angular routing without hash, but every route i build in Angular now consists of a long string:

{ path: '/r/:username/homepage' }

I'm hoping there is a cleaner way to uses routes in here.
The :username variable is only needed when bootstrapping the app, so it would be a lot nicer to strip the first bit off of the Url and start NG route paths after this.

I know base href will compile the app to a potential subdirectory, but this will not work with the variable username.

Is there a way to make this work in Angular?

Body:
You can do something like this:

const appRoutes: Routes = [
 {
   path: 'r',
   component: AppComponent,
   children: [
      { path: ':username/homepage', component: HomePageComponent },
      // other children or you can use loadChildren
   ]
 }
];

https://angular.io/guide/router#lazy-loading-route-configuration


问:
Inserting into child table getting foreign key error using EF and dbcontext
Hello I'm fairly new to ASP MVC so I'm a little stuck resolving this issue.

The table structure has a job as the parent and then task assigned within that job (jobdetails) as the child.  The jobsdetail table has a foreignkey (jobsid) to the jobs table.

When I try to save a record, I get

Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.JobDetails_dbo.Jobs_jobsid". The conflict occurred in database "NavTracking", table "dbo.Jobs", column 'Id'.
  The statement has been terminated."

I suspect the issue is on the : _context.JobDetail.Add(JobDetail); line because its trying to insert a jobsid but not sure.

Here is my class:

```<code>public class JobDetails
{
    public int Id { get; set; }

    [ForeignKey("jobsid")]
    public virtual Jobs Job { get; set; }

    public int jobsid { get; set; }

    public JobType jobtype { get; set; }

    public int jobtypeid { get; set; }

    public Status status { get; set; }

    public int? statusID { get; set; }

    public DateTime? ReqDate { get; set; }

    public int? EtcStatus { get; set; }

    public Analysts Analyst { get; set; }

    public int? analystID { get; set; }

    public Priority priority { get; set; }

    public int? priorityID { get; set; }

    public bool IsTaskComplete { get; set; }

    public string SpecialNotes { get; set; }
}
</code>```

My Controller to save the record:

```<code>    [HttpPost]
    public ActionResult SaveTask(JobTaskViewModel JobDetVM)
    {
        var jobex = _context.Job.SingleOrDefault(j => j.Id ==
        if (JobDetVM.Jobdetail.Id == 0)
        {
            JobDetVM.Jobdetail.jobsid=jobex.Id;
            _context.JobDetail.Add(JobDetVM.Jobdetail);
        }
        else
        {
            var jobdetailsInDB = _context.JobDetail.Single(t => t.Id == JobDetail.Id);
            jobdetailsInDB.jobsid = JobDetail.jobsid;
            jobdetailsInDB.jobtypeid = JobDetail.jobtypeid;
            jobdetailsInDB.statusID = JobDetail.statusID;
            jobdetailsInDB.ReqDate = JobDetail.ReqDate;
            jobdetailsInDB.EtcStatus = JobDetail.EtcStatus;
            jobdetailsInDB.analystID = JobDetail.analystID;
            jobdetailsInDB.priorityID = JobDetail.priorityID;
            jobdetailsInDB.IsTaskComplete = JobDetail.IsTaskComplete;
            jobdetailsInDB.SpecialNotes = JobDetail.SpecialNotes;
        }
        _context.SaveChanges();

        return RedirectToAction("Index", "Job");
    }
</code>```

and the View to post the data:

```<code>@using (Html.BeginForm("SaveTask", "Job"))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.jobtypeid)
        @Html.DropDownListFor(m => m.Jobdetail.jobtypeid, new SelectList(Model.Jobtype, "Id", "JobTypeVal"), "Select Job Type", new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.ReqDate)
        @Html.TextBoxFor(m => m.Jobdetail.ReqDate, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.EtcStatus)
        @Html.TextBoxFor(m => m.Jobdetail.EtcStatus, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.analystID)
        @Html.DropDownListFor(m => m.Jobdetail.analystID, new SelectList(Model.Analyst, "Id", "AnalystName"), "Select Analyst", new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.priorityID)
        @Html.DropDownListFor(m => m.Jobdetail.priorityID, new SelectList(Model.Priority, "Id", "PriorityVal"), "Select Priority", new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.statusID)
        @Html.DropDownListFor(m => m.Jobdetail.statusID, new SelectList(Model.Status, "Id", "StatusVal"), "Select Status", new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Jobdetail.SpecialNotes)
        @Html.TextBoxFor(m => m.Jobdetail.SpecialNotes, new { @class = "form-control" })
    </div>

    @Html.HiddenFor(m => m.Jobdetail.Id)
    @Html.HiddenFor(m => m.Jobdetail.jobsid)
    <button type="submit" class="btn btn-primary">Save</button>

}
</code>```

My View Model:

```<code>   public class JobTaskViewModel
    {
        public JobDetails Jobdetail { get; set; }

        public Jobs Job { get; set; }

        public int jobsID { get; set; }

        public IEnumerable<Status> Status { get; set; }

        public IEnumerable<Analysts> Analyst { get; set; }

        public IEnumerable<JobType> Jobtype { get; set; }

        public IEnumerable<Priority> Priority { get; set; }

    }
</code>```

答:
Ok I found the answer.  I needed to pass the Job_id in the View back to the controller so my submit looks like this:

```<code>@Html.HiddenFor(m => m.Job.Id)
<button type="submit" value="Job.Id" class="btn btn-primary">Save</button>
</code>```

Thanks for the help

Body:
Hello I'm fairly new to ASP MVC so I'm a little stuck resolving this issue.

The table structure has a job as the parent and then task assigned within that job (jobdetails) as the child.  The jobsdetail table has a foreignkey (jobsid) to the jobs table.

When I try to save a record, I get

Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.JobDetails_dbo.Jobs_jobsid". The conflict occurred in database "NavTracking", table "dbo.Jobs", column 'Id'.
  The statement has been terminated."

I suspect the issue is on the : _context.JobDetail.Add(JobDetail); line because its trying to insert a jobsid but not sure.

Here is my class:

public class JobDetails
{
    public int Id { get; set; }

    [ForeignKey("jobsid")]
    public virtual Jobs Job { get; set; }

    public int jobsid { get; set; }

    public JobType jobtype { get; set; }

    public int jobtypeid { get; set; }

    public Status status { get; set; }

    public int? statusID { get; set; }

    public DateTime? ReqDate { get; set; }

    public int? EtcStatus { get; set; }

    public Analysts Analyst { get; set; }

    public int? analystID { get; set; }

    public Priority priority { get; set; }

    public int? priorityID { get; set; }

    public bool IsTaskComplete { get; set; }

    public string SpecialNotes { get; set; }
}

My Controller to save the record:

    [HttpPost]
    public ActionResult SaveTask(JobTaskViewModel JobDetVM)
    {
        var jobex = _context.Job.SingleOrDefault(j => j.Id ==
        if (JobDetVM.Jobdetail.Id == 0)
        {
            JobDetVM.Jobdetail.jobsid=jobex.Id;
            _context.JobDetail.Add(JobDetVM.Jobdetail);
        }
        else
        {
            var jobdetailsInDB = _context.JobDetail.Single(t => t.Id == JobDetail.Id);
            jobdetailsInDB.jobsid = JobDetail.jobsid;
            jobdetailsInDB.jobtypeid = JobDetail.jobtypeid;
            jobdetailsInDB.statusID = JobDetail.statusID;
            jobdetailsInDB.ReqDate = JobDetail.ReqDate;
            jobdetailsInDB.EtcStatus = JobDetail.EtcStatus;
            jobdetailsInDB.analystID = JobDetail.analystID;
            jobdetailsInDB.priorityID = JobDetail.priorityID;
            jobdetailsInDB.IsTaskComplete = JobDetail.IsTaskComplete;
            jobdetailsInDB.SpecialNotes = JobDetail.SpecialNotes;
        }
        _context.SaveChanges();

        return RedirectToAction("Index", "Job");
    }

and the View to post the data:

@using (Html.BeginForm("SaveTask", "Job"))
{

        @Html.LabelFor(m => m.Jobdetail.jobtypeid)
        @Html.DropDownListFor(m => m.Jobdetail.jobtypeid, new SelectList(Model.Jobtype, "Id", "JobTypeVal"), "Select Job Type", new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.ReqDate)
        @Html.TextBoxFor(m => m.Jobdetail.ReqDate, new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.EtcStatus)
        @Html.TextBoxFor(m => m.Jobdetail.EtcStatus, new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.analystID)
        @Html.DropDownListFor(m => m.Jobdetail.analystID, new SelectList(Model.Analyst, "Id", "AnalystName"), "Select Analyst", new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.priorityID)
        @Html.DropDownListFor(m => m.Jobdetail.priorityID, new SelectList(Model.Priority, "Id", "PriorityVal"), "Select Priority", new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.statusID)
        @Html.DropDownListFor(m => m.Jobdetail.statusID, new SelectList(Model.Status, "Id", "StatusVal"), "Select Status", new { @class = "form-control" })

        @Html.LabelFor(m => m.Jobdetail.SpecialNotes)
        @Html.TextBoxFor(m => m.Jobdetail.SpecialNotes, new { @class = "form-control" })

    @Html.HiddenFor(m => m.Jobdetail.Id)
    @Html.HiddenFor(m => m.Jobdetail.jobsid)
    <button type="submit" class="btn btn-primary">Save</button>

}

My View Model:

   public class JobTaskViewModel
    {
        public JobDetails Jobdetail { get; set; }

        public Jobs Job { get; set; }

        public int jobsID { get; set; }

        public IEnumerable<Status> Status { get; set; }

        public IEnumerable<Analysts> Analyst { get; set; }

        public IEnumerable<JobType> Jobtype { get; set; }

        public IEnumerable<Priority> Priority { get; set; }

    }

Body:
Ok I found the answer.  I needed to pass the Job_id in the View back to the controller so my submit looks like this:

@Html.HiddenFor(m => m.Job.Id)
<button type="submit" value="Job.Id" class="btn btn-primary">Save</button>

Thanks for the help


问:
Can't resolve all parameters for AuthGuard
I have this AuthGuard:

```<code>export class AuthGuard implements CanActivate {

  constructor (private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (localStorage.getItem('token')) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }
}
</code>```

And I have provided it in my AppModule:

```<code>@NgModule({
  declarations: [/*...*/],
  imports: [NotificationRoutingModule],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

And i tried to use this guard in my routing module like this:

```<code>const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: [AuthGuard]},
      {path: ':id', component: NotificationDetailComponent, canActivate: [AuthGuard]}
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class NotificationRoutingModule {
}
</code>```

And I get this error:

Did I miss something? Where is the source of this error?

EDIT:
I am using Angular 4.4.6

It work fine when I use the basic route guard, and updated the route configurations:

```<code>@NgModule({
  declarations: [],
  imports: [],
  providers: [
    {
      provide: 'CannotBeActivated',
      useValue: () => {
        return false;
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent,
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: ['CannotBeActivated']},
      {path: ':id', component: NotificationDetailComponent, canActivate: ['CannotBeActivated']}
    ]
  }
];
</code>```

**My tsconfig.json: **

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
</code>```

答: You just missed to put @Injectable() before your AuthGuard service</p>

ContentLicense: CC BY-SA 4.0

Body:
I have this AuthGuard:

export class AuthGuard implements CanActivate {

  constructor (private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (localStorage.getItem('token')) {
      return true;
    }

    this.router.navigate(['/login']);
    return false;
  }
}

And I have provided it in my AppModule:

@NgModule({
  declarations: [/*...*/],
  imports: [NotificationRoutingModule],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
}

And i tried to use this guard in my routing module like this:

const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: [AuthGuard]},
      {path: ':id', component: NotificationDetailComponent, canActivate: [AuthGuard]}
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class NotificationRoutingModule {
}

And I get this error:

Did I miss something? Where is the source of this error?

EDIT:
I am using Angular 4.4.6

It work fine when I use the basic route guard, and updated the route configurations:

@NgModule({
  declarations: [],
  imports: [],
  providers: [
    {
      provide: 'CannotBeActivated',
      useValue: () => {
        return false;
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

const routes = [
  {
    path: 'notification',
    component: NotificationRootComponent,
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: NotificationListComponent, canActivate: ['CannotBeActivated']},
      {path: ':id', component: NotificationDetailComponent, canActivate: ['CannotBeActivated']}
    ]
  }
];

**My tsconfig.json: **

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}


问:
Postgres SQL Query about database and table space
What is the hierarchy of Database related objects in postgres SQL?
Should it be like, table space must be created at instance level unlike other RDBMS(where we have table space under database).
If so we create the table space at instance level, what is the purpose of database? and what is difference between table space and database on postgres server?</p>

答:
Database is where you organize all your objects. Tablespace is just storage space for those object.

You can storage your db object in different Tablespace. For example one table is storage in a Tablespace in diskA but another Table use a Tablespace in diskB to improve the performance. Or maybe you need a tablespace for big tables and dont mind use a slow big HDD for those objects.


问:
Add date on Laravel
When i am using this code it shows an error "Call to a member function addDays() on string" </p>

```<code>public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}
</code>```

答:
Because you're using DB instead of Jobs, you are getting back raw database data instead of a carbon instance.  If you did the same thing with Jobs, you'd get models and the dates would be Carbon:

```<code>$jobsInfoById = Jobs::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
</code>```

To fix it without using Eloquent, do:

```<code>use Carbon\Carbon; //including Carbon already

$jobsInfoById = $jobsInfoById->map(function ($job) {
    return ['created_at' => Carbon::parse($job->created_at)->addDays(30)];
});
</code>```

Carbon instance is created when you are doing the map on the result.

Title: Add date on Laravel

Body:
When i am using this code it shows an error "Call to a member function addDays() on string"

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}

Body:
Because you're using DB instead of Jobs, you are getting back raw database data instead of a carbon instance.  If you did the same thing with Jobs, you'd get models and the dates would be Carbon:

$jobsInfoById = Jobs::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

To fix it without using Eloquent, do:

use Carbon\Carbon; //including Carbon already

$jobsInfoById = $jobsInfoById->map(function ($job) {
    return ['created_at' => Carbon::parse($job->created_at)->addDays(30)];
});

Carbon instance is created when you are doing the map on the result.


问:
SQL Select Sub Query
I have the following database tables

```<code>User          List
------        ------
userId (PK)   listId (PK)
fullName      description
              addedById (FK with userId in User table)
              modifiedById (FK with userId in User table)
</code>```

I need to pull out all data from the List table, but instead of showing the IDs for addedById and modifiedById, I need to pull the fullName from the User table.

This query works, and gives me the data I need. However, I'm not sure if there is a better way of constructing this query? I'm not keen on having multiple sub select queries within my main select query, mainly because of performance issues.

```<code>select t1.[description],
   t1.addedById,
   t1.modifiedById,
   (select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
   (select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]

from dbo.List t1
</code>```

I'd really appreciate if anyone could suggest improvements to the query, or advise to keep as is.

Thanks.

答:
Is that double join with same table bothering you? It's not slow, its preferred way of doing it instead making the linked subquery.

I am assuming you got indexes on PK and both FK.

Only thing you can minimize is to lessen the number of joined rows. You can do that
by either using the left inner join or filtering in the end with where clause stating both keys you use in join must be not null

I can write both examples for you but this should be self explanatory.

Other mayor thing you can do is to PRESELECT values from users. For example if you have a shit ton of users, and you know only few of them can be in either role. And you can filter which ones by some column in Users you haven't listed, even better if that column has an index.

Then you can maybe profit from pre-selecting only those users and then joining to selection result. Either by temp table if both can be pre-selected or by making a select on spot instead joining to the entire table. Not sure about numbers we are dealing with here for this to become relevant..

Title: SQL Select Sub Query

Body:
I have the following database tables

User          List
------        ------
userId (PK)   listId (PK)
fullName      description
              addedById (FK with userId in User table)
              modifiedById (FK with userId in User table)

I need to pull out all data from the List table, but instead of showing the IDs for addedById and modifiedById, I need to pull the fullName from the User table.

This query works, and gives me the data I need. However, I'm not sure if there is a better way of constructing this query? I'm not keen on having multiple sub select queries within my main select query, mainly because of performance issues.

select t1.[description],
   t1.addedById,
   t1.modifiedById,
   (select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
   (select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]

from dbo.List t1

I'd really appreciate if anyone could suggest improvements to the query, or advise to keep as is.

Thanks.


问:
Is foreach guaranteed to iterate in the array order in php?
When an array is passed to foreach is the output order guaranteed to be the same as the input? I know in some languages that the output order is not guaranteed since each element is processed at the same time.

For example, I'm passing a sorted array to foreach to write to a file. I want to be sure that the array will be sorted in the output file.

答: Yes - the items will be output in the same order they are in within the array.</p>


问:
Number value from Science Notation to Decimal Notation
I have a lot of data in Science notation when I load this data into my double variable, everything works fine (in VS I see value 0.00000000022). But when I multiply this number by 1000000 I got unrounded value (0.00021999999999999998).

I must multiply this value because I use it for selection filter. After send data from selection filter I again divide this data to my raw format 0.00021999999999999998 / 1000000 = 0.00000000022.

2.20E-10 = 0.00000000022 * 1000000 = 0.00021999999999999998

Expected value is this:

0.00021999999999999998 => 0.00022

When I use a similar number, for example, 2.70E-10 I got after multiple value 0.00027 (In this case conversion work fine).

Values are converted only for use in the selection menu so that no unnecessary zeros are shown and the label indicates which unit they represent. (For this example from Ohm to microOhm in select box)

Is there any way to correctly convert these values?

I use LINQ for convert this values in  like this:

```<code>var x = y.Select(s => s.Resistance * 1000000).Distinct();
</code>```

答:
problem is floating point numbers, a good article about this is link

use decimal type instead of double for fast solving :)

Body:
I have a lot of data in Science notation when I load this data into my double variable, everything works fine (in VS I see value 0.00000000022). But when I multiply this number by 1000000 I got unrounded value (0.00021999999999999998).

I must multiply this value because I use it for selection filter. After send data from selection filter I again divide this data to my raw format 0.00021999999999999998 / 1000000 = 0.00000000022.

2.20E-10 = 0.00000000022 * 1000000 = 0.00021999999999999998

Expected value is this:

0.00021999999999999998 => 0.00022

When I use a similar number, for example, 2.70E-10 I got after multiple value 0.00027 (In this case conversion work fine).

Values are converted only for use in the selection menu so that no unnecessary zeros are shown and the label indicates which unit they represent. (For this example from Ohm to microOhm in select box)

Is there any way to correctly convert these values?

I use LINQ for convert this values in  like this:

var x = y.Select(s => s.Resistance * 1000000).Distinct();


问:
How to install miniconda on Ubuntu automatically
Download install file Miniconda2-latest-Linux-x86_64.sh from https://conda.io/miniconda.html, install it from command line. There are some questions need to be taken care of manually, like License, install path and adding binary into $PATH. My question is: is there any way to automatically install it by one command? Such as</p>

```<code>bash Miniconda2-latest-Linux-x86_64.sh \
    -license yes -install_path ~/miniconda \
    -to-bash-profile yes
</code>```

答:
You can do

```<code>bash ~/miniconda.sh -b -p $HOME/miniconda
</code>```

-b is for for batch-mode, which includes accepting the license, and with -p you provide the installation path/prefix

Seen here

Body:
Download install file Miniconda2-latest-Linux-x86_64.sh from https://conda.io/miniconda.html, install it from command line. There are some questions need to be taken care of manually, like License, install path and adding binary into $PATH. My question is: is there any way to automatically install it by one command? Such as

bash Miniconda2-latest-Linux-x86_64.sh \
    -license yes -install_path ~/miniconda \
    -to-bash-profile yes

Body:
You can do

bash ~/miniconda.sh -b -p $HOME/miniconda

-b is for for batch-mode, which includes accepting the license, and with -p you provide the installation path/prefix

Seen here


问:
Collision between RestTemplate with basic authentication and exchange method
I am using Spring 4.3 and SpringBoot 1.5 to create a component that has to call an external REST service. This external service requests HTTP Basic Authentication.

I found that SpringBoot provides a very useful builder to set up RestTemplate properties, such as basic authentication, RestTemplateBuilder.

To call the external REST service I have to use the method RestTemplate.exchange, because of the List<T> return type.

```<code>new RestTemplateBuilder().basicAuthorization(username, password)
                         .build()
                         .exchange("/some/path/with/variables",
                                   HttpMethod.GET,
                                   new HttpEntity<>(new HttpHeaders()),
                                   new ParameterizedTypeReference<List<Integer>>() {},
                                   some, params)
</code>```

The problem here is that the signature of the exchange method requests an object of type HttpEntity, that is basically a container of HttpHeaders.

The question is, will the HttpEntity object, passed as input parameter to the exchange method, subscribe the Basic Auth header set using the RestTemplateBuilder.basicAuthorization method?

Thanks a lot.

答:
I have done some experiments during the past couple of days. The instance of HttpEntity passed to the exchange method does not subscribe the information relative to the Basic Authentication set by the RestTemplateBuilder. The two sets of headers are merged into one.

Nice shot, Spring ;)

Body:
I am using Spring 4.3 and SpringBoot 1.5 to create a component that has to call an external REST service. This external service requests HTTP Basic Authentication.

I found that SpringBoot provides a very useful builder to set up RestTemplate properties, such as basic authentication, RestTemplateBuilder.

To call the external REST service I have to use the method RestTemplate.exchange, because of the List<T> return type.

new RestTemplateBuilder().basicAuthorization(username, password)
                         .build()
                         .exchange("/some/path/with/variables",
                                   HttpMethod.GET,
                                   new HttpEntity<>(new HttpHeaders()),
                                   new ParameterizedTypeReference<List<Integer>>() {},
                                   some, params)

The problem here is that the signature of the exchange method requests an object of type HttpEntity, that is basically a container of HttpHeaders.

The question is, will the HttpEntity object, passed as input parameter to the exchange method, subscribe the Basic Auth header set using the RestTemplateBuilder.basicAuthorization method?

Thanks a lot.


问:
Why is this console log posting "undefined"?
i made an array that gets a variable to specify the value i want to display</p>

```<code>var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);
</code>```

答:
Statement fasit[1,3,1,2,3]; - doing nothing.

```<code>var antallSporsmal= 0;
var fasit = [1,3,1,2,3];
console.log(fasit[antallSporsmal]); // output 1
</code>```

as example.

Also new Array() takes as an argument a number and creates an array with a given length.

If need to add some element to array, use arr.push().

Body:
i made an array that gets a variable to specify the value i want to display

var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);

Body:
Statement fasit[1,3,1,2,3]; - doing nothing.

var antallSporsmal= 0;
var fasit = [1,3,1,2,3];
console.log(fasit[antallSporsmal]); // output 1

as example.

Also new Array() takes as an argument a number and creates an array with a given length.

If need to add some element to array, use arr.push().


问:
JPA Hibernate Dynamic entity mapping & persistence at runtime
Basically we have a spring boot application that requires that the user can define his/her own set of fields and that these fields should be persisted in their own class/table through JPA/Hibernate at runtime. These classes will be generated dynamically through bytebuddy.

All that should be done dynamically without having to restart the application.
The Hibernate Dynamic mapping is not an option, since we will be creating new classes entirely and re-map them.

I have also considered an EAV model but that will not work since we will need separate tables for each set of data so the JSON cannot be mixed in the same table.

The first solution that I'm considering is to proxy the EntityManagetFactory and when we have a new entity to map , I'll re-create the EntityManagetFactory  and add the new mapped entity to it, I'll also have the hbm2ddl.auto set to "update" in order to ensure that the new tables scheme will get created.

Problem is that I don't know what other classes that might need proxying, I believe I'll have to proxy the Hibernate SessionFactory but I'm not sure how many other classes that will need to be re-created and proxied and I believe that this is a complex path to go.

The other solution is to mix between the SQL and NoSQL solution by using Hibernate OGM, but in that case I'll loose any relationship that I can have with the existing SQL entities and I'm not in favor of running a second NoSQL DB.

is there are any other solutions I can explore ?

Edit:

I would use bytebuddy in order to generate the new classes dynamically and they would have the @Entity annotation, the generated classes are written into a temporary jar file ( e.g. /tmp/myjar.jar )

Using a BeanPostProcessor.postProcessAfterInitialization I would replace the LocalContainerEntityManagerFactoryBean with a proxy class.

Also I used the LocalContainerEntityManagerFactoryBean .setPersistenceUnitPostProcessors to add an extra processor that would process the classes from the newly created jar

So now after creating the new class with bytebuddy I would manually call the LocalContainerEntityManagerFactoryBeanProxy.afterProperties that does all the job of bootstrapping the JPA and hibernate layer , I do also set the "hibernate.hbm2ddl.auto" property to "update" so that the schema would be created ( I know that this is risky to be done in a production environment )

答:
Firstly, the problem is how to add entity class in hot-deploy. We could do it by some tools of swapping (spring-boot-devtools, or maven copy resource).
Secondly, to architect the different models of an entity, could use JPA Inheritance(https://en.wikibooks.org/wiki/Java_Persistence/Inheritance)
or JPA row mapper.

But, I see it is more easily to persistence JSON object as text in the database, and left the consumer(front or another service) of the service to parse it.

Another way to do it, is to try load class in runtime by its class path. I will try to persistence Json object as text and its type in ddbb. Then in application.properties create the mapping of its type and classpath (the class java of the data), then do something like:

```<code>static{
     Map<String, String> typeClassPathMap = ......// from properties
     File file = new File("c:\\class-path\\");
    // Convert File to a URL
    URL url = file.toURL();
    // file:/c:/myclasses/
    URL[] urls = new URL[]{url};
    ClassLoader cl = new URLClassLoader(urls);
}

 Class<?> loadClass(String type){

    Class clazz = urlClassLoader.loadClass(typeClassPathMap.get(type));
 }
</code>```

It will read class in runtime and is configurable by properties. After that, for each type of data, we define su type and class path in the property file. When data come from ddbb, we use its type to get the java class, and parse it to object. When we need to create new type of data, we left the class in class-path, and configure it in properties.

Body:
Firstly, the problem is how to add entity class in hot-deploy. We could do it by some tools of swapping (spring-boot-devtools, or maven copy resource).
Secondly, to architect the different models of an entity, could use JPA Inheritance(https://en.wikibooks.org/wiki/Java_Persistence/Inheritance)
or JPA row mapper.

But, I see it is more easily to persistence JSON object as text in the database, and left the consumer(front or another service) of the service to parse it.

Another way to do it, is to try load class in runtime by its class path. I will try to persistence Json object as text and its type in ddbb. Then in application.properties create the mapping of its type and classpath (the class java of the data), then do something like:

static{
     Map<String, String> typeClassPathMap = ......// from properties
     File file = new File("c:\\class-path\\");
    // Convert File to a URL
    URL url = file.toURL();
    // file:/c:/myclasses/
    URL[] urls = new URL[]{url};
    ClassLoader cl = new URLClassLoader(urls);
}

 Class<?> loadClass(String type){

    Class clazz = urlClassLoader.loadClass(typeClassPathMap.get(type));
 }

It will read class in runtime and is configurable by properties. After that, for each type of data, we define su type and class path in the property file. When data come from ddbb, we use its type to get the java class, and parse it to object. When we need to create new type of data, we left the class in class-path, and configure it in properties.


问:
How to pass data to child component in vue.js
I'm new to vue.js and I try to pass a value to the child component.

HTML

```<code><div id="example">
   <my-component v-bind:data="parentData"></my-component>
</div>
</code>```

JS

```<code>Vue.component('my-component', {
  props: ['data'],
  template: '<div>Parent component with data: {{ data.value }}!<div is="my-component-child" v-bind:data="childData"></div></div>'
});

Vue.component('my-component-child', {
  props: ['data'],
  template: '<div>Child component with data: {{ data.value }} </div>'
});

new Vue({
  el: '#example',
  data: {
    parentData: {
      value: 'hello parent!'
    },
    childData: {
      value: 'hello child!'
    }
  }
});
</code>```

https://jsfiddle.net/v9osont9/2/

And I've got this error:

[Vue warn]: Property or method "childData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
  (found in )

[Vue warn]: Error in render function:
  (found in )

TypeError: Cannot read property 'value' of undefined

What is the proper way to do this?

答:
When you call

```<code><my-component v-bind:data="parentData"></my-component>
</code>```

you are passing only the parentData to your parent component and childData gets out of scope.

You need to nest your childData in your parentData:

```<code>new Vue({
    el: '#example',
    data: {
        parentData: {
            value: 'hello parent!',
            childData: {
                value: 'hello child!'
            }
        }
    }
});
</code>```

and pass it to your child like this:

```<code><div is="my-component-child" v-bind:data="data.childData">
</code>```

Body:
I'm new to vue.js and I try to pass a value to the child component.

HTML

   <my-component v-bind:data="parentData"></my-component>

JS

Vue.component('my-component', {
  props: ['data'],
  template: '
Parent component with data: {{ data.value }}!

'
});

Vue.component('my-component-child', {
  props: ['data'],
  template: '
Child component with data: {{ data.value }}
'
});

new Vue({
  el: '#example',
  data: {
    parentData: {
      value: 'hello parent!'
    },
    childData: {
      value: 'hello child!'
    }
  }
});

https://jsfiddle.net/v9osont9/2/

And I've got this error:

[Vue warn]: Property or method "childData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
  (found in )

[Vue warn]: Error in render function:
  (found in )

TypeError: Cannot read property 'value' of undefined

What is the proper way to do this?

Body:
When you call

<my-component v-bind:data="parentData"></my-component>

you are passing only the parentData to your parent component and childData gets out of scope.

You need to nest your childData in your parentData:

new Vue({
    el: '#example',
    data: {
        parentData: {
            value: 'hello parent!',
            childData: {
                value: 'hello child!'
            }
        }
    }
});

and pass it to your child like this:

<div is="my-component-child" v-bind:data="data.childData">


问:
How do I run .sh or .bat files from Terminal?
I have a pretty basic problem here, that has happened so haphazardly to me that up until now, I've just ignored it. I downloaded tomcat web server and "Murach's Java Servlets and JSP" book is telling me to navigate to the tomcat/bin directory and start the server my typing in Terminal

$ startup

However, I get the error

```<code>-bash: startup: command not found
</code>```

The relevant files in this directory are startup.sh and startup.bat. Typing both of these returns the same error message

So my questions are, what are .bat and sh files, and how do I run these files? I've read several tutorials for different languages and software programs, and some times when the tutorial says execute a bunch of files in the command line, I get a "command not found" error. Sometimes it works, sometimes it doesn't. This is perplexing to me, so what are some common solutions to solving these sort of "command not found" Terminal problems?

答:
Type in

```<code>chmod 755 scriptname.sh
</code>```

In other words, give yourself permission to run the file. I'm guessing you only have r/w permission on it.

Body:
I have a pretty basic problem here, that has happened so haphazardly to me that up until now, I've just ignored it. I downloaded tomcat web server and "Murach's Java Servlets and JSP" book is telling me to navigate to the tomcat/bin directory and start the server my typing in Terminal

$ startup

However, I get the error

-bash: startup: command not found

The relevant files in this directory are startup.sh and startup.bat. Typing both of these returns the same error message

So my questions are, what are .bat and sh files, and how do I run these files? I've read several tutorials for different languages and software programs, and some times when the tutorial says execute a bunch of files in the command line, I get a "command not found" error. Sometimes it works, sometimes it doesn't. This is perplexing to me, so what are some common solutions to solving these sort of "command not found" Terminal problems?

Body:
Type in

chmod 755 scriptname.sh

In other words, give yourself permission to run the file. I'm guessing you only have r/w permission on it.


问:
Css only or jquery - how to hide navbar on mobile devices - what am I doing wrong?
I want to show the navbar only on devices bigger than ipad and on smaller devices a different styled navbar. I tried it

1) css only using display:none for smaller devices

```<code>  @media (max-width: 768px) {
    nav {
      display:none;
    }
  }
</code>```

2) css only using visibility: hidden / visibility:visible

```<code>    @media (min-width: 768px) {
    nav
    {
        visibility:visible;
    }
}

@media (max-width: 768px) {
    nav
    {
        visibility:hidden;
    }
}
</code>```

3) used jquery

```<code>$(window).on("orientationchange load resize", function () {
     var width = $(document).width();
     if(width<765){
       $("#navbar").hide();
     }
     else if(width>765){
              $("#navbar").show();
     }
});
</code>```

see jsfiddle (with jquery): https://jsfiddle.net/codingcodingcoding/913j87bb/

Nothing works. If anyone knows why, please tell me.

答:
If you add to your jsfiddle (at the css window):

```<code>@media (max-width: 768px) {
  nav {
    display:none;
  }
}
</code>```

it works. Checked it by reducing result window. You don't need jquery for this.

Hope it helps.

Body:
I want to show the navbar only on devices bigger than ipad and on smaller devices a different styled navbar. I tried it

1) css only using display:none for smaller devices

  @media (max-width: 768px) {
    nav {
      display:none;
    }
  }

2) css only using visibility: hidden / visibility:visible

    @media (min-width: 768px) {
    nav
    {
        visibility:visible;
    }
}

@media (max-width: 768px) {
    nav
    {
        visibility:hidden;
    }
}

3) used jquery

$(window).on("orientationchange load resize", function () {
     var width = $(document).width();
     if(width<765){
       $("#navbar").hide();
     }
     else if(width>765){
              $("#navbar").show();
     }
});

see jsfiddle (with jquery): https://jsfiddle.net/codingcodingcoding/913j87bb/

Nothing works. If anyone knows why, please tell me.

Body:
If you add to your jsfiddle (at the css window):

@media (max-width: 768px) {
  nav {
    display:none;
  }
}

it works. Checked it by reducing result window. You don't need jquery for this.

Hope it helps.


问:
Date conversion with different gmt
I have two dates in my database

This date is from an api - 16 Nov 2017 10:54:12 +0000

This date is from my server - 16 Nov 2017 16:24:12 +0530

I want to convert this date into 16 Nov 2017 10:54:12 +0000 in my server time.

Title: Date conversion with different gmt

Body:
$value = "16 Nov 2017 10:54:12 +0000";
echo date(DATE_RFC822, strtotime($value));


问:
MySQL View Optimization
I have a view (say 'v') that is the combination of 10 tables using several Joins and complex calculations. In that view, there are around 10 Thousand rows.

And then I select 1 row based on row as WHERE id = 23456.

Another possible way to use a larger query in which I can cut short the dataset to 1% before the complex calculation starts.

Question: Are SQL views optimized in some form?

答:
MySQL Views are just syntactic sugar.  There is not special optimization.  Think of views as being textually merged; then optimized.  That is, you could get the same optimizations (or not) by manually writing the equivalent SELECT.

If you would like to discuss the particular query further, please provide SHOW CREATE TABLE/VIEW and EXPLAIN SELECT ....  It may be that you are missing a useful 'composite' index.

Title: MySQL View Optimization


答:
Did you mean this

```<code>var antallSporsmal= 0;
var fasit = [1,3,1,2,3];
console.log(fasit[antallSporsmal]);
</code>```

You can also use push

```<code>var fasit=new Array();
fasit.push(1,3,1,2,4);
console.log(fasit[0]);
</code>```

Title: Why is this console log posting "undefined"?

Body:
Did you mean this

var antallSporsmal= 0;
var fasit = [1,3,1,2,3];
console.log(fasit[antallSporsmal]);

You can also use push

var fasit=new Array();
fasit.push(1,3,1,2,4);
console.log(fasit[0]);


答:
Here is goes:

Your code:

```<code>var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);
</code>```

Code you should use:

```<code>var fasit =[1,3,1,2,3];
var antallSporsmal= 0;
console.log(fasit[antallSporsmal]);
</code>```

Body:
Here is goes:

Your code:

var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);

Code you should use:

var fasit =[1,3,1,2,3];
var antallSporsmal= 0;
console.log(fasit[antallSporsmal]);


问:
Can you navigate the contents of a Vector's index via a String?
Is it possible to do something similar to this in Haxe?

```<code>private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";
</code>```

What I would like to be able to do:

```<code>_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"
</code>```

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).

答:
Short answer: yes, you can.

```<code>abstract MyVector<T>(Vector<T>) {
public function new(l:Int) this = new Vector<T>(l);
@:op([]) public function set<K:T>(s:String, v:K) {
    switch (s) {
        case "FIRST": this[0] = v;
        case "SECOND": this[1] = v;
        default: return;
    }
}
@:op([]) public function get(s:String) {
    switch (s) {
        case "FIRST": return this[0];
        case "SECOND": return this[1];
        default: return cast 0;
    }
 }
</code>```

}

```<code>    var mv = new MyVector<String>(2);
    mv["SECOND"] = "Second";
    trace(mv["SECOND"]); // outputs Second
</code>```

You can inline get and set methods if you want.

Body:
Is it possible to do something similar to this in Haxe?

private var _bindingsFiltered:Vector<String>;
_bindingsFiltered = new Vector<String>();

_controller_touched_binding.action = "meta_start";

What I would like to be able to do:

_bindingsFiltered[_controller_touched_binding.action] = "BUTTON_13";
trace(_bindingsFiltered["meta_start"]); //result: "BUTTON_13"

I want to be able to override a specific index too (still accessed via a string), with a new value, rather than keep pushing new content to the end of the vector. I have been using 'openfl.utils.Object' to cheat for now but I am looking for a more reliable approach for the long run.

Is there a way to do this in Haxe?

If not, what are my options?

I would also be interested in a solution for this in AS3, if there is one (avoiding the Array class).

My goal is to find a method that I can use in both languages seamlessly (next-to-none, differences).

Body:
Short answer: yes, you can.

abstract MyVector<T>(Vector<T>) {
public function new(l:Int) this = new Vector<T>(l);
@:op([]) public function set<K:T>(s:String, v:K) {
    switch (s) {
        case "FIRST": this[0] = v;
        case "SECOND": this[1] = v;
        default: return;
    }
}
@:op([]) public function get(s:String) {
    switch (s) {
        case "FIRST": return this[0];
        case "SECOND": return this[1];
        default: return cast 0;
    }
 }

}

    var mv = new MyVector<String>(2);
    mv["SECOND"] = "Second";
    trace(mv["SECOND"]); // outputs Second

You can inline get and set methods if you want.


问:
Nginx subdirectory root with PHP
I'm running nginx in a docker container. I want to have a subdirectory /web/ to access my personal files and projects. It should also support php.

Below is what I'm running with but domain-a.com/web keeps resulting in a 404. PHP is confirmed working since the same php block works on a subdomain but directly in a server{} block.

```<code>http {

    server {
        listen      443 ssl;
        server_name domain-a.com domain-b.com;

        # Mime types
        include /etc/nginx/confs/mime.types;

        # SSL
        include /etc/nginx/confs/nginx-ssl.conf;

        # Proxy to organizr
        # This works
        location / {
            proxy_pass http://organizr/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # HTTP 1.1 support
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # Root folder for my personal files/projects
        # Doesn't work
        location /web {
            index index.php index.html;
            root /etc/nginx/www;

            location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass php:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_path_info;
            }
        }
    }
}
</code>```

答:
If your files are in /etc/nginx/www you will need to use an alias directive, rather than a root directive. See this document for details.

For example:

```<code>location ^~ /web {
    index index.php index.html;
    alias /etc/nginx/www;

    if (!-e $request_filename) { rewrite ^ /web/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}
</code>```

Use $request_filename to obtain the correct path to the aliased file. Avoid try_files with alias due to this issue. See this caution on the use of if.

Title: Nginx subdirectory root with PHP

Body:
I'm running nginx in a docker container. I want to have a subdirectory /web/ to access my personal files and projects. It should also support php.

Below is what I'm running with but domain-a.com/web keeps resulting in a 404. PHP is confirmed working since the same php block works on a subdomain but directly in a server{} block.

http {

    server {
        listen      443 ssl;
        server_name domain-a.com domain-b.com;

        # Mime types
        include /etc/nginx/confs/mime.types;

        # SSL
        include /etc/nginx/confs/nginx-ssl.conf;

        # Proxy to organizr
        # This works
        location / {
            proxy_pass http://organizr/;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            # HTTP 1.1 support
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        # Root folder for my personal files/projects
        # Doesn't work
        location /web {
            index index.php index.html;
            root /etc/nginx/www;

            location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass php:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_path_info;
            }
        }
    }
}

Body:
If your files are in /etc/nginx/www you will need to use an alias directive, rather than a root directive. See this document for details.

For example:

location ^~ /web {
    index index.php index.html;
    alias /etc/nginx/www;

    if (!-e $request_filename) { rewrite ^ /web/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

Use $request_filename to obtain the correct path to the aliased file. Avoid try_files with alias due to this issue. See this caution on the use of if.


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
Using binary serialization to BLOB column, or using XML\Data contact\net Data contact to XML column.

Edit: Binary example already given by @Saurabh. Data contract example provided by Peter Ritchie's blog.


问:
Parse from TableVC to textView in other viewController swift
I am new in programming, and have problem. I am using parse for my array in  tableview. When the row is selected i want to segue on another view controller to textView. The tableview works good but i can't get text to textView.

tableVC:

```<code>import UIKit
import Parse
class ThirdTableVC: UITableViewController {
@IBOutlet weak var refresherQuotes: UIRefreshControl!
@IBOutlet var quoteTable: UITableView!

var selectedQuote: PFObject?
var quoteItems = [PFObject]()

override func viewDidLoad() {
    super.viewDidLoad()

}
@IBAction func updateQuotesResults(_ sender: UIRefreshControl) {
    fetchQuotesData()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    loadQuoteTexts(selectedQuote: selectedQuote)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return quoteItems.count
}

func fetchQuotesData() {
    let quotesQuery = PFQuery(className: "TotalTest")
    quotesQuery.whereKey("Subcategory", equalTo: selectedQuote ?? nil)
    quotesQuery.findObjectsInBackground { (objects, error) in
        if let realCategoryObjects = objects {
            self.quoteItems = realCategoryObjects
            self.tableView.reloadData()
            self.refresherQuotes.endRefreshing()
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let quoteCell = tableView.dequeueReusableCell(withIdentifier: "quoteCell", for: indexPath)

    let quoteItem = quoteItems[indexPath.row]
    let quoteUserTitle = quoteItem.object(forKey: "TextQuote") as? String

    quoteCell.textLabel?.text = quoteUserTitle

    return quoteCell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showQuoteDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let quoteobject = quoteItems[indexPath.row] as? NSDate
            let quoteController = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            quoteController.detailItem = quoteobject
            quoteController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            quoteController.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Row tapped: \(indexPath.row)")

    let selectedQuotes: PFObject = quoteItems[indexPath.row]
    let  FourthVC = self.storyboard?.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
    FourthVC.fourthTextView.text = quoteItems[indexPath.row] as? String
    self.navigationController?.pushViewController(FourthVC, animated: true)

}

func loadQuoteTexts(selectedQuote: PFObject!) {

    let quoteQuery = PFQuery(className: "TotalQuote")
    quoteQuery.whereKey("QuoteSubs", equalTo: selectedQuote ?? nil)
    quoteQuery.includeKey("QuoteSubs")

    quoteQuery.findObjectsInBackground { (result: [PFObject]?, error) in
        if let searchQuoteResults = result {

            self.quoteItems = searchQuoteResults
            self.quoteTable.reloadData()
        }
    }
}
}
</code>```

How can I change this?
viewController with textView:

```<code> import UIKit
 import Parse

 class FourthViewController: UIViewController {

var getQuote: PFObject?

@IBOutlet weak var fourthTextView: UITextView!
@IBOutlet weak var fourthLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    fourthLabel.text! = getQuote as! String
    fourthTextView.text! = getQuote as! String
}
}
</code>```

Please help me to passing texts

答:
If you use pushViewController do it like that , in did selectRowAt

```<code>let MainStory: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desVC = MainStory.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
</code>```

and now pass your text

```<code>desVC.getText = "here goes your text u want to pass"
</code>```

FourthViewController
set up your var

```<code>var getText = String()
</code>```

so you can finally use

```<code>self.navigationController?.pushViewController(desVC, animated: true)
</code>```

so it will pass all parameters you previous add with desVC.getSomething

in FourthViewController  you just need to use getText.

Body:
I am new in programming, and have problem. I am using parse for my array in  tableview. When the row is selected i want to segue on another view controller to textView. The tableview works good but i can't get text to textView.

tableVC:

import UIKit
import Parse
class ThirdTableVC: UITableViewController {
@IBOutlet weak var refresherQuotes: UIRefreshControl!
@IBOutlet var quoteTable: UITableView!

var selectedQuote: PFObject?
var quoteItems = [PFObject]()

override func viewDidLoad() {
    super.viewDidLoad()

}
@IBAction func updateQuotesResults(_ sender: UIRefreshControl) {
    fetchQuotesData()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    loadQuoteTexts(selectedQuote: selectedQuote)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return quoteItems.count
}

func fetchQuotesData() {
    let quotesQuery = PFQuery(className: "TotalTest")
    quotesQuery.whereKey("Subcategory", equalTo: selectedQuote ?? nil)
    quotesQuery.findObjectsInBackground { (objects, error) in
        if let realCategoryObjects = objects {
            self.quoteItems = realCategoryObjects
            self.tableView.reloadData()
            self.refresherQuotes.endRefreshing()
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let quoteCell = tableView.dequeueReusableCell(withIdentifier: "quoteCell", for: indexPath)

    let quoteItem = quoteItems[indexPath.row]
    let quoteUserTitle = quoteItem.object(forKey: "TextQuote") as? String

    quoteCell.textLabel?.text = quoteUserTitle

    return quoteCell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showQuoteDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let quoteobject = quoteItems[indexPath.row] as? NSDate
            let quoteController = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            quoteController.detailItem = quoteobject
            quoteController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            quoteController.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Row tapped: \(indexPath.row)")

    let selectedQuotes: PFObject = quoteItems[indexPath.row]
    let  FourthVC = self.storyboard?.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
    FourthVC.fourthTextView.text = quoteItems[indexPath.row] as? String
    self.navigationController?.pushViewController(FourthVC, animated: true)

}

func loadQuoteTexts(selectedQuote: PFObject!) {

    let quoteQuery = PFQuery(className: "TotalQuote")
    quoteQuery.whereKey("QuoteSubs", equalTo: selectedQuote ?? nil)
    quoteQuery.includeKey("QuoteSubs")

    quoteQuery.findObjectsInBackground { (result: [PFObject]?, error) in
        if let searchQuoteResults = result {

            self.quoteItems = searchQuoteResults
            self.quoteTable.reloadData()
        }
    }
}
}

How can I change this?
viewController with textView:

 import UIKit
 import Parse

 class FourthViewController: UIViewController {

var getQuote: PFObject?

@IBOutlet weak var fourthTextView: UITextView!
@IBOutlet weak var fourthLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    fourthLabel.text! = getQuote as! String
    fourthTextView.text! = getQuote as! String
}
}

Please help me to passing texts

Body:
If you use pushViewController do it like that , in did selectRowAt

let MainStory: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desVC = MainStory.instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController

and now pass your text

desVC.getText = "here goes your text u want to pass"

FourthViewController
set up your var

var getText = String()

so you can finally use

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

so it will pass all parameters you previous add with desVC.getSomething

in FourthViewController  you just need to use getText.


问:
Web Service checking that DB is available
I need to create an ASP.NET web service that simply returns an information telling if a database is available or down when it's consumed.

So I would like to know if I can set a task that is executed inside the web service method on a regular basis to check the connection to the database and return the result via a URL.

答:
No you cannot. Well, you could, but you really should not. A webservice is on demand. If it's called, it does work. If it's not called, it's not running.

You may have been thinking of a windows service. That is something that is always running and can do stuff in the background.

(A windows service may have an additional web frontend to see it's data. Or any other way to visualize it's data points, for example another database.)


问:
Replacing the values from another data from based on the information in the first column in R
I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data.

I have to dataframes (One is subset of the others with updated info in the last column):

df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))

```<code>  Name val Case
1  A   1   NA
2  B   2    1
3  C   3   NA
4  D   1   NA
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2   NA
9  I   3   NA
</code>```

Some rows in the Case column in df1 have to be changed with the info in the df2 below:

df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")

```<code>    Name val Case
1    A   1    1
2    D   2    1
3    H   3    1
</code>```

So there's nothing important in the val column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples.

Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have df1 as a final data frame.

for a better explanation, I want to see something like this:

```<code>  Name val Case
1  A   1    1
2  B   2    1
3  C   3   NA
4  D   1    1
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2    1
9  I   3   NA
</code>```

Note changed information for A,D and H.

Thanks.

答:
Here is what I would do using dplyr:

```<code>df1 %>%
  left_join(df2, by = c("Name")) %>%
  mutate(val = if_else(is.na(val.y), val.x, val.y),
         Case = if_else(is.na(Case.y), Case.x, Case.y)) %>%
 select(Name, val, Case)
</code>```

Body:
I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data.

I have to dataframes (One is subset of the others with updated info in the last column):

df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))

  Name val Case
1  A   1   NA
2  B   2    1
3  C   3   NA
4  D   1   NA
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2   NA
9  I   3   NA

Some rows in the Case column in df1 have to be changed with the info in the df2 below:

df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")

    Name val Case
1    A   1    1
2    D   2    1
3    H   3    1

So there's nothing important in the val column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples.

Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have df1 as a final data frame.

for a better explanation, I want to see something like this:

  Name val Case
1  A   1    1
2  B   2    1
3  C   3   NA
4  D   1    1
5  E   2    1
6  F   3   NA
7  G   1    1
8  H   2    1
9  I   3   NA

Note changed information for A,D and H.

Thanks.

Body:
Here is what I would do using dplyr:

df1 %>%
  left_join(df2, by = c("Name")) %>%
  mutate(val = if_else(is.na(val.y), val.x, val.y),
         Case = if_else(is.na(Case.y), Case.x, Case.y)) %>%
 select(Name, val, Case)


问:
How to define ApiBlueprint array values example with MSON?
Can I use MSON to specify an example values instead of + Body?
Is it possible to override predefined structure values?

I've tried like this:

```<code>+ Request (application/json)

    + Headers

            Authorization: JWT <token>
    + Attributes (ClientsideCommand)
        + alias: `show-xc`
        + args (array[AppCommandArg], fixed-type)
            + (AppCommandArg)
                + arg_key: address
                + order: 1
                + required: true
                + skip_arg_name: true
            + (AppCommandArg)
                + arg_key: `-A1`
                + order: 2
                + required: true
                + skip_arg_name: false
</code>```

But such definition corrupts json-schema, because AppCommandArg descibed as separate objects.
And also in the JSON generated from the MSON has 3 items where first item is deafult AppCommandArg.

答: Looks like it's not possible to make this things twogether. If you add elements as showed abowe Apiary renders it as it sees it, if an element noted twice the json schema also will describe it twice.</p>

Body:
Can I use MSON to specify an example values instead of + Body?
Is it possible to override predefined structure values?

I've tried like this:

+ Request (application/json)

    + Headers

            Authorization: JWT <token>
    + Attributes (ClientsideCommand)
        + alias: `show-xc`
        + args (array[AppCommandArg], fixed-type)
            + (AppCommandArg)
                + arg_key: address
                + order: 1
                + required: true
                + skip_arg_name: true
            + (AppCommandArg)
                + arg_key: `-A1`
                + order: 2
                + required: true
                + skip_arg_name: false

But such definition corrupts json-schema, because AppCommandArg descibed as separate objects.
And also in the JSON generated from the MSON has 3 items where first item is deafult AppCommandArg.


问:
Is foreach guaranteed to iterate in the array order in php?
When an array is passed to foreach is the output order guaranteed to be the same as the input? I know in some languages that the output order is not guaranteed since each element is processed at the same time.

For example, I'm passing a sorted array to foreach to write to a file. I want to be sure that the array will be sorted in the output file.

答: This is correct, foreach will output in same order as the input array .


问:
filling a dateframe from a list
I tried to create a date frame with lists:

```<code>lista_values  = [2983, 2983, 5652, 12375, 13055, 26180]
labels = ['00_04', '04_08', '08_12', '12_16', '16_20', '20_24']
lista_index = [datetime.datetime(2017, 11, 11, 0, 0)]
df = pd.DataFrame(lista_values,index=lista_index,columns=labels)
</code>```

then my error:

```<code>ValueError: Shape of passed values is (1, 6), indices imply (6, 1)
</code>```

How can I create a data frame with these lists, for example? I really don't understand why is out of bounds here if the columns and labels have same length

Title: filling a dateframe from a list

Body:
I tried to create a date frame with lists:

lista_values  = [2983, 2983, 5652, 12375, 13055, 26180]
labels = ['00_04', '04_08', '08_12', '12_16', '16_20', '20_24']
lista_index = [datetime.datetime(2017, 11, 11, 0, 0)]
df = pd.DataFrame(lista_values,index=lista_index,columns=labels)

then my error:

ValueError: Shape of passed values is (1, 6), indices imply (6, 1)

How can I create a data frame with these lists, for example? I really don't understand why is out of bounds here if the columns and labels have same length

Body:
Now is this what you want? I flipped the dataframe with transpose (T).

import pandas as pd
import datetime

lista_values  = [2983, 2983, 5652, 12375, 13055, 26180]
labels = ['00_04', '04_08', '08_12', '12_16', '16_20', '20_24']
lista_index = [datetime.datetime(2017, 11, 11, 0, 0)]

df = pd.DataFrame(data=lista_values, index=labels, columns = lista_index).T

df

Returns:

            00_04  04_08  08_12  12_16  16_20  20_24
2017-11-11   2983   2983   5652  12375  13055  26180


问:
How bittorrent tracker works?
I read official documetation here and wikipedia article about bittorrent client here but couldn't find how tracker exactly work. As per my understanding tracker should know which peer have which piece of some file. For example client 1 have 5 pieces of file 1 and 10 pieces of file 2. In official documentation I see tracker have fields like peer_id ip port uploaded downloaded left and event but I don't see where is the information about which file we are tracking. For example if I ask tracker hey I need pieces for linux.torrent file, how tracker would answer me?

答:
A trackers job is, when a peer announces to a specific swarm (identified by the info_hash),to register that peer as active on that swarm and then send that peer a peer list with other peers active on that swarm.

A tracker does NOT keep track on which pieces or files a peer has.

I recommend you to read the inoffical protocol specification: https://wiki.theory.org/index.php/BitTorrentSpecification

it's bit easier do comprehend than the terse and dense BEP-3.

Title: How bittorrent tracker works?


问:
how much processes are build after running this code?
this program is running on Unix:

```<code> main(int argc,char** argv)
    {
         forkthem(5)
    }
    void forkthem(int n)
    {
         if(n>0)
         {
             fork();
             forkthem(n-1);
         }
    }
</code>```

we tried to build a tree of processes but we didn't really got an answer.
we will be very thankful if anyone help us.

答:
When n=0, then one process, the original one.

When n=1, then one fork happens, so two processes

When n=2, then each of the two n=1 processes forks again, so 4 processes

...

When n=k,   2**k processes

So, n=5 means 32 processes

Body:
this program is running on Unix:

 main(int argc,char** argv)
    {
         forkthem(5)
    }
    void forkthem(int n)
    {
         if(n>0)
         {
             fork();
             forkthem(n-1);
         }
    }

we tried to build a tree of processes but we didn't really got an answer.
we will be very thankful if anyone help us.


问:
Angular 4+ best practice HTTP service
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

```<code>export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}
</code>```

TaskService

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}
</code>```

TaskComponent

```<code>export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}
</code>```

template

```<code><input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

答:
you're getting that error because you're trying to access the Title property of something that is undefined until the observable finishes.  To guard against this, you should use ngIf:

```<code><input *ngIf="task" type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

this way, your element won't attempt to render until task is a truthy value.

But best practice though, in my opinion, is to use the async pipe always, as this handles subscription management for you and facilitates things like onPush change detection and makes cleaner, more readable code:

```<code>export class TaskComponent implements OnInit {
    task$: Observable<Task>;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.task$ = this.route.params.switchMap(p =>
                             this.taskService.getTask(<number>p.id));
    }
}

<input *ngIf="task$ | async as task" type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

you give async an observable and it subscribes for you and cleans everything up to prevent memory leaks (though that wouldn't be a problem in this specific situation). This makes it more clear what is happening in your code and when and why, as you can see, this change reduced your code quite a bit (in relative terms). It also does allow for you to switch change detection to on push, which is a huge app performance booster.

Title: Angular 4+ best practice HTTP service

Body:
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}

TaskService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}

TaskComponent

export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}

template

<input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

Body:
you're getting that error because you're trying to access the Title property of something that is undefined until the observable finishes.  To guard against this, you should use ngIf:

<input *ngIf="task" type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

this way, your element won't attempt to render until task is a truthy value.

But best practice though, in my opinion, is to use the async pipe always, as this handles subscription management for you and facilitates things like onPush change detection and makes cleaner, more readable code:

export class TaskComponent implements OnInit {
    task$: Observable<Task>;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.task$ = this.route.params.switchMap(p =>
                             this.taskService.getTask(<number>p.id));
    }
}

<input *ngIf="task$ | async as task" type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

you give async an observable and it subscribes for you and cleans everything up to prevent memory leaks (though that wouldn't be a problem in this specific situation). This makes it more clear what is happening in your code and when and why, as you can see, this change reduced your code quite a bit (in relative terms). It also does allow for you to switch change detection to on push, which is a huge app performance booster.


问:
C++ multiple interfaces inheritance and static_cast
In the following code:

Live

```<code>#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}
</code>```

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

答:
The point is that you are doing a static_cast to a different type passing by a void* which hides the actual type to the compiler.

What I mean is that:

```<code>TextView tv;
ITextView* itv = static_cast<ITextView*>(&tv);
</code>```

this is safe, you are explicitly converting to an parent type.

```<code>TextView tv;
void* ptr = &tv;
ITextView* itv = static_cast<ITextView*>(ptr);
</code>```

Here the compiler doesn't know the actual type of ptr and consider it as a ITextView*, so it not able to adjust the pointer to the correct subpart of an object (it is worth noticing that this may seem to work because ITextView doesn't have any member variables). This is related in how inheritance is implemented under the hood, think about:

```<code>---------------------
| VTable A | Type A |
---------------------

---------------------
| VTable B | Type B |
---------------------

-----------------------------------------
| VTable AB | Type A | Type B | Type AB |
-----------------------------------------
</code>```

Suppose this is the memory layout for

```<code>class A { /* members */ };
class B { /* members */ };
class AB : public A, public B { /* members */ };
</code>```

Now this is clear that if you have the address to an AB and you cast it to an B* without letting the compiler know that it was an AB then the compiler is not able to point to the correct Type B part, which resides after Type A slice. This would have been possible to know only by knowing that it was an AB in the first place.

Body:
In the following code:

Live

#include <iostream>
#include <thread>
#include <mutex>
#include <functional>

struct IView {
    virtual void setOnClick() = 0;
};
struct ITextView : IView {
    virtual void setText() = 0;
};
struct IButton : ITextView {
    virtual void setRadius() = 0;
};

struct View : IView {
    int i = 1;
    virtual void setOnClick() override {
        std::cout << "setting OnClick! i: " << i << std::endl;
    };
};

/// Works as is
/// But if make "TextView : View, ITextView" - have segfault on the run
struct TextView : ITextView, View {
    int j = 2;
    virtual void setText() override {
        std::cout << "setting text! i: " << i << " j: " << j << std::endl;
    };

    // forward IView
    virtual void setOnClick() override {
        View::setOnClick();
    }
};

int main() {
    TextView tv;

    void* ptr = &tv;    // I need to pass raw pointer, and then restore "interface" from it

    ITextView* itv = static_cast<ITextView*>(ptr);  // I don't need safety checks here
    itv->setOnClick();
    itv->setText();

    return 0;
}

If I change TextViews inheritance order I'll have segfault on itv->setText(); call.

Why is it important? Can I use static_cast here, or I have UB here? As I understand dynamic_cast only required with virtual inheritance, and this, as I can tell, not that case.

Body:
The point is that you are doing a static_cast to a different type passing by a void* which hides the actual type to the compiler.

What I mean is that:

TextView tv;
ITextView* itv = static_cast<ITextView*>(&tv);

this is safe, you are explicitly converting to an parent type.

TextView tv;
void* ptr = &tv;
ITextView* itv = static_cast<ITextView*>(ptr);

Here the compiler doesn't know the actual type of ptr and consider it as a ITextView*, so it not able to adjust the pointer to the correct subpart of an object (it is worth noticing that this may seem to work because ITextView doesn't have any member variables). This is related in how inheritance is implemented under the hood, think about:

---------------------
| VTable A | Type A |
---------------------

---------------------
| VTable B | Type B |
---------------------

-----------------------------------------
| VTable AB | Type A | Type B | Type AB |
-----------------------------------------

Suppose this is the memory layout for

class A { /* members */ };
class B { /* members */ };
class AB : public A, public B { /* members */ };

Now this is clear that if you have the address to an AB and you cast it to an B* without letting the compiler know that it was an AB then the compiler is not able to point to the correct Type B part, which resides after Type A slice. This would have been possible to know only by knowing that it was an AB in the first place.


问:
how to deploy vue app in the shared hosting environment?
I would like to deploy my vue application on shared hosting server. How should I do it?
Its a bit confusing as of now. Will I need express js for it or I can directly upload it like the normal html site?</p>

答:
There isn't typically anything particularly special about deploying a vue application to a shared hosting environment.  Often the best first step is to "deploy" the website to your local development box running similar web server software as your shared hosting environment.

Once you can make the vue app run there outside of your coding environment, then you know exactly which files you need to deploy to your shared hosting environment to have it run at the hosting company.  You shouldn't typically need to deploy any additional files to the hosting company that you are not using when "hosting" the site on your own dev box outside of your coding environment.


问:
distinct and max query in pyspark dataframe
I have a dataset like:

```<code>list1     list2
a          e
a          e
b          w
a          e
a          r
b          c
</code>```

I want to find most frequent item in list2 grouped by list1.

```<code>list1     list2    max
  a         e       3
  b         w       1
</code>```

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

```<code>qry1=spark.sql("SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc")
qry1.registerTempTable("try1")

qry2=spark.sql("select clf1 as clf2, first(value_count) as max_value from try1 group by clf2 ")
qry2.registerTempTable("try2")

qry3=qry1.join(qry2, (try1["clf1"] == try2["clf2"]) & (try1["value_count"] == try2["max_value"]), 'inner')
</code>```

答:
l  am not sure about the output you are looking for.still,you can try this query :</p>

```<code> qry1=spark.sql("SELECT * FROM (SELECT col1 as clf1, col2, count(col2) AS value_count FROM table1 GROUP BY col2,col1 order by value_count desc) a where value_count !=1")
</code>```

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

qry1=spark.sql("SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc")
qry1.registerTempTable("try1")

qry2=spark.sql("select clf1 as clf2, first(value_count) as max_value from try1 group by clf2 ")
qry2.registerTempTable("try2")

qry3=qry1.join(qry2, (try1["clf1"] == try2["clf2"]) & (try1["value_count"] == try2["max_value"]), 'inner')

Body:
l  am not sure about the output you are looking for.still,you can try this query :

 qry1=spark.sql("SELECT * FROM (SELECT col1 as clf1, col2, count(col2) AS value_count FROM table1 GROUP BY col2,col1 order by value_count desc) a where value_count !=1")