问:
After-update trigger gets 'bad bind variable' error
When trying to make a trigger in Oracle which updates table PAND after changing AFGEVINKT from 0 to 1 in table BGT_PAND_MUTATIE:

```<code>CREATE OR REPLACE TRIGGER AU_BGT_PAND_MUTATIE
AFTER UPDATE OF AFGEVINKT ON BGT_PAND_MUTATIE
FOR EACH ROW

BEGIN

   UPDATE PAND
   SET VRIJNUMMER1 = NULL
   WHERE PAND.ID =: BGT_PAND_MUTATIE.ID;

END;
</code>```

I get the following message:

```<code>Error(5,20): PLS-00049: bad bind variable 'BGT_PAND_MUTATIE.ID'
</code>```

Table BGT_PAND_MUTATIE has columns ID and AFGEVINKT. Table PAND has columns ID and VRIJNUMMER1.

What do I have to do to make this work?

答:
You currently have:

```<code>WHERE PAND.ID =: BGT_PAND_MUTATIE.ID;
</code>```

The colon in the =: is making the following identifier be treated as a bind variable. You don't refer to the table directly though; you use the NEW psdeudorecord:

```<code>WHERE PAND.ID = :NEW.ID;
</code>```

Body:
When trying to make a trigger in Oracle which updates table PAND after changing AFGEVINKT from 0 to 1 in table BGT_PAND_MUTATIE:

CREATE OR REPLACE TRIGGER AU_BGT_PAND_MUTATIE
AFTER UPDATE OF AFGEVINKT ON BGT_PAND_MUTATIE
FOR EACH ROW

BEGIN

   UPDATE PAND
   SET VRIJNUMMER1 = NULL
   WHERE PAND.ID =: BGT_PAND_MUTATIE.ID;

END;

I get the following message:

Error(5,20): PLS-00049: bad bind variable 'BGT_PAND_MUTATIE.ID'

Table BGT_PAND_MUTATIE has columns ID and AFGEVINKT. Table PAND has columns ID and VRIJNUMMER1.

What do I have to do to make this work?

Body:
You currently have:

WHERE PAND.ID =: BGT_PAND_MUTATIE.ID;

The colon in the =: is making the following identifier be treated as a bind variable. You don't refer to the table directly though; you use the NEW psdeudorecord:

WHERE PAND.ID = :NEW.ID;


来源: stackexchange

问:
ssh key for Bitbucket in Jenkins slave on Windows
I have a Jenkins master on Linux and slave on Windows. Master jobs are able to clone the Git repository using ssh and we have config for this. But the same is not working from slave jobs. It is giving below error:

```<code>stderr: Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists."
</code>```

I had configured Git tool location in slave node.

答:
Problem is with slave node configuration.
Its explained here follow the link

https://issues.jenkins-ci.org/browse/JENKINS-12353

ContentLicense: CC BY-SA 4.0

Body:
I have a Jenkins master on Linux and slave on Windows. Master jobs are able to clone the Git repository using ssh and we have config for this. But the same is not working from slave jobs. It is giving below error:

stderr: Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists."

I had configured Git tool location in slave node.

ContentLicense: CC BY-SA 3.0


问:
"ToDictonary" throws exception when used on Mocked object
I have this abstract class

```<code>public abstract class DisposableList<T> : List<T>, IDisposable
{
    protected DisposableList();

    public virtual void Dispose();
}
</code>```

and this Interface

```<code>public interface IGroup : IDisposable
{
    string Name { get; }
}
</code>```

I need to test this method

```<code>public class MyClass
{
    public void MyMethod(IConnection connection)
    {
        var groups = connection.GetGroups();
        var grps = groups.ToDictionary(x => x?.Name); //Here gets System.NullReference exception
    }
}
</code>```

In testing, so far what I did is:

```<code>var group1 = new Mock<IGroup>();
group1.SetupGet(c => c.Name).Returns("abc");

var groups = new Mock<DisposableList<IGroup>>();
groups.Object.Add(group1.Object);

Mock<IConnection> connection.Setup(c => c.GetGroups()).Returns(() => groups.Object);

new MyClass().MyMethod(connection);
</code>```

but var grps = groups.ToDictionary(x => x?.Name); gets System.NullReferenceException: 'Object reference not set to an instance of an object.'

Name is not null and groups is not null. Something happens inside.

how can I fix this?

答:
You can't set null value as dictionary key like this; (It is possible to be null)

```<code>groups.ToDictionary(x => x?.Name);
</code>```

Eliminate the items which is null or has null Name value.

```<code>groups.Where(x => x != null && !string.IsNullOrEmpty(x.Name)).ToDictionary(x => x.Name);
</code>```

Body:
I have this abstract class

public abstract class DisposableList<T> : List<T>, IDisposable
{
    protected DisposableList();

    public virtual void Dispose();
}

and this Interface

public interface IGroup : IDisposable
{
    string Name { get; }
}

I need to test this method

public class MyClass
{
    public void MyMethod(IConnection connection)
    {
        var groups = connection.GetGroups();
        var grps = groups.ToDictionary(x => x?.Name); //Here gets System.NullReference exception
    }
}

In testing, so far what I did is:

var group1 = new Mock<IGroup>();
group1.SetupGet(c => c.Name).Returns("abc");

var groups = new Mock<DisposableList<IGroup>>();
groups.Object.Add(group1.Object);

Mock<IConnection> connection.Setup(c => c.GetGroups()).Returns(() => groups.Object);

new MyClass().MyMethod(connection);

but var grps = groups.ToDictionary(x => x?.Name); gets System.NullReferenceException: 'Object reference not set to an instance of an object.'

Name is not null and groups is not null. Something happens inside.

how can I fix this?

Body:
You can't set null value as dictionary key like this; (It is possible to be null)

groups.ToDictionary(x => x?.Name);

Eliminate the items which is null or has null Name value.

groups.Where(x => x != null && !string.IsNullOrEmpty(x.Name)).ToDictionary(x => x.Name);


问:
How can I find a range in an array using user input?
```<code>package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}
</code>```

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

```<code>Arrays.asList(a).indexOf(index1)
</code>```

but that will give me -1 every time
And I don't know how to make it wors in the other method

答:
```<code>public static void DoubleSegsum(double[] a, int from, int to){

            double sum=0;
            for(int i=from;i<to;i++){
                sum+=a[i];
            }
        System.out.println(sum);
    }
</code>```

Body:
package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

Arrays.asList(a).indexOf(index1)

but that will give me -1 every time
And I don't know how to make it wors in the other method


问:
join two tables in R using Names from both tables
Hi guys I know there are few questions related to joining tables in R, I tried most of them but they didn't work, in my case, I have two tables first one (A) has two columns (Id and company_name), 70,000 rows, and the second one (B) has company_name, registration number .....etc with 10,000,000 rows.

I want to join them to get the registration number for all the companies in A.

hint, I tried to merge, inner join using sqldf,fuzzyjoin and vlookup in excel but it didn't return all the record in A.

答:
R

```<code>merge(table_a, table_b, by = "company_name", all.x = TRUE)
</code>```

Excel

A: Id from table1 .

  B: company_name from table1 .

  C: company_name from table2 .

  D: registration_number from table2 .

Use this formula in any other column to get registration_number

```<code>Vlookup(B2, $C$2:$D$10000001, 2, FALSE)
</code>```

Body:
R

merge(table_a, table_b, by = "company_name", all.x = TRUE)

Excel

A: Id from table1 .

  B: company_name from table1 .

  C: company_name from table2 .

  D: registration_number from table2 .

Use this formula in any other column to get registration_number

Vlookup(B2, $C$2:$D$10000001, 2, FALSE)


问:
Form submission in angular 2
I have successfully implemented Http post request with my rest micro service .

When i make post request using the login form ,if the username password matches with database entry , it gives me back the username password in my console.

And if the username password does not exist, it returns me null.

But i want to redirect to my homepage only after successful login i.e if username and password is correct.

