问:
create css sub menu from sub
hello
what i am trying to is to create a sub menu from a sub menu. for example if a user hovers over Actions this then drops to show say billing - mail etc. i would like to create another sub if a user hovers over billing. i have attached the code i am using which is stu nicholls pro dropdown. thanks

menu css

```<code>.nav {
height:35px;
background: url(images/pro_line_0.gif) repeat-x;
margin-top:100px;
position:relative;
font-family:arial, verdana, sans-serif;
font-size:11px;
width:100%;
z-index:500;

}

.nav .table {
display:table;

}

.nav .select,
.nav .current {
margin:0;
padding:0;
list-style:none;
display:table-cell;
white-space:nowrap;
}

.nav li {
margin:0;
padding:0;
height:auto;
float:left;
}

.nav .select a {
display:block;
height:35px;
float:left;

padding:0 5px 0 30px;
text-decoration:none;
line-height:35px;
white-space:nowrap;
color:#fff;
}

.nav .current a {
display:block;
height:35px;
float:left;
background: url(images/pro_line_2.gif);
padding:0 0 0 10px;
text-decoration:none;
line-height:35px;
white-space:nowrap;
color:#fff;
}

.nav .current a b {
display:block;
padding:0 30px 0 15px;
background:url(images/pro_line_2.gif) right top;
}

.nav .select a:hover,
.nav .select li:hover a {

padding:0 0 0 15px;
cursor:pointer;
color:#088;
}

.nav .select a:hover b,
.nav .select li:hover a b {
display:block;
float:left;
padding:0 5px 0 15px;

cursor:pointer;
}

.nav .select_sub {
display:none;
}

/* IE6 only */
.nav table {
border-collapse:collapse;
margin:-1px;
font-size:1em;
width:0;
height:0;
}

.nav .sub {
display:table;
padding:0;
list-style:none;
}

.nav .sub_active .current_sub a,
.nav .sub_active a:hover {
background:transparent;
color:#f00;
}

.nav .select :hover .select_sub,
.nav .current .show {
display:block;
position:absolute;
width:100%;
top:35px;
background:url(images/back_0.gif);*/
padding:0;
z-index:100;
left:0px;
text-align:left;
}

.nav .current .show {
z-index:10;
}

.nav .select :hover .sub li a,
.nav .current .show .sub li a {
display:block;
float:left;
background:transparent;
padding:0 5px 0 30px;
margin:0;
white-space:nowrap;
border:0;
color:#444;
}

.nav .current .sub li.sub_show a {
color:#088;
cursor:default;
/*background:url(images/back_1.gif);*/

}

.nav .select :hover .sub li a:hover,
.nav .current .sub li a:hover {
visibility:visible;
font-weight:bold;
/*background:url(images/back_1.gif);*/
}
</code>```

sample html

```<code><ul class="select"><li><a href="#nogo"><b>Control Panel</b>
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
    <div class="select_sub show">
        <ul class="sub">
            <li><a href="/sample/admin/cp/mail/index.php">Tickets</a></li>
            <li><a href="#nogo">Messages</a></li>
            <li><a href="/sample/admin/cp/actions/index.php">Actions</a></li>
            <li><a href="/sample/admin/userlog.php">History</a></li>
            <li><a href="#nogo">Settings</a></li>
            <li><a href="#nogo">Destruction</a></li>
            <li><a href="/sample/admin/cp/contacts/index.php">Contacts</a></li>
            <li><a href="/sample/admin/cp/users/index.php">Users</a></li>
            <li><a href="/sample/admin/cp/companies/index.php">Companies</a></li>
        </ul>
    </div>
</code>```

答:
Try using nested
s in your HTML. That is, build your menu like so:

```<code><ul class="menu">
  <li>
    <a>My Link</a>
    <ul class="submenu">
      <li><a>My Nested Link</a></li>
  </li>
</ul>
</code>```

Then use a simple Javascript solution like Superfish (or one of your chosing)
http://users.tpg.com.au/j_birch/plugins/superfish/

Title: create css sub menu from sub

Body:
hello
what i am trying to is to create a sub menu from a sub menu. for example if a user hovers over Actions this then drops to show say billing - mail etc. i would like to create another sub if a user hovers over billing. i have attached the code i am using which is stu nicholls pro dropdown. thanks

menu css

.nav {
height:35px;
background: url(images/pro_line_0.gif) repeat-x;
margin-top:100px;
position:relative;
font-family:arial, verdana, sans-serif;
font-size:11px;
width:100%;
z-index:500;

}

.nav .table {
display:table;

}

.nav .select,
.nav .current {
margin:0;
padding:0;
list-style:none;
display:table-cell;
white-space:nowrap;
}

.nav li {
margin:0;
padding:0;
height:auto;
float:left;
}

.nav .select a {
display:block;
height:35px;
float:left;

padding:0 5px 0 30px;
text-decoration:none;
line-height:35px;
white-space:nowrap;
color:#fff;
}

.nav .current a {
display:block;
height:35px;
float:left;
background: url(images/pro_line_2.gif);
padding:0 0 0 10px;
text-decoration:none;
line-height:35px;
white-space:nowrap;
color:#fff;
}

.nav .current a b {
display:block;
padding:0 30px 0 15px;
background:url(images/pro_line_2.gif) right top;
}

.nav .select a:hover,
.nav .select li:hover a {

padding:0 0 0 15px;
cursor:pointer;
color:#088;
}

.nav .select a:hover b,
.nav .select li:hover a b {
display:block;
float:left;
padding:0 5px 0 15px;

cursor:pointer;
}

.nav .select_sub {
display:none;
}

/* IE6 only */
.nav table {
border-collapse:collapse;
margin:-1px;
font-size:1em;
width:0;
height:0;
}

.nav .sub {
display:table;
padding:0;
list-style:none;
}

.nav .sub_active .current_sub a,
.nav .sub_active a:hover {
background:transparent;
color:#f00;
}

.nav .select :hover .select_sub,
.nav .current .show {
display:block;
position:absolute;
width:100%;
top:35px;
background:url(images/back_0.gif);*/
padding:0;
z-index:100;
left:0px;
text-align:left;
}

.nav .current .show {
z-index:10;
}

.nav .select :hover .sub li a,
.nav .current .show .sub li a {
display:block;
float:left;
background:transparent;
padding:0 5px 0 30px;
margin:0;
white-space:nowrap;
border:0;
color:#444;
}

.nav .current .sub li.sub_show a {
color:#088;
cursor:default;
/*background:url(images/back_1.gif);*/

}

.nav .select :hover .sub li a:hover,
.nav .current .sub li a:hover {
visibility:visible;
font-weight:bold;
/*background:url(images/back_1.gif);*/
}

sample html

Control Panel

Tickets

Messages

Actions

History

Settings

Destruction

Contacts

Users

Companies

Body:
Try using nested <ul>s in your HTML. That is, build your menu like so:

<ul class="menu">
  <li>
    <a>My Link</a>
    <ul class="submenu">
      <li><a>My Nested Link</a></li>
  </li>
</ul>

Then use a simple Javascript solution like Superfish (or one of your chosing)
http://users.tpg.com.au/j_birch/plugins/superfish/


来源: stackexchange

问:
Prolog - Deleting Nth Column From A Matrix
I'm trying to create a query elimcol(_, [H|T], X) that deletes the nth column in a matrix array.

I believe that I'm complicating things as a beginner, but in Prolog logic, it would be better to call a matrix a "list of lists". So with that being said, since columns are essentially the "ith" element in every list of list, how would one go about deleting the ith element from all the lists, in a list of of lists. (I'm sorry for this confusing statement)

So far, this is what I was able to create:

```<code>elimcol(1, [G|H], H) :- !.
elimcol(N, [G|H], [G|L]) :-
    N > 1,
    Nn is N - 1,
    !,
    elimcol(Nn,H,L).

</code>```

This is able to delete for one list. However when I tried to expand deleting more lists, it doesn't seem to delete the "ith element" anymore.

```<code>?- elimcol(3,[[1,2,3], [1,1,1], [4,5,6]], X).
X = [[1, 2, 3], [1, 1, 1]].
</code>```

Appreciate any help on this. Many thanks!

EDIT: Did some minor changes, however same result i'm still only able to delete ith elements for (just one list)