How to check if my console returns me null then i should not redirect ?

Below shown is my code

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```

app.component.html

```<code><div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
<router-outlet></router-outlet>
</div>
</code>```

app.routing.ts

```<code>import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);
</code>```

header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}
</code>```

header.component.html

```<code><div class="row">
<div class="col-xs-12"><ul class="nav nav-pills">
<li routerLinkActive="active"><a [routerLink]="['/homepage/home']">
<strong>Home</strong></a></li>
<li><a [routerLink]="['/homepage']"><strong>Logout</strong></a></li>
</ul></div>
</div>
</code>```

Here is my login component where i have implemented the post request

login.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

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

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));

    this.router.navigate(['homepage/home']);
  }
}
</code>```

As shown above in the login.component.ts file i need to check if my console returns me null then i should not redirect else i should redirect to /homepage/home

login.component.html

```<code><div class="container formWidth" style="text-align:center;">
  <h1> eSpace Login</h1><hr>
<br/>
     <h2>Login</h2>
    <form role="form">
      <div ng-control-group="credentials">
        <label for="username">Username</label>
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>
<br/>
        <label for="password">Password</label>
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>
      </div>
      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>
</div>
</code>```

post.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }
</code>```

Here is my home component in which i implemented get request

home.component.ts

```<code>import { Component } from '@angular/core';
import { GetService } from './get.service';

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

export class HomeComponent{
 title :string;
  data:any;

  constructor(private MyService: GetService){
  this.title="Angular Service";

  this.MyService.GetUsers()
 .subscribe(users => {this.data=users });
 }
}
</code>```

home.component.html

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```0

get.service.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```1

Here are the screen shots of my output

when i submit my form with the username and password which is not in my database,even then its redirecting me to homepage and returns null in my console

And when the credentials match my database ,even then it redirects to homepage and returns the credentials

can anybody please suggest me how to verify and redirect ?

答:
You just have to move your redirection in your subscription to your login service :</p>

```<code> checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
   .subscribe(users => {
     console.log(users);
     if (!users) {
       return // <= do nothing if the server's response is null
     } else {
       this.router.navigate(['homepage/home']); // <= redirect if it is ok
       }
    }

  }
}
</code>```

Title: Form submission in angular 2

Body:
I have successfully implemented Http post request with my rest micro service .

When i make post request using the login form ,if the username password matches with database entry , it gives me back the username password in my console.

And if the username password does not exist, it returns me null.

But i want to redirect to my homepage only after successful login i.e if username and password is correct.

How to check if my console returns me null then i should not redirect ?

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}

app.component.html

    {{title}}

<router-outlet></router-outlet>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}

header.component.html

Home

Logout

Here is my login component where i have implemented the post request

login.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

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

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));

    this.router.navigate(['homepage/home']);
  }
}

As shown above in the login.component.ts file i need to check if my console returns me null then i should not redirect else i should redirect to /homepage/home

login.component.html

 eSpace Login

Login

    <form role="form">

        Username
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>

        Password
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>

      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>

post.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }

Here is my home component in which i implemented get request

home.component.ts

import { Component } from '@angular/core';
import { GetService } from './get.service';

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

export class HomeComponent{
 title :string;
  data:any;

  constructor(private MyService: GetService){
  this.title="Angular Service";

  this.MyService.GetUsers()
 .subscribe(users => {this.data=users });
 }
}

home.component.html

<app-header></app-header>

  Welcome to eSpace Home

Angular GET service

Username	  Password

             {{ item.username }}	  {{ item.password }}

get.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GetService {
constructor(private http:Http) { }

GetUsers(){
  return this.http.get('http://localhost:8080/checkUsers')
    .map(result => result.json());
           }
 }

Here are the screen shots of my output

when i submit my form with the username and password which is not in my database,even then its redirecting me to homepage and returns null in my console

And when the credentials match my database ,even then it redirects to homepage and returns the credentials

can anybody please suggest me how to verify and redirect ?

Body:
You just have to move your redirection in your subscription to your login service :

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
   .subscribe(users => {
     console.log(users);
     if (!users) {
       return // <= do nothing if the server's response is null
     } else {
       this.router.navigate(['homepage/home']); // <= redirect if it is ok
       }
    }

  }
}


问:
find_element_by_partial_link_text ascii code issue
http://www.m2sys.com/.

When I click on CloudApper™ under Solutions I get an ascii code error.

I find the element using:

```<code>driver.find_element_by_partial_link_text('CloudApper™')
</code>```

How can I click the partial link?

答:
Just ignore the TM in superscript while searching for CloudApper™.

```<code>driver.find_element_by_partial_link_text('CloudApper')
</code>```

There are two instances by  link text CloudApper™ in the target page. You can use this for finding the link  cloudApper located below solutions. driver.find_element_by_xpath("//ul[@id='mobile-advanced']//a[contains(@href,'cloudapper')]")

Body:
http://www.m2sys.com/.

When I click on CloudApper™ under Solutions I get an ascii code error.

I find the element using:

driver.find_element_by_partial_link_text('CloudApper™')

How can I click the partial link?

Body:
Just ignore the TM in superscript while searching for CloudApper™.

driver.find_element_by_partial_link_text('CloudApper')

There are two instances by  link text CloudApper™ in the target page. You can use this for finding the link  cloudApper located below solutions. driver.find_element_by_xpath("//ul[@id='mobile-advanced']//a[contains(@href,'cloudapper')]")


问:
MvvmCross Android binding Enabled not work with Click
I have a TextView bound with Enabled, Clickable and Click. When the activity is loaded, Enabled & Clickable were bound to false value but the TextView cannot be disabled & still be clickable. After changed the bound value to true & then false, the TextView is disabled.

I found that the issue was related to binding the Click event. Once Click is bound, the mentioned issue occurs. Without binding the Click event, it works as expected.

In the following sample code, the first 2 TextViews are ok. The last one with binding Click does not work.

BTW, I have this issue with TextInputEditText instead. I found the situation applies to TextView as well so I use TextView for illustration.

```<code>         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview can be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice" />
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview with no click command, can be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice" />
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview with click command cannot be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice;
                                   Click DoSomethingCommand" />

    private IMvxAsyncCommand _doSomethingCommand;
    public IMvxAsyncCommand DoSomethingCommand
    {
        get
        {
            _doSomethingCommand = _doSomethingCommand ?? new MvxAsyncCommand(async () =>
            {
                await Task.Delay(10);
            });
            return _doSomethingCommand;
        }
    }
</code>```

Any idea how to fix?

Thanks

答:
As Stuart said, there are some interaction between ICommand.CanExecute and the Enabled property. Switching the binding to :

```<code>local:MvxBind="Click DoSomethingCommand;Enabled RouteMarker.ArrivalNotice;Clickable RouteMarker.ArrivalNotice;"
</code>```

Effect.

Body:
I have a TextView bound with Enabled, Clickable and Click. When the activity is loaded, Enabled & Clickable were bound to false value but the TextView cannot be disabled & still be clickable. After changed the bound value to true & then false, the TextView is disabled.

I found that the issue was related to binding the Click event. Once Click is bound, the mentioned issue occurs. Without binding the Click event, it works as expected.

In the following sample code, the first 2 TextViews are ok. The last one with binding Click does not work.

BTW, I have this issue with TextInputEditText instead. I found the situation applies to TextView as well so I use TextView for illustration.

         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview can be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice" />
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview with no click command, can be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice" />
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:text="test textview with click command cannot be disabled at load"
             style="@style/EntryTextStyle"
             local:MvxBind="       Enabled RouteMarker.ArrivalNotice;
                                   Clickable RouteMarker.ArrivalNotice;
                                   Click DoSomethingCommand" />

    private IMvxAsyncCommand _doSomethingCommand;
    public IMvxAsyncCommand DoSomethingCommand
    {
        get
        {
            _doSomethingCommand = _doSomethingCommand ?? new MvxAsyncCommand(async () =>
            {
                await Task.Delay(10);
            });
            return _doSomethingCommand;
        }
    }

Any idea how to fix?

Thanks

Body:
As Stuart said, there are some interaction between ICommand.CanExecute and the Enabled property. Switching the binding to :

local:MvxBind="Click DoSomethingCommand;Enabled RouteMarker.ArrivalNotice;Clickable RouteMarker.ArrivalNotice;"

Effect.


问:
Merging cells in JTable
Is it possible to merge some cells of a JTable object?

(source: codeguru.com)

If it's not possible through JTable what is the best approach. Thanks.

答:
You could implement a JTable using a TableModel merging two columns of the original TableModel.</p>

```<code>class Model2 extends AbstractTableModel
{
private TableModel delegate;
public Model2(TableModel delegate)
 {
 this.delegate= delegate;
 }

public int getRowCount() { return this.delegate.getRowCount();}
public int getColumnCount() { return this.delegate.getColumnCount()-1;}
public Object getValueAt(int row, int col)
 {
 if(col==0) return ""+delegate.getValueAt(row,col)+delegate.getValueAt(row,col+1);
 return delegate.getValueAt(col+1);
 }
(...)
}
</code>```

OwnerDisplayName: kvphxga

Title: Merging cells in JTable

LastEditorDisplayName: kvphxga

Body:
You could implement a JTable using a TableModel merging two columns of the original TableModel.

class Model2 extends AbstractTableModel
{
private TableModel delegate;
public Model2(TableModel delegate)
 {
 this.delegate= delegate;
 }

public int getRowCount() { return this.delegate.getRowCount();}
public int getColumnCount() { return this.delegate.getColumnCount()-1;}
public Object getValueAt(int row, int col)
 {
 if(col==0) return ""+delegate.getValueAt(row,col)+delegate.getValueAt(row,col+1);
 return delegate.getValueAt(col+1);
 }
(...)
}

ContentLicense: CC BY-SA 2.5


问:
Nodejs: Wait for a promise to get resolved
In this code, variables adminName and adminPassword should get values before the execution of if statements. But if statements are executing before the then handler function. thats why the validation not working.

```<code>function validateAdminLogin()
{

var adminName="";
var adminPassword="";

var isValid=true;

var UserDAO = require('./js/DAO/UserDAO');
var wait=require('wait.for-es6');
var admin=document.getElementById("adminform").elements.namedItem("username").value;
var adminPwd=document.getElementById("adminform").elements.namedItem("pwd").value;

    UserDAO.getAdminCredentials().then(function(rows){

    adminName= rows.username;
    adminPassword=rows.password;

    alert(admin+"----"+adminName);

    },function(error){
    alert(error);
    console.log(error);
    });

    //alert(admin+"-------"+adminName);

if(admin!==adminName)
{
alert("Invalid username");
isValid=false;
}

if(adminPwd!==adminPassword)
{
alert("Invalid password");
isValid=false;
}

return isValid;
}
</code>```

I'm also including the code in which I've written the promise.

```<code>getAdminCredentials: function()
{
    var deferred = q.defer();

    $query =  "SELECT * FROM `user` where type='administrator' ";

    connection.connect(function(err) {

        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }

     // console.log("Successfully connected.");
    });

    connection.query($query, function(err, rows, fields) {
        if(err){
            console.log("An error ocurred performing the query.");
            console.log(err);
            deferred.reject(err);
            return;
        }
        else
            {
             console.log("Query succesfully executed");
            userDTO.setUserId(rows[0].user_id);
           userDTO.setUsername(rows[0].username);
           userDTO.setPassword(rows[0].password);

           deferred.resolve(userDTO);

            }

    });

    return deferred.promise;

    connection.end();
}
</code>```

How do I deal with this asynchronous nature of nodejs? Please help.

答:
You could rewrite your validateAdminLogin function like this:

```<code>function validateAdminLogin() {
    var UserDAO = require('./js/DAO/UserDAO');
    var wait = require('wait.for-es6');
    var admin = document.getElementById("adminform").elements.namedItem("username").value;
    var adminPwd = document.getElementById("adminform").elements.namedItem("pwd").value;

    // return a promise which will be resolved with a bool indicating the "valid" status
    // the promise can reject when there was an error
    return UserDAO.getAdminCredentials().then(function(rows) {
        var adminName = rows.username;
        var adminPassword = rows.password;

       if (admin !== adminName) {
           alert("Invalid username");
           return false
       }

       if (adminPwd !== adminPassword) {
           alert("Invalid password");
           return false
       }

       return true
   }, function(error) {
       console.log(error);
   });
}
</code>```

You'll have to handle your function call somewhat different because it doesn't return the bool immediately. You're call site would look like this:

```<code>validateAdminLogin().then(function (isValid) {
    // handle the "isValid" bool
}, function (error) {
    // handle the error...
});
</code>```

It isn't possible to synchronize a asynchronous action in node.js.

Body:
In this code, variables adminName and adminPassword should get values before the execution of if statements. But if statements are executing before the then handler function. thats why the validation not working.

function validateAdminLogin()
{

var adminName="";
var adminPassword="";

var isValid=true;

var UserDAO = require('./js/DAO/UserDAO');
var wait=require('wait.for-es6');
var admin=document.getElementById("adminform").elements.namedItem("username").value;
var adminPwd=document.getElementById("adminform").elements.namedItem("pwd").value;

    UserDAO.getAdminCredentials().then(function(rows){

    adminName= rows.username;
    adminPassword=rows.password;

    alert(admin+"----"+adminName);

    },function(error){
    alert(error);
    console.log(error);
    });

    //alert(admin+"-------"+adminName);

if(admin!==adminName)
{
alert("Invalid username");
isValid=false;
}

if(adminPwd!==adminPassword)
{
alert("Invalid password");
isValid=false;
}

return isValid;
}

I'm also including the code in which I've written the promise.

getAdminCredentials: function()
{
    var deferred = q.defer();

    $query =  "SELECT * FROM `user` where type='administrator' ";

    connection.connect(function(err) {

        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }

     // console.log("Successfully connected.");
    });

    connection.query($query, function(err, rows, fields) {
        if(err){
            console.log("An error ocurred performing the query.");
            console.log(err);
            deferred.reject(err);
            return;
        }
        else
            {
             console.log("Query succesfully executed");
            userDTO.setUserId(rows[0].user_id);
           userDTO.setUsername(rows[0].username);
           userDTO.setPassword(rows[0].password);

           deferred.resolve(userDTO);

            }

    });

    return deferred.promise;

    connection.end();
}

How do I deal with this asynchronous nature of nodejs? Please help.

Body:
You could rewrite your validateAdminLogin function like this:

function validateAdminLogin() {
    var UserDAO = require('./js/DAO/UserDAO');
    var wait = require('wait.for-es6');
    var admin = document.getElementById("adminform").elements.namedItem("username").value;
    var adminPwd = document.getElementById("adminform").elements.namedItem("pwd").value;

    // return a promise which will be resolved with a bool indicating the "valid" status
    // the promise can reject when there was an error
    return UserDAO.getAdminCredentials().then(function(rows) {
        var adminName = rows.username;
        var adminPassword = rows.password;

       if (admin !== adminName) {
           alert("Invalid username");
           return false
       }

       if (adminPwd !== adminPassword) {
           alert("Invalid password");
           return false
       }

       return true
   }, function(error) {
       console.log(error);
   });
}

You'll have to handle your function call somewhat different because it doesn't return the bool immediately. You're call site would look like this:

validateAdminLogin().then(function (isValid) {
    // handle the "isValid" bool
}, function (error) {
    // handle the error...
});

It isn't possible to synchronize a asynchronous action in node.js.


问:
Dragtable Javascript library isn't working for every page. Only in Index.html where library is imported?

I'm trying to use dragtable Javascript library for my Project.

```<code><script type="text/javascript" src='js/dragtable.js'></script>
</code>```