```<code>elimcol(_, [], []).
elimcol(1, [_|T], T) :- !.
elimcol(I, [H|T], [H|R]) :-
   I1 is I-1,
   !,
   elimcol(I1, T, R).
</code>```

答:
maplist/N it's an idiomatic way to prove a relation among multiple lists elements,
and nth1/4 can be used to discard the column from a row. Then

del_mat_col(M,N,M1) :-
    maplist(del_col(N),M,M1).
del_col(N,R,R1) :- nth1(N,R,_,R1).
```

<p>yields</p>

<pre class="lang-erlang prettyprint-override"><code>?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,1,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[b, c], [e, f], [h, j]].

?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,2,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[a, c], [d, f], [g, j]].
</code>```

Using library(yall), the code becomes:

del_mat_col(M,N,M1) :-
    maplist({N}/[R,R1]>>nth1(N,R,_,R1),M,M1).
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a query elimcol(_, [H|T], X) that deletes the nth column in a matrix array.

I believe that I'm complicating things as a beginner, but in Prolog logic, it would be better to call a matrix a "list of lists". So with that being said, since columns are essentially the "ith" element in every list of list, how would one go about deleting the ith element from all the lists, in a list of of lists. (I'm sorry for this confusing statement)

So far, this is what I was able to create:

elimcol(1, [G|H], H) :- !.
elimcol(N, [G|H], [G|L]) :-
    N > 1,
    Nn is N - 1,
    !,
    elimcol(Nn,H,L).

This is able to delete for one list. However when I tried to expand deleting more lists, it doesn't seem to delete the "ith element" anymore.

?- elimcol(3,[[1,2,3], [1,1,1], [4,5,6]], X).
X = [[1, 2, 3], [1, 1, 1]].

Appreciate any help on this. Many thanks!

EDIT: Did some minor changes, however same result i'm still only able to delete ith elements for (just one list)

elimcol(_, [], []).
elimcol(1, [_|T], T) :- !.
elimcol(I, [H|T], [H|R]) :-
   I1 is I-1,
   !,
   elimcol(I1, T, R).

Body:
maplist/N it's an idiomatic way to prove a relation among multiple lists elements,
and nth1/4 can be used to discard the column from a row. Then

del_mat_col(M,N,M1) :-
    maplist(del_col(N),M,M1).
del_col(N,R,R1) :- nth1(N,R,_,R1).

yields

?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,1,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[b, c], [e, f], [h, j]].

?- M=[[a,b,c],[d,e,f],[g,h,j]],del_mat_col(M,2,M1).
M = [[a, b, c], [d, e, f], [g, h, j]],
M1 = [[a, c], [d, f], [g, j]].

Using library(yall), the code becomes:

del_mat_col(M,N,M1) :-
    maplist({N}/[R,R1]>>nth1(N,R,_,R1),M,M1).


问:
Put & Delete method not working in Retrofit and rxjava Android
I creating Android application with retrofit & rxjava, server in nodejs. I created post function its working but I created Put function its not working it shows successful but its not affected in mysql
help me to solve this problem its save my life

I tested my Api with postman its working. Its problem in Android retrofit I don't where its mistake

MyApi

```<code>connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected with mysql database...')
})

var server = app.listen(3000, function () {
  var port = server.address().port
  console.log("Server listening at", port)
});

app.get('/get', function (req, res) {
   connection.query('select * from customer', function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.get('/get/:id', function (req, res) {
   connection.query('select * from customer where Id=?', [req.params.id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.post('/register', function (req, res) {
   var params  = req.body;
   console.log(params);
   connection.query('INSERT INTO customer SET ?', params, function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.put('/update/:id', function (req, res) {
   connection.query('UPDATE `customer` SET `Name`=?,`Address`=?,`Country`=?,`Phone`=? where `Id`=?', [req.body.Name,req.body.Address, req.body.Country, req.body.Phone, req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.delete('/delete/:id', function (req, res) {
   console.log(req.body);
   connection.query('DELETE FROM `customer` WHERE `Id`=?', [req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end('Record has been deleted!');
    });
});
</code>```

INodeJS.java

```<code>public interface INodeJS {
    @POST("register")
    @FormUrlEncoded
    Observable<String> insert(@Field("Id") String id,
                                    @Field("Name") String name,
                                    @Field("Address") String address,
                                    @Field("Country") String Country,
                                    @Field("Phone") String Phone);
    @PUT("update/{Id}/")
    @FormUrlEncoded
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
}
</code>```

RetrofitClient.java

```<code>public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance(OkHttpClient client)
    {
        if(instance == null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:3000")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
            return instance;
    }
}
</code>```

MainActivity.java

```<code>INodeJS myApi;
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = RetrofitClient.getInstance(okHttpClient);
        myApi = retrofit.create(INodeJS.class);

        edit_id = findViewById(R.id.id);
        edit_name = findViewById(R.id.name);
        edit_address = findViewById(R.id.address);
        edit_country = findViewById(R.id.country);
        edit_phone = findViewById(R.id.phone);
        insert = findViewById(R.id.btn_insert);
        update = findViewById(R.id.btn_update);

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
    }
    private void updateuser(String id, String name, String address, String country, String phone)
    {
        compositeDisposable.add(myApi.update(id,name,address,country,phone)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Toast.makeText(MainActivity.this,"Data updated",Toast.LENGTH_LONG).show();
            }
        }));
    }
    private void insertuser(String id, String name, String address, String country, String phone) {

        compositeDisposable.add(myApi.insert(id,name,address,country,phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
                        clear_edittext();
                    }
                }));
    }
</code>```

I am using HttpLoggingInterceptor to all function while update function

```<code>D/OkHttp: --> PUT http://10.0.2.2:3000/update/100/
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 53
D/OkHttp: Name=David&Address=sydney&Country=Australia&Phone=234555
D/OkHttp: --> END PUT (53-byte body)
D/OkHttp: <-- 200 OK http://10.0.2.2:3000/update/100/ (110ms)
D/OkHttp: X-Powered-By: Express
D/OkHttp: Connection: keep-alive
D/OkHttp: Content-Length: 169
</code>```

答:
Just remove / from the end of your endpoint and do like below.

Also, set your base URL like this "http://10.0.2.2:3000/"

```<code>    @FormUrlEncoded
    @PUT("update/{Id}")
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
</code>```

Body:
I creating Android application with retrofit & rxjava, server in nodejs. I created post function its working but I created Put function its not working it shows successful but its not affected in mysql
help me to solve this problem its save my life

I tested my Api with postman its working. Its problem in Android retrofit I don't where its mistake

MyApi

connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected with mysql database...')
})

var server = app.listen(3000, function () {
  var port = server.address().port
  console.log("Server listening at", port)
});