```<code><div class="div_wrapper" >

    <table id="table1" class="unassignedMerchants draggable" border="1">
        <thead>
            <tr>
                <th>ID</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in tenUnassignedMerchants">
                <td>{{ item.id }}</td>
            </tr>
        </tbody>
    </table>
</code>```

In index.html page it's working correctly but when I'm trying to use it in another .html page which is part of the project it's not working.
What is the way to make this library visible for other pages?

答:
It`s depending of how add this library and how it connect with yours component.

For example how components know that it`s gradable. It could add directive as class or as attribute to yours elements...

Body:
I'm trying to use dragtable Javascript library for my Project.

                ID

                {{ item.id }}

In index.html page it's working correctly but when I'm trying to use it in another .html page which is part of the project it's not working.
What is the way to make this library visible for other pages?


问:
R: merge two lists of lists of dataframes
I have two lists of lists of dataframes like this:

```<code>L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))
</code>```

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

```<code>> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6
</code>```

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

```<code>L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))
</code>```

Any help is appreciated!

答:
Here is an approach using reshape2::melt.

```<code>library(reshape2);

# Collapse lists and turn into long dataframe
df.long <- rbind.data.frame(
    melt(L1, id.vars = "X1"),
    melt(L2, id.vars = "X1"));

# Split dataframe into nested list
lst <- lapply(split(df.long, df.long$L1), function(x) split(x, x$L2));
lst <- lapply(lst, function(x) lapply(x, function(y) data.frame(X1 = y$X1)));

str(lst);
#List of 2
# $ Q1:List of 3
#  ..$ A:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 1 2 3
#  ..$ B:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 4 5 6
#  ..$ C:'data.frame':  6 obs. of  1 variable:
#  .. ..$ X1: int [1:6] 1 2 3 4 5 6
# $ Q2:List of 3
#  ..$ A:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 4 5 6
#  ..$ B:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 1 2 3
#  ..$ C:'data.frame':  6 obs. of  1 variable:
#  .. ..$ X1: int [1:6] 1 2 3 4 5 6
</code>```

Data

```<code>L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))
</code>```

Body:
I have two lists of lists of dataframes like this:

L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))

Any help is appreciated!

Body:
Here is an approach using reshape2::melt.

library(reshape2);

# Collapse lists and turn into long dataframe
df.long <- rbind.data.frame(
    melt(L1, id.vars = "X1"),
    melt(L2, id.vars = "X1"));

# Split dataframe into nested list
lst <- lapply(split(df.long, df.long$L1), function(x) split(x, x$L2));
lst <- lapply(lst, function(x) lapply(x, function(y) data.frame(X1 = y$X1)));

str(lst);
#List of 2
# $ Q1:List of 3
#  ..$ A:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 1 2 3
#  ..$ B:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 4 5 6
#  ..$ C:'data.frame':  6 obs. of  1 variable:
#  .. ..$ X1: int [1:6] 1 2 3 4 5 6
# $ Q2:List of 3
#  ..$ A:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 4 5 6
#  ..$ B:'data.frame':  3 obs. of  1 variable:
#  .. ..$ X1: int [1:3] 1 2 3
#  ..$ C:'data.frame':  6 obs. of  1 variable:
#  .. ..$ X1: int [1:6] 1 2 3 4 5 6

Data

L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))


问:
How to Merge Chrome driver service with desired capabilities for headless using xvfb?
I want to merge ChromeDriverService with chromeOptions or with DesiredCapabilities for running browser in xvfb.

Below is part of code ChromeDriverService I previously used without selenium grid.

```<code>String NodeChromeIncognito = "http://localhost:5558/wd/hub"

         ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
         .usingDriverExecutable(new File("driver_linux/chromedriver"))
         .usingAnyFreePort()
         .withEnvironment(ImmutableMap.of("DISPLAY", ":1")).build();
     chromeDriverService.start();
    // commented because using RemoteWebDriver
    // driver = new ChromeDriver(chromeDriverService);
</code>```

and below is part code of RemoteWebDriver which I will merge with ChromeDriverService.

```<code>DesiredCapabilities cap = null;
String NodeChromeIncognito = "http://localhost:5558/wd/hub";
String NodeChrome = "http://localhost:5557/wd/hub";
String NodeFirefox = "http://localhost:5556/wd/hub";

    if (browserName.equals("chrome")) {
        cap = DesiredCapabilities.chrome();
        cap.setBrowserName("chrome");
        driver = new RemoteWebDriver(new URL(NodeChrome), cap);
    } else if (browserName.equals("firefox")) {
        System.setProperty("webdriver.gecko.driver", "driver_linux/geckodriver");
        cap = DesiredCapabilities.firefox();
        cap.setCapability("marionette", true);
        driver = new RemoteWebDriver(new URL(NodeFirefox), cap);
    }else if (browserName.equals("chromeIncognito")) {
        ChromeOptions option = new ChromeOptions();
        option.addArguments("--incognito");

        cap = DesiredCapabilities.chrome();
        cap.setCapability(ChromeOptions.CAPABILITY, option);
        cap.setPlatform(Platform.WIN10);
        cap.setBrowserName("chrome incognito");
        driver = new RemoteWebDriver(new URL(NodeChromeIncognito), cap);
    }
</code>```

I know I could use addArguments("--headless") for chrome, but it does not work well with the my webApp. And also I used DesiredCapabilities.merge and error.

How to merge code/configuration ChromeDriverService with ChromeOptions or DesiredCapabilites ?

答:
As you mentioned you want to merge ChromeDriverService with ChromeOptions or with DesiredCapabilities both can be achieved. But as of current Selenium Java Client releases the following Constructors are Deprecated :

```<code>ChromeDriver(Capabilities capabilities)
//and
ChromeDriver(ChromeDriverService service, Capabilities capabilities)
</code>```

Hence we have to use either of the following options :

Option A : Use only ChromeOptions :

```<code>private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
 .usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
 .usingAnyFreePort()
 .build();
chromeDriverService.start();

ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
driver = new RemoteWebDriver(service.getUrl(), options);
</code>```

Option B : Use DesiredCapabilities and then use merge() from MutableCapabilities to merge within ChromeOptions :

```<code>private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
 .usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
 .usingAnyFreePort()
 .build();
chromeDriverService.start();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("...", true);
ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
option.merge(capabilities);
driver = new RemoteWebDriver(service.getUrl(), options);
</code>```

Body:
I want to merge ChromeDriverService with chromeOptions or with DesiredCapabilities for running browser in xvfb.

Below is part of code ChromeDriverService I previously used without selenium grid.

String NodeChromeIncognito = "http://localhost:5558/wd/hub"

         ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
         .usingDriverExecutable(new File("driver_linux/chromedriver"))
         .usingAnyFreePort()
         .withEnvironment(ImmutableMap.of("DISPLAY", ":1")).build();
     chromeDriverService.start();
    // commented because using RemoteWebDriver
    // driver = new ChromeDriver(chromeDriverService);

and below is part code of RemoteWebDriver which I will merge with ChromeDriverService.

DesiredCapabilities cap = null;
String NodeChromeIncognito = "http://localhost:5558/wd/hub";
String NodeChrome = "http://localhost:5557/wd/hub";
String NodeFirefox = "http://localhost:5556/wd/hub";

    if (browserName.equals("chrome")) {
        cap = DesiredCapabilities.chrome();
        cap.setBrowserName("chrome");
        driver = new RemoteWebDriver(new URL(NodeChrome), cap);
    } else if (browserName.equals("firefox")) {
        System.setProperty("webdriver.gecko.driver", "driver_linux/geckodriver");
        cap = DesiredCapabilities.firefox();
        cap.setCapability("marionette", true);
        driver = new RemoteWebDriver(new URL(NodeFirefox), cap);
    }else if (browserName.equals("chromeIncognito")) {
        ChromeOptions option = new ChromeOptions();
        option.addArguments("--incognito");

        cap = DesiredCapabilities.chrome();
        cap.setCapability(ChromeOptions.CAPABILITY, option);
        cap.setPlatform(Platform.WIN10);
        cap.setBrowserName("chrome incognito");
        driver = new RemoteWebDriver(new URL(NodeChromeIncognito), cap);
    }

I know I could use addArguments("--headless") for chrome, but it does not work well with the my webApp. And also I used DesiredCapabilities.merge and error.

How to merge code/configuration ChromeDriverService with ChromeOptions or DesiredCapabilites ?

Body:
As you mentioned you want to merge ChromeDriverService with ChromeOptions or with DesiredCapabilities both can be achieved. But as of current Selenium Java Client releases the following Constructors are Deprecated :

ChromeDriver(Capabilities capabilities)
//and
ChromeDriver(ChromeDriverService service, Capabilities capabilities)

Hence we have to use either of the following options :

Option A : Use only ChromeOptions :

private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
 .usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
 .usingAnyFreePort()
 .build();
chromeDriverService.start();

ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
driver = new RemoteWebDriver(service.getUrl(), options);

Option B : Use DesiredCapabilities and then use merge() from MutableCapabilities to merge within ChromeOptions :

private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
 .usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
 .usingAnyFreePort()
 .build();
chromeDriverService.start();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("...", true);
ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
option.merge(capabilities);
driver = new RemoteWebDriver(service.getUrl(), options);


问:
AppCode doesn't prompt RxSwift classes and some other installed CocoaPods
I have installed newest version of RxSwift by CocoaPods.

While trying to use simple elements of RxSwift, like NotificationsCenter.default.rx it doesn't prompt methods to use. Interestingly sometimes it prompts for other pods and sometimes not for the rest so I have to open XCode for checking code correction.

How can I fix that?

答:
You can actually kind of have autocompletion in Appcode if you declare your type explicitly. The only issue is you will have to look up the Base for Reactive<Base> since Appcode considers all rx extensions to be NSObject by default. For example:

```<code>import RxSiwft
import RxCocoa

...

(UIButton().rx as Reactive<UIButton>) //Autocompletion will work
</code>```

Body:
You can actually kind of have autocompletion in Appcode if you declare your type explicitly. The only issue is you will have to look up the Base for Reactive<Base> since Appcode considers all rx extensions to be NSObject by default. For example:

import RxSiwft
import RxCocoa

...

(UIButton().rx as Reactive<UIButton>) //Autocompletion will work


问:
ionic3 - text auto play (horizontal and loop)
example: https://github.com/bingcool/ionic-banner-tips,
Please open the link and check, I want it like same top of the screen that yellow text can auto horizontal scroll and loop.

Edit:

```<code>  <ion-slides autoplay="1" loop="true" speed="3000">
    <ion-slide>This is the loop text</ion-slide>
  </ion-slides>
</code>```

This is my project, I want my ionic3 project same like that example the yellow one. And make the text in one line.

答:
Finally problem solved

html file

scss file

```<code>.a {
    position: absolute;
    width: 100%;
    height: 50px;
    background-color: pink;
    overflow: hidden;
}
.b {
    position: absolute;
    width: 1440px;
    height: 100%;
}
.b p {
    // width: 480px;
    // height: 100%;
    margin-left: 400px;
    float: left;
}
.play {
    animation: ma 10s 3s infinite linear;
}
@keyframes ma {
    0% {
        margin-left: 0px;
    }
    100% {
        margin-left: -1200px;
    }
}
.play:hover {
    animation-play-state: paused;
}
</code>```

Final project screenshot

Body:
example: https://github.com/bingcool/ionic-banner-tips,
Please open the link and check, I want it like same top of the screen that yellow text can auto horizontal scroll and loop.

Edit:

  <ion-slides autoplay="1" loop="true" speed="3000">
    <ion-slide>This is the loop text</ion-slide>
  </ion-slides>

This is my project, I want my ionic3 project same like that example the yellow one. And make the text in one line.

Body:
Finally problem solved

html file

scss file

.a {
    position: absolute;
    width: 100%;
    height: 50px;
    background-color: pink;
    overflow: hidden;
}
.b {
    position: absolute;
    width: 1440px;
    height: 100%;
}
.b p {
    // width: 480px;
    // height: 100%;
    margin-left: 400px;
    float: left;
}
.play {
    animation: ma 10s 3s infinite linear;
}
@keyframes ma {
    0% {
        margin-left: 0px;
    }
    100% {
        margin-left: -1200px;
    }
}
.play:hover {
    animation-play-state: paused;
}

Final project screenshot


问:
How to set variable from a SQL query?
I'm trying to set a variable from a SQL query:

```<code>declare @ModelID uniqueidentifer

Select @ModelID = select modelid from models
where areaid = 'South Coast'
</code>```

Obviously I'm not doing this right as it doesn't work. Can somebody suggest a solution?

Thanks!

答:
I prefer just setting it from the declare statement</p>

```<code>DECLARE @ModelID uniqueidentifer = (SELECT modelid
                                    FROM models
                                    WHERE areaid = 'South Coast')
</code>```

Title: How to set variable from a SQL query?

Body:
I'm trying to set a variable from a SQL query:

declare @ModelID uniqueidentifer

Select @ModelID = select modelid from models
where areaid = 'South Coast'

Obviously I'm not doing this right as it doesn't work. Can somebody suggest a solution?

Thanks!

Body:
I prefer just setting it from the declare statement

DECLARE @ModelID uniqueidentifer = (SELECT modelid
                                    FROM models
                                    WHERE areaid = 'South Coast')


问:
C++ equivalent of python: tf.Graph.get_tensor_by_name() in Tensorflow?
What is the C++ equivalent of python: tf.Graph.get_tensor_by_name(name) in Tensorflow? Thanks!

Here is the code I am trying to run, but I get an empty output:

```<code>Status status = NewSession(SessionOptions(), &session); // create new session
ReadBinaryProto(tensorflow::Env::Default(), model, &graph_def); // read Graph
session->Create(graph_def); // add Graph to Tensorflow session
std::vector<tensorflow::Tensor> output; // create Tensor to store output
std::vector<string> vNames; // vector of names for required graph nodes
vNames.push_back("some_name"); // I checked names and they are presented in loaded Graph

session->Run({}, vNames, {}, &output); // ??? As a result I have empty output
</code>```

答:
there is a way to get neural node from graph_def directly.
if u only want the shape\type of node: "some_name":

```<code>void readPB(GraphDef & graph_def)
{

    int i;
    for (i = 0; i < graph_def.node_size(); i++)
    {
        if (graph_def.node(i).name() == "inputx")
        {
            graph_def.node(i).PrintDebugString();
        }
    }
}
</code>```

results:

```<code>name: "inputx"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
      dim {
        size: -1
      }
      dim {
        size: 5120
      }
    }
  }
}
</code>```

try member functins of the node and get the informations.

Body:
What is the C++ equivalent of python: tf.Graph.get_tensor_by_name(name) in Tensorflow? Thanks!

Here is the code I am trying to run, but I get an empty output:

Status status = NewSession(SessionOptions(), &session); // create new session
ReadBinaryProto(tensorflow::Env::Default(), model, &graph_def); // read Graph
session->Create(graph_def); // add Graph to Tensorflow session
std::vector<tensorflow::Tensor> output; // create Tensor to store output
std::vector<string> vNames; // vector of names for required graph nodes
vNames.push_back("some_name"); // I checked names and they are presented in loaded Graph

session->Run({}, vNames, {}, &output); // ??? As a result I have empty output

Body:
there is a way to get neural node from graph_def directly.
if u only want the shape\type of node: "some_name":

void readPB(GraphDef & graph_def)
{

    int i;
    for (i = 0; i < graph_def.node_size(); i++)
    {
        if (graph_def.node(i).name() == "inputx")
        {
            graph_def.node(i).PrintDebugString();
        }
    }
}