app.get('/get', function (req, res) {
   connection.query('select * from customer', function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.get('/get/:id', function (req, res) {
   connection.query('select * from customer where Id=?', [req.params.id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.post('/register', function (req, res) {
   var params  = req.body;
   console.log(params);
   connection.query('INSERT INTO customer SET ?', params, function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.put('/update/:id', function (req, res) {
   connection.query('UPDATE `customer` SET `Name`=?,`Address`=?,`Country`=?,`Phone`=? where `Id`=?', [req.body.Name,req.body.Address, req.body.Country, req.body.Phone, req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.delete('/delete/:id', function (req, res) {
   console.log(req.body);
   connection.query('DELETE FROM `customer` WHERE `Id`=?', [req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end('Record has been deleted!');
    });
});

INodeJS.java

public interface INodeJS {
    @POST("register")
    @FormUrlEncoded
    Observable<String> insert(@Field("Id") String id,
                                    @Field("Name") String name,
                                    @Field("Address") String address,
                                    @Field("Country") String Country,
                                    @Field("Phone") String Phone);
    @PUT("update/{Id}/")
    @FormUrlEncoded
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
}

RetrofitClient.java

public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance(OkHttpClient client)
    {
        if(instance == null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:3000")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
            return instance;
    }
}

MainActivity.java

INodeJS myApi;
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = RetrofitClient.getInstance(okHttpClient);
        myApi = retrofit.create(INodeJS.class);

        edit_id = findViewById(R.id.id);
        edit_name = findViewById(R.id.name);
        edit_address = findViewById(R.id.address);
        edit_country = findViewById(R.id.country);
        edit_phone = findViewById(R.id.phone);
        insert = findViewById(R.id.btn_insert);
        update = findViewById(R.id.btn_update);

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
    }
    private void updateuser(String id, String name, String address, String country, String phone)
    {
        compositeDisposable.add(myApi.update(id,name,address,country,phone)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Toast.makeText(MainActivity.this,"Data updated",Toast.LENGTH_LONG).show();
            }
        }));
    }
    private void insertuser(String id, String name, String address, String country, String phone) {

        compositeDisposable.add(myApi.insert(id,name,address,country,phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
                        clear_edittext();
                    }
                }));
    }

I am using HttpLoggingInterceptor to all function while update function

D/OkHttp: --> PUT http://10.0.2.2:3000/update/100/
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 53
D/OkHttp: Name=David&Address=sydney&Country=Australia&Phone=234555
D/OkHttp: --> END PUT (53-byte body)
D/OkHttp: <-- 200 OK http://10.0.2.2:3000/update/100/ (110ms)
D/OkHttp: X-Powered-By: Express
D/OkHttp: Connection: keep-alive
D/OkHttp: Content-Length: 169

Body:
Just remove / from the end of your endpoint and do like below.

Also, set your base URL like this "http://10.0.2.2:3000/"

    @FormUrlEncoded
    @PUT("update/{Id}")
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);


问:
How to calculate score while using SVM?
I am new to machine learning, I am a bit confused by the documentation of the sklearn on how to get the score while using sklearn.svm.SVC.

This is my code

```<code>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.30)

for _c in [0.4,0.6,0.8,1.0,1.2,1.4]:
    svm=SVC(C=_c,kernel='linear')
    svm.fit(x_train,y_train)
    result=svm.predict(x_test)
    print('C value is {} and score is {}'.format(_c,svm.score(x_test,y_test)))
</code>```

This is the output

```<code>C value is 0.4 and score is 0.0091324200913242
C value is 0.6 and score is 0.0091324200913242
C value is 0.8 and score is 0.0091324200913242
C value is 1.0 and score is 0.0091324200913242
C value is 1.2 and score is 0.0091324200913242
C value is 1.4 and score is 0.0091324200913242
</code>```

I see all the score are same, my question how to determine the best score of my model?

should I pass the predicted value to svm.score y value i.e.

```<code>result=svm.predict(x_test)
svm.score(x_test,result))
</code>```

should I pass the x_test and y_test value i.e.

```<code>svm.score(x_test,y_test))
</code>```

答:
To your question:

It is wrong, you cannot compare features xwith your target y

Same mistake as in 1.

you have to use:

```<code>for _c in [0.4,0.6,0.8,1.0,1.2,1.4]:
    svm=SVC(C=_c,kernel='linear')
    svm.fit(x_train,y_train)
    result=svm.predict(x_test)
    print('C value is {} and score is {}'.format(_c,svm.score(y_test,result)))
</code>```

This will compare your original target values y_test with your predicted values result . That is the idea of testing, you test your prediction against original values to see how good/bad your prediction is.

Title: How to calculate score while using SVM?

Body:
I am new to machine learning, I am a bit confused by the documentation of the sklearn on how to get the score while using sklearn.svm.SVC.

This is my code

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.30)

for _c in [0.4,0.6,0.8,1.0,1.2,1.4]:
    svm=SVC(C=_c,kernel='linear')
    svm.fit(x_train,y_train)
    result=svm.predict(x_test)
    print('C value is {} and score is {}'.format(_c,svm.score(x_test,y_test)))

This is the output

C value is 0.4 and score is 0.0091324200913242
C value is 0.6 and score is 0.0091324200913242
C value is 0.8 and score is 0.0091324200913242
C value is 1.0 and score is 0.0091324200913242
C value is 1.2 and score is 0.0091324200913242
C value is 1.4 and score is 0.0091324200913242

I see all the score are same, my question how to determine the best score of my model?

should I pass the predicted value to svm.score y value i.e.

result=svm.predict(x_test)
svm.score(x_test,result))

should I pass the x_test and y_test value i.e.

svm.score(x_test,y_test))

Body:
To your question:

It is wrong, you cannot compare features xwith your target y

Same mistake as in 1.

you have to use:

for _c in [0.4,0.6,0.8,1.0,1.2,1.4]:
    svm=SVC(C=_c,kernel='linear')
    svm.fit(x_train,y_train)
    result=svm.predict(x_test)
    print('C value is {} and score is {}'.format(_c,svm.score(y_test,result)))

This will compare your original target values y_test with your predicted values result . That is the idea of testing, you test your prediction against original values to see how good/bad your prediction is.


问:
React/JavaScript, can someone explain why setState doesn't seem to correctly update the state during the function?

searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }```

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!

答:
One question: When do you call 'searchProject' method and with how many parameters at a single go?

From the given snippet it looks like this method can be called with multiple parameters at the same time which updates -'projectList' is every if block. So it would be better if you perform all conditional checks before you update the state a single go. Use a single 'projects' variable defined with let before all the conditional checks.

One small observation: Given snippet has arrow function syntax for filter methods, kindly update the 'searchProject' to the same syntax as well.

Body:
searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!


问:
calling azure graph api to fetch Get-PimAzureResourceRoleDefinition
I am trying to a call graphapi to get roledefination but i am getting permission errors, and  have i checked my service prnciple it had all required permissions.

```<code>Invoke-RestMethod : {
  "error": {
    "code": "UnknownError",
    "message": "{\"errorCode\":\"PermissionScopeNotGranted\",\"message\":\"Authorization failed due to missing permission scope PrivilegedAccess.ReadWrite.AzureResources,PrivilegedAccess.Read.AzureResources.\",\"target\":null,\"details\":null,\"innerError\":null,\"instanceAnnotations\":[],\"typeAnnotation\":null}",
        "innerError": {
          "request-id": "d762f8d4-2cc4-428e-b1ea-7623d8d388f1",
          "date": "2020-06-03T04:25:03"
        }
      }
    }
    At line:38 char:15
    +     $Result = Invoke-RestMethod -Uri $uri -Headers $Headers
    +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
        + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

    Below is my code
    ========================

    $TenantName = 'xxxx.onmicrosoft.com'
    $ClientId = 'xxxxxx'
    $ClientSecret = "xxxxxx"

    # Create a hashtable for the body, the data needed for the token request
    # The variables used are explained above
    $Body = @{
        'tenant' = $TenantId
        'client_id' = $ClientId
        'scope' = 'https://graph.microsoft.com/.default'
        'client_secret' = $ClientSecret
        'grant_type' = 'client_credentials'
    }

    $Params = @{
        'Uri' = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
        'Method' = 'Post'
        'Body' = $Body
        'ContentType' = 'application/x-www-form-urlencoded'
    }

    $AuthResponse = Invoke-RestMethod @Params

    $Headers = @{
        'Authorization' = "Bearer $($AuthResponse.access_token)"
    }

        #Find Pim Role
        $uri = "https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources/xxxxxxxxxxxx/roleDefinitions`?`$filter=displayName eq 'xxxxxx-Contributors'"

    $Result = Invoke-RestMethod -Uri $uri -Headers $Headers
</code>```

Also how to get resource id of roledefination which we are passing in URL after /resources

答:
Check your Api permissions, make sure the PrivilegedAccess.Read.AzureResources is selected and click the button Grant admin consent for xxx.

You could decode your access_token via https://jwt.io/, scp shows your scopes.

Update:

how to get resource id of roledefination which we are passing in URL after /resources

try request this:

```<code>GET https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources
</code>```

Body:
I am trying to a call graphapi to get roledefination but i am getting permission errors, and  have i checked my service prnciple it had all required permissions.

Invoke-RestMethod : {
  "error": {
    "code": "UnknownError",
    "message": "{\"errorCode\":\"PermissionScopeNotGranted\",\"message\":\"Authorization failed due to missing permission scope PrivilegedAccess.ReadWrite.AzureResources,PrivilegedAccess.Read.AzureResources.\",\"target\":null,\"details\":null,\"innerError\":null,\"instanceAnnotations\":[],\"typeAnnotation\":null}",
        "innerError": {
          "request-id": "d762f8d4-2cc4-428e-b1ea-7623d8d388f1",
          "date": "2020-06-03T04:25:03"
        }
      }
    }
    At line:38 char:15
    +     $Result = Invoke-RestMethod -Uri $uri -Headers $Headers
    +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
        + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

    Below is my code
    ========================

    $TenantName = 'xxxx.onmicrosoft.com'
    $ClientId = 'xxxxxx'
    $ClientSecret = "xxxxxx"

    # Create a hashtable for the body, the data needed for the token request
    # The variables used are explained above
    $Body = @{
        'tenant' = $TenantId
        'client_id' = $ClientId
        'scope' = 'https://graph.microsoft.com/.default'
        'client_secret' = $ClientSecret
        'grant_type' = 'client_credentials'
    }

    $Params = @{
        'Uri' = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
        'Method' = 'Post'
        'Body' = $Body
        'ContentType' = 'application/x-www-form-urlencoded'
    }

    $AuthResponse = Invoke-RestMethod @Params

    $Headers = @{
        'Authorization' = "Bearer $($AuthResponse.access_token)"
    }

        #Find Pim Role
        $uri = "https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources/xxxxxxxxxxxx/roleDefinitions`?`$filter=displayName eq 'xxxxxx-Contributors'"

    $Result = Invoke-RestMethod -Uri $uri -Headers $Headers

Also how to get resource id of roledefination which we are passing in URL after /resources

Body:
Check your Api permissions, make sure the PrivilegedAccess.Read.AzureResources is selected and click the button Grant admin consent for xxx.

You could decode your access_token via https://jwt.io/, scp shows your scopes.

Update:

how to get resource id of roledefination which we are passing in URL after /resources

try request this:

GET https://graph.microsoft.com/beta/privilegedAccess/azureResources/resources


问:
How to send via my iphone application a planned emails and without launching the email application?
I know how to send email from my application by launching the iPhone Mail application, then return to my app. But I have two concerns:

1 / My first concern is how my application can send emails without opening the mail application?

So I will inform the user that the email has been sent successfully or failure on failure of transmission.

2 / My second concern is to make sending mail programmed (in scheduled task) as in the case of UILocalNotification.

I have not found a solution, I try to avoid knowing the solution that uses open source classes for sending mail via SMTP, because I want my application uses the configuration of the iphone and mail ask the user to configure where the mail is not configured.

Thank you in advance for your help.

答:
You can send mail from your app using MFMailComposeViewController.

http://developer.apple.com/library/ios/#documentation/MessageUI/Reference/MFMailComposeViewController_class/Reference/Reference.html

ContentLicense: CC BY-SA 3.0


问:
c++ premier code not giving correct output
```<code>#include <iostream>

int main()
{

    int currVal = 0, val = 0;

    if (std::cin >> currVal) {
       int cnt = 1;

       while (std::cin >> val)
       {

          if (val == currVal)
          {
             ++cnt;
          }

          else
          {
             std::cout << currVal << " occurs " << cnt << " times";
             std::cout<<std::endl;
             currVal = val;
             cnt = 1;
          }
       }
       std::cout << currVal << " occurs " << cnt << " times" << std::endl;

   }
   return 0;
}
</code>```

This code is supposed to input few integers and answer how many times each integer occurs consecutively. Note that this code has been directly copied from the book c++ premier.

for input-
42 42 42 69 69 50 50 50 100 100 100

It gives output-

```<code>42 occurs 3 times
69 occurs 2 times
50 occurs 3 times
</code>```

It is ignoring the 100s at the last.

Note that there is a line of code outside the while loop specifically to output the last inetger
.

Where did I go wrong?

答:
There is no issue with your code. 100 is not showing how many times has been entered because of the way that you had to exit from the while loop (ctrl+c perhaps).

Instead what you can do is to have a terminating number (-1 for example) if the user enters the terminating number then you exit, this way you won't have to exit the loop with ctrl+c.

@john suggested the following: you can exit by entering something that doesn't parse to a number, a character for example.

Body:
#include <iostream>

int main()
{

    int currVal = 0, val = 0;

    if (std::cin >> currVal) {
       int cnt = 1;

       while (std::cin >> val)
       {

          if (val == currVal)
          {
             ++cnt;
          }

          else
          {
             std::cout << currVal << " occurs " << cnt << " times";
             std::cout<<std::endl;
             currVal = val;
             cnt = 1;
          }
       }
       std::cout << currVal << " occurs " << cnt << " times" << std::endl;

   }
   return 0;
}

This code is supposed to input few integers and answer how many times each integer occurs consecutively. Note that this code has been directly copied from the book c++ premier.

for input-
42 42 42 69 69 50 50 50 100 100 100

It gives output-

42 occurs 3 times
69 occurs 2 times
50 occurs 3 times

It is ignoring the 100s at the last.

Note that there is a line of code outside the while loop specifically to output the last inetger
.

Where did I go wrong?


问:
Heroku is not dectecting Node.js buildpacks
I am using Heroku and trying to deploy my code, but when I try to deploy I get an error.

It says it does not detect any build packs, but I have done a version check and have the latest Node.js installed.

Is there something I am missing?

terminal:

```<code>Creating app... done, ⬢ boiling-lake-07398
https://boiling-lake-07398.herokuapp.com/ | https://git.heroku.com/boiling-lake-07398.git
Shons-MacBook-Pro:Newsletter-Signup shonswope$ git push heroku master
Enumerating objects: 1305, done.
Counting objects: 100% (1305/1305), done.
Delta compression using up to 4 threads
Compressing objects: 100% (1248/1248), done.
Writing objects: 100% (1305/1305), 1.87 MiB | 455.00 KiB/s, done.
Total 1305 (delta 179), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this a
pplication automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to pacific-bastion-08294.
remote:
To https://git.heroku.com/pacific-bastion-08294.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pacific-bastion-08294.git'
Shons-MacBook-Pro:Newsletter-Signup shonswope$ npm --version
6.12.0
Shons-MacBook-Pro:Newsletter-Signup shonswope$ node --version
v12.13.0
Shons-MacBook-Pro:Newsletter-Signup shonswope$ git --version
git version 2.24.3 (Apple Git-128)
Shons-MacBook-Pro:Newsletter-Signup shonswope$
</code>```

答:
Still, following the documentation mentioned in the error message, try and set a buildpack explicitly:

```<code>heroku buildpacks:set heroku/nodejs
</code>```

This situation may also occur if you remove or rename a file that previously led to the automatic detection of your application type and thus the automatic setting of the detected buildpack on your application.

Check also the answer for this question, and your package.json content.

As seen here, that package.json and Procfile must be at the root folder of your project.

Body:
I am using Heroku and trying to deploy my code, but when I try to deploy I get an error.

It says it does not detect any build packs, but I have done a version check and have the latest Node.js installed.

Is there something I am missing?

terminal:

Creating app... done, ⬢ boiling-lake-07398
https://boiling-lake-07398.herokuapp.com/ | https://git.heroku.com/boiling-lake-07398.git
Shons-MacBook-Pro:Newsletter-Signup shonswope$ git push heroku master
Enumerating objects: 1305, done.
Counting objects: 100% (1305/1305), done.
Delta compression using up to 4 threads
Compressing objects: 100% (1248/1248), done.
Writing objects: 100% (1305/1305), 1.87 MiB | 455.00 KiB/s, done.
Total 1305 (delta 179), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this a
pplication automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to pacific-bastion-08294.
remote:
To https://git.heroku.com/pacific-bastion-08294.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/pacific-bastion-08294.git'
Shons-MacBook-Pro:Newsletter-Signup shonswope$ npm --version
6.12.0
Shons-MacBook-Pro:Newsletter-Signup shonswope$ node --version
v12.13.0
Shons-MacBook-Pro:Newsletter-Signup shonswope$ git --version
git version 2.24.3 (Apple Git-128)
Shons-MacBook-Pro:Newsletter-Signup shonswope$

Body:
Still, following the documentation mentioned in the error message, try and set a buildpack explicitly:

heroku buildpacks:set heroku/nodejs

This situation may also occur if you remove or rename a file that previously led to the automatic detection of your application type and thus the automatic setting of the detected buildpack on your application.

Check also the answer for this question, and your package.json content.

As seen here, that package.json and Procfile must be at the root folder of your project.


问:
Fail to find the dnn implementation for LSTM
I'm trying to run a simple LSTM model with following code

```<code>model = tf.keras.models.Sequential()
model.add(tf.keras.layers.LSTM(32,
                                       input_shape=x_train_single.shape[-2:]))
model.add(tf.keras.layers.Dense(1))

model.compile(optimizer=tf.keras.optimizers.RMSprop(), loss='mae')

single_step_history = model.fit(train_data_single, epochs=EPOCHS,
                                        steps_per_epoch=EVALUATION_INTERVAL)
</code>```

The error happened when it trying to fit the model

```<code>tensorflow.python.framework.errors_impl.UnknownError:  [_Derived_]  Fail to find the dnn implementation.
     [[{{node CudnnRNN}}]]
     [[sequential/lstm/StatefulPartitionedCall]] [Op:__inference_distributed_function_3107]
</code>```

There's another error like this

```<code>2020-02-22 19:08:06.478567: W tensorflow/core/kernels/data/cache_dataset_ops.cc:820] The calling
iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the
dataset, the partially cached contents of the dataset will be discarded. This can happen if you have
an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use
`dataset.take(k).cache().repeat()` instead.
</code>```

I tried all methods on this question which doesn't work for me

my envrionment is

```<code> tensorflow-gpu 2.0
 CUDA v10
 CuDNN 7.6.5
</code>```

Solution

OK.. I found that I didn't have the latest Nvidia driver, so I upgraded, and works

答:
Answering here for the benefit of the community even if the user has provided the solution.

Upgrading Nvidia driver to the latest has resolved the issue.

You can update NVIDIA manually from here here by selecting the product details and OS, you’re going to have to download the most recent drivers from their website. You’ll then have to run the installer and overwrite the old driver.

Body:
I'm trying to run a simple LSTM model with following code

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.LSTM(32,
                                       input_shape=x_train_single.shape[-2:]))
model.add(tf.keras.layers.Dense(1))

model.compile(optimizer=tf.keras.optimizers.RMSprop(), loss='mae')

single_step_history = model.fit(train_data_single, epochs=EPOCHS,
                                        steps_per_epoch=EVALUATION_INTERVAL)

The error happened when it trying to fit the model

tensorflow.python.framework.errors_impl.UnknownError:  [_Derived_]  Fail to find the dnn implementation.
     [[{{node CudnnRNN}}]]
     [[sequential/lstm/StatefulPartitionedCall]] [Op:__inference_distributed_function_3107]

There's another error like this

2020-02-22 19:08:06.478567: W tensorflow/core/kernels/data/cache_dataset_ops.cc:820] The calling
iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the
dataset, the partially cached contents of the dataset will be discarded. This can happen if you have
an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use
`dataset.take(k).cache().repeat()` instead.

I tried all methods on this question which doesn't work for me

my envrionment is

 tensorflow-gpu 2.0
 CUDA v10
 CuDNN 7.6.5

Solution

OK.. I found that I didn't have the latest Nvidia driver, so I upgraded, and works


问:
Binary Tree: summation of all nodes between a min and max value
I have an assignment where I am given the root of a randomly generated BST. I am given randomly generated test cases for this assignment.

The assignment description is the following:

You are given the root node of a binary search tree, T, and two
  integers: min, and max. Note that min and max are not necessarily stored in the
  tree. Determine the sum of all keys stored in T that are larger than or
  equal to min, and smaller than or equal to max. Implement your algorithm
  recursively

I am not allowed to have global variables or create helper functions

my current code is this:

```<code>private static int problem2(Node root, int min, int max){

 if(root = null){
    return 0;
 }

 if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }

}
</code>```

my issue is that if at any point during my recursion, the node trips the base case and causes my function to not complete itself properly.
I believe that my ordering may be to blame.

The node classed is defined as:

```<code>private static class Node
{
    public Node left = null;
    public Node right = null;

    public int key;

    public Node(int key)
    {
        this.key = key;
    }
}
</code>```

答:
Problem I believe lies here:

```<code>if(root == null || root.key < min || root.key > max){
    return 0;
 }
</code>```

Imagine this case1 : min:10, max:20, root.key:8, here this would directly return 0, but it might be possible that there are some nodes on right child of this root that might be within the accepted range.

Similarly,
case1 : min:10, max:20, root.key:22, here this would directly return 0, but it might be possible that there are some nodes on left child of this root that might be within the accepted range.

you need to modify your code in such a way that if root.key < min, then look for nodes on right child,
while if root.key > max, then look for nodes on left child of the root.

Also, both the if conditions in your code are same, hence your flow would never enter the definition of the second if block.

Body:
I have an assignment where I am given the root of a randomly generated BST. I am given randomly generated test cases for this assignment.

The assignment description is the following:

You are given the root node of a binary search tree, T, and two
  integers: min, and max. Note that min and max are not necessarily stored in the
  tree. Determine the sum of all keys stored in T that are larger than or
  equal to min, and smaller than or equal to max. Implement your algorithm
  recursively

I am not allowed to have global variables or create helper functions

my current code is this:

private static int problem2(Node root, int min, int max){

 if(root = null){
    return 0;
 }

 if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }

}

my issue is that if at any point during my recursion, the node trips the base case and causes my function to not complete itself properly.
I believe that my ordering may be to blame.

The node classed is defined as:

private static class Node
{
    public Node left = null;
    public Node right = null;

    public int key;

    public Node(int key)
    {
        this.key = key;
    }
}

Body:
Problem I believe lies here:

if(root == null || root.key < min || root.key > max){
    return 0;
 }

Imagine this case1 : min:10, max:20, root.key:8, here this would directly return 0, but it might be possible that there are some nodes on right child of this root that might be within the accepted range.

Similarly,
case1 : min:10, max:20, root.key:22, here this would directly return 0, but it might be possible that there are some nodes on left child of this root that might be within the accepted range.

you need to modify your code in such a way that if root.key < min, then look for nodes on right child,
while if root.key > max, then look for nodes on left child of the root.

Also, both the if conditions in your code are same, hence your flow would never enter the definition of the second if block.


问:
Why the output is a string array even after assigning the variable as number in typescript?
Code:

```<code>function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);
</code>```

Output:

```<code>Example is String Array undefined
</code>```

I have given the var type as a "number", but why the output screen shows "String array"?

答: pass a number in the function instead of an example variable(that doesn't hold a value), y it shows string array as type? bcz when its undefined, the typeof undefined doesn't match with string or number, hence it goes to the else block.</p>

Body:
Code:

function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);

Output:

Example is String Array undefined

I have given the var type as a "number", but why the output screen shows "String array"?


问:
C++ equivalent blueprint event dispatcher vs blueprint events
I know delegates are the equivalent to dispatchers. But there are so many different types of event declarations. Using the UFUNCTION macro events can be defined using BlueprintNativeEvents and BlueprintImplementableEvent. But then there is DECLARE_EVENT macro. I love to overthink things. can someone explain the difference between dispatchers, events, and the various types of events? Are dispatchers the observable and events the observers to those observables in the observer pattern?</p>

答:
When you use UFUNCTIONs BlueprintNativeEvent and BlueprintImplementableEvent - it means that this function can be overriten by a Blueprint. Then you can launch a blueprint function from c++.

Then - there are several types of delegates:

DECLARE_DELEGATE - C++ only, standard delegate, only one function can bind to it.

DECLARE_MULTICAST_DELEGATE - C++ only just like standard delegate but multiple functions can bind to it an be called all at once using Broadcast function.

DECLARE_EVENT - C++ only. Just like a multicast delegate but only the owner of this event can call a Broadcast.

DECLARE_DYNAMIC_MULTICAST_DELEGATE - C++/BP. It's like a multicast delegate, but it is serializable and can be bindable from blueprints when you use BlueprintAssignable keyword in UPROPERTY.

Event Dispatcher are a BP only equivalents of DYNAMIC_MULTICAST_DELEGATE I think. You can bind multiple events to it and broadcast them at once.


问:
Reference problem in data.table following a copy
I have a complicated problem regarding an assignation by reference in a data.table column nested in another data.table. I was able to reproduce the behaviour in the reproducible example below.

I'm sorry, it's still long and need some time to be fully understand, but it's the shorter I was able to produce that point out my problem.

Let's say I create the following data.table named data_1 containing a single column of type data.table:

```<code>library(data.table)