results:

name: "inputx"
op: "Placeholder"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "shape"
  value {
    shape {
      dim {
        size: -1
      }
      dim {
        size: 5120
      }
    }
  }
}

try member functins of the node and get the informations.


问:
Android gradle sync issue
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

```<code>C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project
</code>```

build.gradle  (app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle  (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

i didnt update android studio or gradle. Android support repository is installed.

答:
For react-native projects: Add maven repo to your project. (Removes react-native-fbsdk error after adding maven repo links).

```<code>buildscript {
    repositories {
       jcenter()
       mavenCentral()
       maven {            // Add this block
          url "https://maven.google.com"
       }
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }

        // If something is not found from above maven repo.
        maven { url 'https://maven.google.com' }    // Add this block
    }
}
</code>```

More Info here

Title: Android gradle sync issue

Body:
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project

build.gradle  (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'

build.gradle  (project)

buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i didnt update android studio or gradle. Android support repository is installed.

Body:
For react-native projects: Add maven repo to your project. (Removes react-native-fbsdk error after adding maven repo links).

buildscript {
    repositories {
       jcenter()
       mavenCentral()
       maven {            // Add this block
          url "https://maven.google.com"
       }
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }

        // If something is not found from above maven repo.
        maven { url 'https://maven.google.com' }    // Add this block
    }
}

More Info here


问:
IPhone Bluetooth Connectivity to external hardware device over ATCommand or any other way
I am working on bluetooth connectivity As I have to connect one hardware device (Like OBDii) but I don't know, how it is possible.

Hardware device(Which is attached to the vehicle) will send ATCommand and we need to have interpreted that command and device will display the full report to user related to that vehicle.

I quite aware that it is possible using android device but not sure about iphone. How it works and which framework will use for the same?

What specification/profile is required for that bluetooth hardware device ?

is that possible to communication with that ELD hardware device ?

答: On iOS, you will have to use a Bluetooth 4.0 compliant OBD2 adapter, as iOS does not support the serial Bluetooth 3 profile. The proper framework to use is CoreBluetooth, which is a pretty straightforward implementation of the Bluetooth 4.0 spec.


问:
Android webdav Java Sardine
im trying Sardine to make a webdav client in android, im trying this code:

This works perfect on JAVA aplicacion, but crashes in android :(

```<code>    HttpClient client = new DefaultHttpClient();
    SardineImpl sardine = new SardineImpl((AbstractHttpClient) client,"testuser","test");
    List<DavResource> resources = sardine.getResources("http://demo.sabredav.org/");
    for (int i = 1; i < resources.size(); i++) {

          System.out.println(resources.get(i));
}
</code>```

Replacing System.out.println by Toast i get this

```<code>11-24 16:05:34.602: ERROR/AndroidRuntime(19362): java.lang.NoSuchMethodError: org.apache.http.impl.client.AbstractHttpClient.setRedirectStrategy
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.googlecode.sardine.impl.SardineImpl.init(SardineImpl.java:188)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.googlecode.sardine.impl.SardineImpl.<init>(SardineImpl.java:182)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at es.sardine.sardine.onCreate(sardine.java:39)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1065)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2745)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2797)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.access$2300(ActivityThread.java:135)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.os.Looper.loop(Looper.java:143)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.main(ActivityThread.java:4914)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at java.lang.reflect.Method.invoke(Method.java:521)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I had the same trouble trying to use Sardine and including Apache HttpClient which would conflict with the version embedded in Android. So I decided to replace it with OkHttp and I have much less trouble.
Here is the fork I created: https://github.com/thegrizzlylabs/sardine-android</p>

Title: Android webdav Java Sardine

Body:
im trying Sardine to make a webdav client in android, im trying this code:

This works perfect on JAVA aplicacion, but crashes in android :(

    HttpClient client = new DefaultHttpClient();
    SardineImpl sardine = new SardineImpl((AbstractHttpClient) client,"testuser","test");
    List<DavResource> resources = sardine.getResources("http://demo.sabredav.org/");
    for (int i = 1; i < resources.size(); i++) {

          System.out.println(resources.get(i));
}

Replacing System.out.println by Toast i get this

11-24 16:05:34.602: ERROR/AndroidRuntime(19362): java.lang.NoSuchMethodError: org.apache.http.impl.client.AbstractHttpClient.setRedirectStrategy
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.googlecode.sardine.impl.SardineImpl.init(SardineImpl.java:188)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.googlecode.sardine.impl.SardineImpl.<init>(SardineImpl.java:182)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at es.sardine.sardine.onCreate(sardine.java:39)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1065)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2745)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2797)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.access$2300(ActivityThread.java:135)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2132)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.os.Looper.loop(Looper.java:143)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at android.app.ActivityThread.main(ActivityThread.java:4914)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at java.lang.reflect.Method.invoke(Method.java:521)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-24 16:05:34.602: ERROR/AndroidRuntime(19362):     at dalvik.system.NativeStart.main(Native Method)


问:
Textfield in the keyboard
How do you make a keyboard have a textfield inside like the messages app ?</p>

答:
never tried but you can try this -

You can programmatically

set a tool bar.

set a textfield.

set the  tool bar as the inputAccessoryView of the textfield.

make the textfield the first responder.

Title: Textfield in the keyboard


问:
Error:null value in entry: streamOutputFolder=null OR Error:null value in entry: streamOutputFolder=null
I am unable to run my app in emulator because of this Error:

Error:null value in entry: streamOutputFolder=null

or

gradle - Error:null value in entry: incrementalFolder=null

答:
When you are unable to run your app on your emulator or phone

go to the .gradle folder delete it then rebuild your projects
then click on run button

if that doesnt work
delete .gradle folder
open the build.gradle file
which content something like this

// Top-level build file where you can add configuration options common to all sub-projects/modules.

```<code>buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

//change the classpath to

classpath 'com.android.tools.build:gradle:3.0.0'

but if your classpath initially is 2.3.1 change it to 2.3.0

Body:
When you are unable to run your app on your emulator or phone

go to the .gradle folder delete it then rebuild your projects
then click on run button

if that doesnt work
delete .gradle folder
open the build.gradle file
which content something like this

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

//change the classpath to

classpath 'com.android.tools.build:gradle:3.0.0'

but if your classpath initially is 2.3.1 change it to 2.3.0


问:
output showing nil result in console when passing
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

```<code>   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}
</code>```

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

```<code>import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}
</code>```

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

答:
Try this:</p>

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails", let destination = segue.destination as? movieDetailViewController {
        if let cell = sender as? UITableViewCell, let indexPath = tables.indexPath(for: cell) {
            destination.film = movies[indexPath.row] as? Movie
        }
    }
}
</code>```

Body:
I am new iOS development and still learning basics, my query is when i passed the data to other view controller from my main tableView controller so it is passing smoothly but the output result is showing nil in the console as shown below
here as you can see output in console is nil.This is my second view controller named as movieDetailViewController

below is my main tableView controller from where i am calling my second view controller.

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? movieDetailViewController
    {
        destination.film = movies[(tables.indexPathForSelectedRow?.row)!] as? Movie
    }
  }
}

Here the structure Movie is a normal swift file containing attributes that i want to print shown as below:

import Foundation

struct Movie {

     var title: String
     var overview: String
     var poster_path: String

}

Now as i describe that output when passed to another view controller is showing nil. I have been stuck in this problem from 1 week and also searched a lot but no solution helped me in this .

Body:
Try this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails", let destination = segue.destination as? movieDetailViewController {
        if let cell = sender as? UITableViewCell, let indexPath = tables.indexPath(for: cell) {
            destination.film = movies[indexPath.row] as? Movie
        }
    }
}


问:
How do you keep html semantically correct and and handle big css of complex designs like Big portals or News sites?
In personal and small business websites it's not so difficult but when we comes to New sites,Portals and E-commerce sites, where so many content comes on each pages, it's little hard.

How do you keep **HTML semantically correct and and handle big CSS of complex designs like Big portals or News sites?**

How to keep the HTML code semantically correct and Semantic naming convention for css classes and ID?

Is to use CSS grid Framework the best way to handle CSS in this scenario?

答: The best thing to do here is to create  and then float them right or left . Specify their width . Hence when you try to open them in different browsers they will be aligned properly or if you try to access them in very low or high resolution still they are perfectly aligned . Basically you need to create a nested structure so that all your corresponding elements are aligned respectively . </p>


问:
React - What is the best way to change an elements text each time the user clicks anywhere on screen?
I've started learning React, and after having read through the documentation, have a question..

I want to do the following:

I want to render text as part of a component. Then when a user clicks anywhere on the screen, the text changes, then changes again on a second click, and then again on a third, and finally, a fourth click.

I'd like to know what best practice would be when doing this in react? I was thinking about using the 'onClick' method, but that would only allow for two states?

Some assistance would be very much appreciated to help me on my react journey.

const welcome =
Welcome to my app 1/4
;

ReactDOM.render(
  welcome,
  document.getElementById('theapp')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/styles.css">
  <title>Learn ReactJS</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
  <script src="https://s3.amazonaws.com/codecademy-content/courses/React/react-course-bundle.min.js"></script>
  <script src="/app.compiled.js"></script>

  <div id="theapp"></div>

</body>

</html></code>```

答:
You can use mousedown event to observe clicks anywhere on the screen like

```<code>class Welcome extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        count: 0,
        message: ["message1", "message2", "message3", "message4"]
      }
    }

    componentDidMount() {
        window.addEventListener('mousedown', this.pageClick.bind(this), false);
    }

    pageClick(e) {
        this.setState((prevState) => {
            if(prevState.count != this.state.message.length - 1)
                return { count: prevState.count + 1};
        });
    }

    render() {
        const { message, count } = this.state;
        return (
            <h1>Welcome to my app {message[count]}</h1>
        )
    }
}

ReactDOM.render(
  <Welcome/>,
  document.getElementById("app")
);
</code>```

You can use mouseup and click events also.

Body:
I've started learning React, and after having read through the documentation, have a question..

I want to do the following:

I want to render text as part of a component. Then when a user clicks anywhere on the screen, the text changes, then changes again on a second click, and then again on a third, and finally, a fourth click.

I'd like to know what best practice would be when doing this in react? I was thinking about using the 'onClick' method, but that would only allow for two states?

Some assistance would be very much appreciated to help me on my react journey.

const welcome =
Welcome to my app 1/4
;

ReactDOM.render(
  welcome,
  document.getElementById('theapp')
);

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="/styles.css">
  <title>Learn ReactJS</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Body:
You can use mousedown event to observe clicks anywhere on the screen like

class Welcome extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        count: 0,
        message: ["message1", "message2", "message3", "message4"]
      }
    }

    componentDidMount() {
        window.addEventListener('mousedown', this.pageClick.bind(this), false);
    }

    pageClick(e) {
        this.setState((prevState) => {
            if(prevState.count != this.state.message.length - 1)
                return { count: prevState.count + 1};
        });
    }

    render() {
        const { message, count } = this.state;
        return (
            <h1>Welcome to my app {message[count]}</h1>
        )
    }
}