set.seed(20200602L)

data_1 <- data.table(
  foo = replicate(5L, {
    data.table(
      bar = lapply(sample(3L, 5L, replace=TRUE), rpois, 1)
    )
  }, simplify=FALSE)
)

data_1[]
##              foo
##  1: <data.table>
##  2: <data.table>
##  3: <data.table>
##  4: <data.table>
##  5: <data.table>
</code>```

One can explore the content of the column foo below :

```<code>data_1[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0
</code>```

I would then like to create a function fun() that will add a column baz to each element in the column foo. This column baz would mirror the list in bar as shown below :

```<code>fun <- function(data) {

  data[, .(lapply(foo, function(x) {
    x[, baz:=lapply(bar, function(y) {
      rev(y)
    })]
  }))]

}
</code>```

Before to apply that function to data_1, I'll copy it into data_2 because I need to keep the original intact.

```<code>data_2 <- copy(data_1)

invisible(fun(data_1))

data_1[, foo]
##  [[1]]
##       bar   baz
##  1: 4,0,1 1,0,4
##  2:   0,2   2,0
##  3: 1,3,2 2,3,1
##  4:   1,1   1,1
##  5:     0     0
##
##  [[2]]
##     bar baz
##  1:   2   2
##  2: 0,3 3,0
##  3:   0   0
##  4: 2,3 3,2
##  5: 0,0 0,0
##
##  [[3]]
##       bar   baz
##  1: 0,1,1 1,1,0
##  2: 1,2,1 1,2,1
##  3:   2,1   1,2
##  4:     1     1
##  5:     1     1
##
##  [[4]]
##       bar   baz
##  1:     1     1
##  2:   3,3   3,3
##  3:     0     0
##  4:   2,2   2,2
##  5: 0,0,0 0,0,0
##
##  [[5]]
##     bar baz
##  1: 0,0 0,0
##  2: 0,0 0,0
##  3: 0,1 1,0
##  4: 2,1 1,2
##  5:   0   0
</code>```

One could double-check that data_2 is still intact :

```<code>data_2[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0
</code>```

Up to that point, everything looks fine. However, let's say I change my mind and I want to apply the function fun() to data_2 as well. I would have thought that it would have work the same as it did for data_1. Unfortunately, it's not :

```<code>invisible(fun(data_2))
##  Warning messages:
##  1: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  2: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  3: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  4: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  5: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.

data_2[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0
</code>```

Can someone explain me why and maybe point me a way to solve the problem?

References

```<code>sessionInfo()
##  R version 4.0.0 (2020-04-24)
##  Platform: x86_64-pc-linux-gnu (64-bit)
##  Running under: SUSE Linux Enterprise Server 12 SP5
##
##  Matrix products: default
##  BLAS:   /apps/R-4.0.0/lib/libRblas.so
##  LAPACK: /apps/R-4.0.0/lib/libRlapack.so
##
##  locale:
##   [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
##   [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
##  attached base packages:
##  [1] stats     graphics  grDevices utils     datasets  methods   base
##
##  other attached packages:
##  [1] data.table_1.12.8
##
##  loaded via a namespace (and not attached):
##  [1] compiler_4.0.0 tools_4.0.0
</code>```

答:
The .internal.selfref is not being updated by copy for the constituent data.tables:

```<code>all.equal(
  lapply(data_1$foo, attr, '.internal.selfref'),
  lapply(data_2$foo, attr, '.internal.selfref')
)
# [1] TRUE
</code>```

This needs to be updated; you can fix the issue by running alloc.col on the copied data.tables:

```<code>data_2 = copy(data_1)
# also possible to do lapply(foo, copy), but this should be slower
data_2[ , foo := lapply(foo, alloc.col)]

invisible(fun(data_1))

invisible(fun(data_2))
</code>```

Body:
I have a complicated problem regarding an assignation by reference in a data.table column nested in another data.table. I was able to reproduce the behaviour in the reproducible example below.

I'm sorry, it's still long and need some time to be fully understand, but it's the shorter I was able to produce that point out my problem.

Let's say I create the following data.table named data_1 containing a single column of type data.table:

library(data.table)

set.seed(20200602L)

data_1 <- data.table(
  foo = replicate(5L, {
    data.table(
      bar = lapply(sample(3L, 5L, replace=TRUE), rpois, 1)
    )
  }, simplify=FALSE)
)

data_1[]
##              foo
##  1: <data.table>
##  2: <data.table>
##  3: <data.table>
##  4: <data.table>
##  5: <data.table>

One can explore the content of the column foo below :

data_1[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0

I would then like to create a function fun() that will add a column baz to each element in the column foo. This column baz would mirror the list in bar as shown below :

fun <- function(data) {

  data[, .(lapply(foo, function(x) {
    x[, baz:=lapply(bar, function(y) {
      rev(y)
    })]
  }))]

}

Before to apply that function to data_1, I'll copy it into data_2 because I need to keep the original intact.

data_2 <- copy(data_1)

invisible(fun(data_1))

data_1[, foo]
##  [[1]]
##       bar   baz
##  1: 4,0,1 1,0,4
##  2:   0,2   2,0
##  3: 1,3,2 2,3,1
##  4:   1,1   1,1
##  5:     0     0
##
##  [[2]]
##     bar baz
##  1:   2   2
##  2: 0,3 3,0
##  3:   0   0
##  4: 2,3 3,2
##  5: 0,0 0,0
##
##  [[3]]
##       bar   baz
##  1: 0,1,1 1,1,0
##  2: 1,2,1 1,2,1
##  3:   2,1   1,2
##  4:     1     1
##  5:     1     1
##
##  [[4]]
##       bar   baz
##  1:     1     1
##  2:   3,3   3,3
##  3:     0     0
##  4:   2,2   2,2
##  5: 0,0,0 0,0,0
##
##  [[5]]
##     bar baz
##  1: 0,0 0,0
##  2: 0,0 0,0
##  3: 0,1 1,0
##  4: 2,1 1,2
##  5:   0   0

One could double-check that data_2 is still intact :

data_2[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0

Up to that point, everything looks fine. However, let's say I change my mind and I want to apply the function fun() to data_2 as well. I would have thought that it would have work the same as it did for data_1. Unfortunately, it's not :

invisible(fun(data_2))
##  Warning messages:
##  1: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  2: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  3: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  4: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.
##  5: In `[.data.table`(x, , `:=`(baz, lapply(bar, function(y) { :
##    Invalid .internal.selfref detected and fixed by taking a (shallow) copy of the data.table so that := can add this new column by reference. At an earlier point, this data.table has been copied by R (or was created manually using structure() or similar). Avoid names<- and attr<- which in R currently (and oddly) may copy the whole data.table. Use set* syntax instead to avoid copying: ?set, ?setnames and ?setattr. If this message doesn't help, please report your use case to the data.table issue tracker so the root cause can be fixed or this message improved.

data_2[, foo]
##  [[1]]
##       bar
##  1: 4,0,1
##  2:   0,2
##  3: 1,3,2
##  4:   1,1
##  5:     0
##
##  [[2]]
##     bar
##  1:   2
##  2: 0,3
##  3:   0
##  4: 2,3
##  5: 0,0
##
##  [[3]]
##       bar
##  1: 0,1,1
##  2: 1,2,1
##  3:   2,1
##  4:     1
##  5:     1
##
##  [[4]]
##       bar
##  1:     1
##  2:   3,3
##  3:     0
##  4:   2,2
##  5: 0,0,0
##
##  [[5]]
##     bar
##  1: 0,0
##  2: 0,0
##  3: 0,1
##  4: 2,1
##  5:   0

Can someone explain me why and maybe point me a way to solve the problem?

References

sessionInfo()
##  R version 4.0.0 (2020-04-24)
##  Platform: x86_64-pc-linux-gnu (64-bit)
##  Running under: SUSE Linux Enterprise Server 12 SP5
##
##  Matrix products: default
##  BLAS:   /apps/R-4.0.0/lib/libRblas.so
##  LAPACK: /apps/R-4.0.0/lib/libRlapack.so
##
##  locale:
##   [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
##   [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
##  attached base packages:
##  [1] stats     graphics  grDevices utils     datasets  methods   base
##
##  other attached packages:
##  [1] data.table_1.12.8
##
##  loaded via a namespace (and not attached):
##  [1] compiler_4.0.0 tools_4.0.0

Body:
The .internal.selfref is not being updated by copy for the constituent data.tables:

all.equal(
  lapply(data_1$foo, attr, '.internal.selfref'),
  lapply(data_2$foo, attr, '.internal.selfref')
)
# [1] TRUE

This needs to be updated; you can fix the issue by running alloc.col on the copied data.tables:

data_2 = copy(data_1)
# also possible to do lapply(foo, copy), but this should be slower
data_2[ , foo := lapply(foo, alloc.col)]

invisible(fun(data_1))

invisible(fun(data_2))


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答: It depends upon the machine architecture. This document explains some basics about this.</p>

OwnerDisplayName: mixedpickles

OwnerDisplayName: Vinay

ContentLicense: CC BY-SA 2.5


问:
How to modify the orientation of a
 spanning multiple columns?
I am producing a
 of alphabetically sorted items, which spans over multiple lines. An example of this can be seen here:

http://jsfiddle.net/H4FPw/1/

currently the list is laid out horizontally, as follows:

```<code>a  b  c

d  e  f

g  h  i

j  k  l
</code>```

But clients being clients, I have now been asked to change this so that the list is vertically oriented, as follows:

```<code>a  e  i

b  f  j

c  g  k

d  h  l
</code>```

Unfortunately I don't know how to do this in the nice and tidy way that I've originally done it.

Can somebody please fill me in if this is possible to do with single
 and CSS? Or do I have to make multiple lists?

答: I'd use CSS3 columns or JavaScript. IDK if it's possible by CSS2.</p>

Title: How to modify the orientation of a <ul> spanning multiple columns?

Body:
I am producing a
 of alphabetically sorted items, which spans over multiple lines. An example of this can be seen here:

http://jsfiddle.net/H4FPw/1/

currently the list is laid out horizontally, as follows:

a  b  c

d  e  f

g  h  i

j  k  l

But clients being clients, I have now been asked to change this so that the list is vertically oriented, as follows:

a  e  i

b  f  j

c  g  k

d  h  l

Unfortunately I don't know how to do this in the nice and tidy way that I've originally done it.

Can somebody please fill me in if this is possible to do with single
 and CSS? Or do I have to make multiple lists?


问:
function for the sum of all even numbers
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

```<code>function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")
</code>```

答:
Would this help?

function sumEven(s) {
  return s.split('').map(x=>+x).filter(x=>x%2==0).reduce((a,b)=>a+b)
}

console.log(sumEven('idsv366f4386523ec64qe35c'))```

Body:
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")


问:
Regular expression for URL validation (in JavaScript)
Does someone have a regex for validating urls (NOT for finding them inside a text passage)? JavaScript snippet would be preferred.</p>

答:
I couldn't find one that worked well for my needs. Written and post @ https://gist.github.com/geoffreyrobichaux/0a7774b424703b6c0fffad309ab0ad0a

function validURL(s) {
    var regexp = /^(ftp|http|https|chrome|:\/\/|\.|@){2,}(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\S*:\w*@)*([a-zA-Z]|(\d{1,3}|\.){7}){1,}(\w|\.{2,}|\.[a-zA-Z]{2,3}|\/|\?|&|:\d|@|=|\/|\(.*\)|#|-|%)*$/gum
    return regexp.test(s);
}```


问:
Need to change a textcontent of span in JS Only if input is not empty (right now, it's updating all the time)
```<code>const inputRef = document.querySelector('#name-input');
const textRef = document.querySelector('#name-output');
inputRef.addEventListener('input', event => {
  if (event.target.value != '') {
    textRef.textContent = event.target.value;
  } else {
    textRef.textContent;
  }
});
</code>```

Need to change a textContent value of span only if event.target.value is not empty. Right now it's changing inappropriately.

How can I get back default value of span, if input is not empty. Let's say I have a string "Hello, visitor" - right there, 'visitor' is span. If I'm not passing anything to input - I'm getting "Hello, visitor". If I have passed "Alex", it's returning "Hello, Alex", but i delete everything - it will be just "Hello," instead of "Hello, visitor".

答:
You should have a variable holding a default value. If input is empty, use default value as a textContent of span

const inputRef = document.querySelector('#name-input');
const textRef = document.querySelector('#name-output');
let defaultValue = 'Visitor';
inputRef.addEventListener('input', event => {
  if (event.target.value != '') {
    textRef.textContent = event.target.value;
  } else {
    textRef.textContent = defaultValue;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="name-input" />
<span>Hello, </span><span id="name-output">Visitor</span></code>```

Body:
const inputRef = document.querySelector('#name-input');
const textRef = document.querySelector('#name-output');
inputRef.addEventListener('input', event => {
  if (event.target.value != '') {
    textRef.textContent = event.target.value;
  } else {
    textRef.textContent;
  }
});

Need to change a textContent value of span only if event.target.value is not empty. Right now it's changing inappropriately.

How can I get back default value of span, if input is not empty. Let's say I have a string "Hello, visitor" - right there, 'visitor' is span. If I'm not passing anything to input - I'm getting "Hello, visitor". If I have passed "Alex", it's returning "Hello, Alex", but i delete everything - it will be just "Hello," instead of "Hello, visitor".

Body:
You should have a variable holding a default value. If input is empty, use default value as a textContent of span

const inputRef = document.querySelector('#name-input');
const textRef = document.querySelector('#name-output');
let defaultValue = 'Visitor';
inputRef.addEventListener('input', event => {
  if (event.target.value != '') {
    textRef.textContent = event.target.value;
  } else {
    textRef.textContent = defaultValue;
  }
});

<input id="name-input" />
<span>Hello, </span><span id="name-output">Visitor</span>


问:
numpy: fill offset diagonal with different values
I need to make a n*n matrix m whose elements follow m(i,i+1)=sqrt(i) and 0 otherwise. For example, for n=5, we should have

```<code>[0 a 0 0 0]
[0 0 b 0 0]
[0 0 0 c 0]
[0 0 0 0 d]
[0 0 0 0 0]
</code>```

where {a,b,c,d}=sqrt({1,2,3,4}). Here is a solution for a constant tri-diagonal matrix, but my case is a bit more complicated than that. I know I can do that with a loop or with list comprehension, but are there other ways? n can be potentially big.

e.g. (list comprehension code)

```<code>ele=lambda i,j:sqrt(i+1) if j-i==1 else 0

[[ele(i,j) for j in range(0,6)] for i in range(0,6)]
</code>```

答:
A bit late obviously but i want to introduce numpy diagflat method in this question. It can be done in this way:</p>

```<code>import numpy as np

n = 5

aux = np.arange(1 , n)
aux = np.sqrt(aux)

A = np.diagflat(aux , 1)
</code>```

Body:
I need to make a n*n matrix m whose elements follow m(i,i+1)=sqrt(i) and 0 otherwise. For example, for n=5, we should have

[0 a 0 0 0]
[0 0 b 0 0]
[0 0 0 c 0]
[0 0 0 0 d]
[0 0 0 0 0]

where {a,b,c,d}=sqrt({1,2,3,4}). Here is a solution for a constant tri-diagonal matrix, but my case is a bit more complicated than that. I know I can do that with a loop or with list comprehension, but are there other ways? n can be potentially big.

e.g. (list comprehension code)

ele=lambda i,j:sqrt(i+1) if j-i==1 else 0

[[ele(i,j) for j in range(0,6)] for i in range(0,6)]

Body:
A bit late obviously but i want to introduce numpy diagflat method in this question. It can be done in this way:

import numpy as np

n = 5

aux = np.arange(1 , n)
aux = np.sqrt(aux)

A = np.diagflat(aux , 1)


问:
Base type is not CLS-compliant, what reasons of this warning?
I have got warning from subject on one of my classes. Actually class is very simple, just an inheritor of my generic base type. Also I have some other inheritors from that generic class across the solution, and there are no such warnings.

What could be the reason(s) of this?
Compiler does not give any clues of why base type is not CLS-compliant

答: put <AssemblyClsCompliant>false</AssemblyClsCompliant> in your .csproj file of your base project and the project who refer to it.


问:
C++ nested lambda bug in VS2010 with lambda parameter capture?
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN):

```<code>int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>(
        [&] // Note capture
        {
            x = n;
        }
    );
};

lambda( -10 )(); // Call outer and inner lambdas

assert( -10 == x ); // Fails!
</code>```

This compiles but fails at the assert. Specifically, n in the inner lambda is uninitialized (0xCCCCCCCC), but x is successfully modified to its value. If I change the inner lambda's capture clause to "[&,n]", the assert passes as expected. Is this a bug with VS2010 or have I not understood how lambda capture works?

答:
It is not a bug, since n goes out of scope after lambdas return statement, thus the capture by reference is invalidated by the time you use it.

```<code>int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>( // n is local to "lambda" and is destroyed after return statement, thus when you call the std::function, the reference capture of n is invalid.
        [&]
        {
            x = n; // Undefined behaviour
        }
    );
};

auto tmp = lambda(-10);
// n is no longer valid
tmp(); // calling tmp which uses reference of n which is alrdy destroyed.

assert( -10 == x ); // Fails!
</code>```

Body:
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN):

int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>(
        [&] // Note capture
        {
            x = n;
        }
    );
};

lambda( -10 )(); // Call outer and inner lambdas

assert( -10 == x ); // Fails!

This compiles but fails at the assert. Specifically, n in the inner lambda is uninitialized (0xCCCCCCCC), but x is successfully modified to its value. If I change the inner lambda's capture clause to "[&,n]", the assert passes as expected. Is this a bug with VS2010 or have I not understood how lambda capture works?

Body:
It is not a bug, since n goes out of scope after lambdas return statement, thus the capture by reference is invalidated by the time you use it.

int x = 0;
auto lambda = [&]( int n )
{
    return std::function<void()>( // n is local to "lambda" and is destroyed after return statement, thus when you call the std::function, the reference capture of n is invalid.
        [&]
        {
            x = n; // Undefined behaviour
        }
    );
};

auto tmp = lambda(-10);
// n is no longer valid
tmp(); // calling tmp which uses reference of n which is alrdy destroyed.

assert( -10 == x ); // Fails!


答:
Since its obviously an assignment for educational purposes, I won't post a full solution, however I'll give hints that might help:

Basically you do everything right, the method definition is good.

However there are a couple of mistakes in the method itself:

First off, this piece of code:

```<code>if(root == null || root.key < min || root.key > max){
    return 0;
}
</code>```

The first condition is for the cases where you've reached the end, ok.
But what about the rest? Does the fact that the certain node is less than 'min.' implies that all its "children" also won't be able to "contribute" to the sum and will necessarily be "out of range"?

Disclaimer: I here rely on the fact that its a binary tree (as written in the title of the question), so I don't assume any ordering of elements. Even if its a Binary Search Tree my comment is still valid (think about why).

Now, the recursion itself:

```<code>if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }
</code>```

What you say here basically is "if my current root's key is out of [min,max] range then enter the recursion". Instead you should be saying "if my current root's key is within the [min,max] range then enter the recursion"

Note, that due to my first comment, this code also might change - just keep an eye on the corner cases

Title: Binary Tree: summation of all nodes between a min and max value

Body:
Since its obviously an assignment for educational purposes, I won't post a full solution, however I'll give hints that might help:

Basically you do everything right, the method definition is good.

However there are a couple of mistakes in the method itself:

First off, this piece of code:

if(root == null || root.key < min || root.key > max){
    return 0;
}

The first condition is for the cases where you've reached the end, ok.
But what about the rest? Does the fact that the certain node is less than 'min.' implies that all its "children" also won't be able to "contribute" to the sum and will necessarily be "out of range"?

Disclaimer: I here rely on the fact that its a binary tree (as written in the title of the question), so I don't assume any ordering of elements. Even if its a Binary Search Tree my comment is still valid (think about why).

Now, the recursion itself:

if(root.key < min || root.key > max){
   int lft = problem2(root.left, min, max);
   int rgt = problem2(root.right, min, max);
   int sum = lft + rgt;
   return sum;
 }

What you say here basically is "if my current root's key is out of [min,max] range then enter the recursion". Instead you should be saying "if my current root's key is within the [min,max] range then enter the recursion"

Note, that due to my first comment, this code also might change - just keep an eye on the corner cases


问:
CakePHP: upgrade from 3.9.x to 4.0: bin/cake upgrade rector --rules phpunit80 Hangs
I'm upgrading a CakePHP 3 app to CakePHP 4, and following the Upgrade Guide.

However, the bin/cake upgrade rector --rules phpunit80 <path/to/app/tests> tool hangs.

A little background, my app was made mostly in CakePHP 3.6.  I upgraded it to 3.7, then 3.8, then 3.9 and made sure everything as working (no deprecation warnings) before attempting the upgrade to 4.

I'm following the CakePHP 4.0 upgrade guide.  All steps are successful up to "Applying Rector Refactorings".

When I run this:

```<code>PS C:\xampp\htdocs\my_app\upgrade> bin/cake upgrade rector --rules phpunit80 C:\xampp\htdocs\my_app\tests
</code>```

I get this result:

```<code>Rector v0.7.26
</code>```

Then,

```<code>0/189 [>---------------------------]   0%
</code>```

And it just hangs there (about 1 hour already).

Is there any advice on how to solve this?

Thanks!
D.

答:
Well, I sort of figured out a solution to the problem.  Here it how I got Rector to work.

Downgraded my app's Cake version to 3.8.12 (was 3.9.0-RC2)

Manually fixed curly braces deprecation notice in app\vendor\cakephp\plugin-installer\src\Installer\PluginInstaller.php:170

To fix Class Cake\Composer\Installer\PluginInstaller is not autoloadable, can not call post-autoload-dump script, I deleted my app\vendor folder, then ran composer update, and that seemed to fix that.  Did not get that error up to here.

Made a backup of the well working app here and started the upgrade steps in 4.0 Upgrade Guide.

In \upgrade, ran composer install --no-dev, again got the message Class Cake\Composer\Installer\PluginInstaller is not autoloadable, can not call post-autoload-dump script.

Ran bin/cake upgrade file_rename locales <path/to/app>.  No issues.

Ran bin/cake upgrade file_rename templates <path/to/app>. OK, no issues.

Changed my config/app.php to be App=> paths => templates from 'templates' => [APP . 'Template' . DS], to 'templates' => [ROOT . DS . 'Template' . DS], (also did locales).

Ran bin/cake upgrade rector --rules phpunit80 <path/to/app/tests> and now got results.  It seemed to do all the updates, and output  some errors, but I decided to go forward.

Ran bin/cake upgrade rector --rules cakephp40 <path/to/app/src>, and now it seems to work.  It shows the number of files updated, lots of progress bars, etc.  It started outputting changes made in my controllers (in alphabetical order) but then it hangs after the first several controllers.  However, looking into my src folders, I can see that all the controllers, models, etc are updated (last modified date is just now).

Ran composer require --update-with-dependencies "phpunit/phpunit:^8.0".  Completes and looks OK.

Ran composer require --update-with-dependencies "cakephp/cakephp:4.0. LOTS of dependancy issues here. I took some alternate steps and got everything updated (actually copied the composer.json from here).  That seemed to fix the dependency problems, but there are still myriad issues with the upgraded app.

I'm not going further here as this info above addresses the original question, and I have yet to complete a clean upgrade.  Ultimately, I am leaning towards starting a fresh, clean app installation and rebuilding my app, copying and fixing code from the refactored files (like dype mentioned above).

Anyway, thanks for your replies.
Have a good one,
D.

Body:
I'm upgrading a CakePHP 3 app to CakePHP 4, and following the Upgrade Guide.

However, the bin/cake upgrade rector --rules phpunit80 <path/to/app/tests> tool hangs.

A little background, my app was made mostly in CakePHP 3.6.  I upgraded it to 3.7, then 3.8, then 3.9 and made sure everything as working (no deprecation warnings) before attempting the upgrade to 4.

I'm following the CakePHP 4.0 upgrade guide.  All steps are successful up to "Applying Rector Refactorings".

When I run this:

PS C:\xampp\htdocs\my_app\upgrade> bin/cake upgrade rector --rules phpunit80 C:\xampp\htdocs\my_app\tests

I get this result:

Rector v0.7.26

Then,

0/189 [>---------------------------]   0%

And it just hangs there (about 1 hour already).

Is there any advice on how to solve this?

Thanks!
D.