ReactDOM.render(
  <Welcome/>,
  document.getElementById("app")
);

You can use mouseup and click events also.


问:
iOS: How to implement search controller using objective c & How to call API at runtime i.e when I start typing in search controller?
I want to implement search controller like gmail application,

OR I want to implement like this example

Image 1 It shows normal inbox with search controller button

Image 2 After clicking on search button It will expand show like image 2. Here we can enter the words...etc

Image 3 Here whatever we enter, depending upon text it shows in list, and when we click on it, it will navigate to detail view.

same thing I want to implement.

Only thing is that, when I will start typing in search controller, one API will call i.e search, then depending upon text entered in search, it will take as parameter and it will show data in list (table view). this data will come from API response.

And when I click on any result, it has to move detail view.

Anybody, can help me.

I am totally new in iOS. Just now I started learning of iOS. Plz help me for this.

Here is .h file

```<code>#import <UIKit/UIKit.h>

@interface PDSearchExampleTableViewController : UITableViewController
{
    BOOL searching;
}

@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) NSMutableArray *sampleDataArray;
@property (strong, nonatomic) NSMutableArray *filteredSampleDataArray;

- (IBAction)searchButtonClicked:(id)sender;

@end
</code>```

Here is .m file

```<code>#import "PDSearchExampleTableViewController.h"

@interface PDSearchExampleTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>

@end

@implementation PDSearchExampleTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _searchBar.delegate = self;
    _sampleDataArray = [[NSMutableArray alloc] init];
    _filteredSampleDataArray = [[NSMutableArray alloc] init];
    [_sampleDataArray addObject:@"one"];
    [_sampleDataArray addObject:@"two"];
    [_sampleDataArray addObject:@"three"];
    [_sampleDataArray addObject:@"four"];
    [_sampleDataArray addObject:@"five"];
    [_sampleDataArray addObject:@"six"];
    [_sampleDataArray addObject:@"seven"];

     [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (searching) {
        return [_filteredSampleDataArray count];
    } else {
        return [_sampleDataArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sampleSearchCell" forIndexPath:indexPath];

    if (searching) {
        cell.textLabel.text = [_filteredSampleDataArray objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [_sampleDataArray objectAtIndex:indexPath.row];
    }

    return cell;
}

- (IBAction)searchButtonClicked:(id)sender {
    self.navigationItem.rightBarButtonItem = nil;
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"Search Sample Data";
    [_searchBar sizeToFit];
    self.navigationItem.titleView = _searchBar;
    [_searchBar becomeFirstResponder];
    [_searchBar.window makeKeyAndVisible];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [_searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searching = NO;
    [self.tableView reloadData];
    self.navigationItem.titleView = nil;
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonClicked:)];
    [_searchBar setShowsCancelButton:NO];
    [_searchBar resignFirstResponder];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [_filteredSampleDataArray removeAllObjects];

    if ([searchText length] != 0) {
        searching = YES;
        [self searchData];
    } else {
        searching = NO;
    }

    [self.tableView reloadData];
}

- (void)searchData {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", _searchBar.text];
    NSArray *tempArray = [_sampleDataArray filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", tempArray);
    _filteredSampleDataArray = [NSMutableArray arrayWithArray:tempArray];
}
</code>```

答:
You can follow my blog link . Have implemented in both objective C and Swift.

Swift

Objective C

Body:
I want to implement search controller like gmail application,

OR I want to implement like this example

Image 1 It shows normal inbox with search controller button

Image 2 After clicking on search button It will expand show like image 2. Here we can enter the words...etc

Image 3 Here whatever we enter, depending upon text it shows in list, and when we click on it, it will navigate to detail view.

same thing I want to implement.

Only thing is that, when I will start typing in search controller, one API will call i.e search, then depending upon text entered in search, it will take as parameter and it will show data in list (table view). this data will come from API response.

And when I click on any result, it has to move detail view.

Anybody, can help me.

I am totally new in iOS. Just now I started learning of iOS. Plz help me for this.

Here is .h file

#import <UIKit/UIKit.h>

@interface PDSearchExampleTableViewController : UITableViewController
{
    BOOL searching;
}

@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) NSMutableArray *sampleDataArray;
@property (strong, nonatomic) NSMutableArray *filteredSampleDataArray;

- (IBAction)searchButtonClicked:(id)sender;

@end

Here is .m file

#import "PDSearchExampleTableViewController.h"

@interface PDSearchExampleTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>

@end

@implementation PDSearchExampleTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _searchBar.delegate = self;
    _sampleDataArray = [[NSMutableArray alloc] init];
    _filteredSampleDataArray = [[NSMutableArray alloc] init];
    [_sampleDataArray addObject:@"one"];
    [_sampleDataArray addObject:@"two"];
    [_sampleDataArray addObject:@"three"];
    [_sampleDataArray addObject:@"four"];
    [_sampleDataArray addObject:@"five"];
    [_sampleDataArray addObject:@"six"];
    [_sampleDataArray addObject:@"seven"];

     [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (searching) {
        return [_filteredSampleDataArray count];
    } else {
        return [_sampleDataArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sampleSearchCell" forIndexPath:indexPath];

    if (searching) {
        cell.textLabel.text = [_filteredSampleDataArray objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [_sampleDataArray objectAtIndex:indexPath.row];
    }

    return cell;
}

- (IBAction)searchButtonClicked:(id)sender {
    self.navigationItem.rightBarButtonItem = nil;
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"Search Sample Data";
    [_searchBar sizeToFit];
    self.navigationItem.titleView = _searchBar;
    [_searchBar becomeFirstResponder];
    [_searchBar.window makeKeyAndVisible];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [_searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searching = NO;
    [self.tableView reloadData];
    self.navigationItem.titleView = nil;
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonClicked:)];
    [_searchBar setShowsCancelButton:NO];
    [_searchBar resignFirstResponder];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [_filteredSampleDataArray removeAllObjects];

    if ([searchText length] != 0) {
        searching = YES;
        [self searchData];
    } else {
        searching = NO;
    }

    [self.tableView reloadData];
}

- (void)searchData {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", _searchBar.text];
    NSArray *tempArray = [_sampleDataArray filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", tempArray);
    _filteredSampleDataArray = [NSMutableArray arrayWithArray:tempArray];
}


问:
How to delete every row in a range that contains data?
In a big data set I am trying to find each cell in column J that contains any data so "is not blank", then delete that row that  contains data. My code however won't work for it:

```<code>Dim rng3 As Range

Do
    Set rng3 = Columns("J:J")
    If Not rng3 Is Nothing Then
        rng.EntireRow.Delete
    Else
        Exit Do
    End If
Loop
</code>```

I was hoping somebody can help me with this.

答:
Select a range you need

Press F5

Press Special... button

Select Constants or Formulas (with other selections, if needed)

Press OK

Now go to: Home -> Cells -> Delete (arrow) -> Delete Sheet Rows

UPDATE

Macros:

```<code>Sub DeleteRowsWithData()

    Dim rng As Range

    ' Change to the range you need
    Set rng = Range("A1").CurrentRegion

    ' Change field to the one you need
    rng.AutoFilter Field:=1, Criteria1:="<>", Operator:=xlFilterValues

    With rng
        With .Offset(1).Resize(.Rows.Count - 1) 'Exclude header
            Application.DisplayAlerts = False
            .Rows.Delete
            Application.DisplayAlerts = True
        End With
    End With

End Sub
</code>```

Body:
In a big data set I am trying to find each cell in column J that contains any data so "is not blank", then delete that row that  contains data. My code however won't work for it:

Dim rng3 As Range

Do
    Set rng3 = Columns("J:J")
    If Not rng3 Is Nothing Then
        rng.EntireRow.Delete
    Else
        Exit Do
    End If
Loop

I was hoping somebody can help me with this.

Body:
Select a range you need

Press F5

Press Special... button

Select Constants or Formulas (with other selections, if needed)

Press OK

Now go to: Home -> Cells -> Delete (arrow) -> Delete Sheet Rows

UPDATE

Macros:

Sub DeleteRowsWithData()

    Dim rng As Range

    ' Change to the range you need
    Set rng = Range("A1").CurrentRegion

    ' Change field to the one you need
    rng.AutoFilter Field:=1, Criteria1:="<>", Operator:=xlFilterValues

    With rng
        With .Offset(1).Resize(.Rows.Count - 1) 'Exclude header
            Application.DisplayAlerts = False
            .Rows.Delete
            Application.DisplayAlerts = True
        End With
    End With

End Sub


问:
What is the best way to create a moving window in 2D array ond order pixels
I'm very new to Python, and need do to a bit of tricky 2D array manipulation with it. I'm not sure of the best way to go about it.

Basically, I start with an array of values between 0 and 1.

I need to have a moving 2x2 window to apply to the 2D array, (edit: where the array is a 2D image; ie say 200x200 pixels or so) and within each 2x2 window, assign values 1-4, inversely, according to the array value weights (ie, the minimum cell in the 2x2 becomes 4, then the next minimum becomes 3, etc.)

I can see how to extract my 2x2 windows by a nested loop; is that the best way?

More tricky is how to go about the ordering assignment.

I thought to use numpy.where (subarray.min) iteratively on my window subarrays, but I can't see how to GET at the returned location where returns! I'm not sure that there isn't a better way to go about this.

Advice? Pointers to how to do complicated, messy, array manipulations with NumPy?

答:
Perhaps this will help [refer to here]

Invocation:

```<code>x = np.arange(36).reshape((6, 6))
print(x)
b = sliding_window(x, (2, 3), None, False)
print(b)
</code>```

Body:
Perhaps this will help [refer to here]

Invocation:

x = np.arange(36).reshape((6, 6))
print(x)
b = sliding_window(x, (2, 3), None, False)
print(b)


问:
Passing two command parameters using a WPF binding
I have a command which I am executing from my XAML file using the following standard syntax:

```<code><Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand}"/>
</code>```

This worked fine until I realized that I needed TWO pieces of information from the view in order to make this operation complete the way users expect (the width and height of the canvas specfically).

It seems like it's possible to pass an array as an argument to my command, but I don't see there being a way to specify the binding to my two canvas properties in the CommandParameter:

```<code><Button Content="Zoom"
        Command="{Binding MyViewModel.ZoomCommand"
        CommandParameter="{Binding ElementName=MyCanvas, Path=Width}"/>
</code>```

How do I pass both Width and Height to my command?  It doesn't seem like this is possible using commands from XAML and I need to wire up a click handler in my codebehind to get this information to pass to my zoom method.

答:
Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.</p>

```<code>public class YourConverter : IMultiValueConverter
{
    public object Convert(object[] values, ...)
    {
        Tuple<string, string> tuple = new Tuple<string, string>(
            (string)values[0], (string)values[1]);
        return (object)tuple;
    }
}

// ...

public void OnExecute(object parameter)
{
    var param = (Tuple<string, string>) parameter;
}
</code>```

Body:
I have a command which I am executing from my XAML file using the following standard syntax:

<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand}"/>

This worked fine until I realized that I needed TWO pieces of information from the view in order to make this operation complete the way users expect (the width and height of the canvas specfically).

It seems like it's possible to pass an array as an argument to my command, but I don't see there being a way to specify the binding to my two canvas properties in the CommandParameter:

<Button Content="Zoom"
        Command="{Binding MyViewModel.ZoomCommand"
        CommandParameter="{Binding ElementName=MyCanvas, Path=Width}"/>

How do I pass both Width and Height to my command?  It doesn't seem like this is possible using commands from XAML and I need to wire up a click handler in my codebehind to get this information to pass to my zoom method.

Body:
Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.

public class YourConverter : IMultiValueConverter
{
    public object Convert(object[] values, ...)
    {
        Tuple<string, string> tuple = new Tuple<string, string>(
            (string)values[0], (string)values[1]);
        return (object)tuple;
    }
}

// ...

public void OnExecute(object parameter)
{
    var param = (Tuple<string, string>) parameter;
}


答:
This simple code will do the trick:</p>

```<code>For i = Cells(Rows.Count, 10).End(xlUp).Row To 1 Step -1
    If Cells(i, 10).Value <> "" Then
        Cells(i, 10).EntireRow.Delete
    End If
Next i
</code>```

Title: How to delete every row in a range that contains data?

Body:
This simple code will do the trick:

For i = Cells(Rows.Count, 10).End(xlUp).Row To 1 Step -1
    If Cells(i, 10).Value <> "" Then
        Cells(i, 10).EntireRow.Delete
    End If
Next i