问:
Should a function have only one return statement?
Are there good reasons why it's a better practice to have only one return statement in a function?

Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?

答:
I always avoid multiple return statements. Even in small functions. Small functions can become larger, and tracking the multiple return paths makes it harder (to my small mind) to keep track of what is going on. A single return also makes debugging easier. I've seen people post that the only alternative to multiple return statements is a messy arrow of nested IF statements 10 levels deep. While I certain agree that such coding does occur, it isn't the only option. I wouldn't make the choice between a multiple return statements and a nest of IFs, I'd refactor it so you'd eliminate both. And that is how I code. The following code eliminates both issues and, in my mind, is very easy to read:

public string GetResult()
{
    string rv = null;
    bool okay = false;

    okay = PerformTest(1);

    if (okay)
    {
        okay = PerformTest(2);
    }

    if (okay)
    {
        okay = PerformTest(3);
    }

    if (okay)
    {
        okay = PerformTest(4);
    };

    if (okay)
    {
        okay = PerformTest(5);
    }

    if (okay)
    {
        rv = "All Tests Passed";
    }

    return rv;
}
```

OwnerDisplayName: David

LastEditorDisplayName: finnw


来源: stackexchange

问:
Turn Vector Into ones, zeros matrix in MATLAB
Say I have a 1xn dimensional vector with values between 0 - 9 like this:

```<code>A = [4 3 7 9 0]
</code>```

I want to convert this to an nx10 matrix like so:

```<code>A = [0 0 0 0 1 0 0 0 0 0
     0 0 0 1 0 0 0 0 0 0
     0 0 0 0 0 0 0 1 0 0
     0 0 0 0 0 0 0 0 0 1
     1 0 0 0 0 0 0 0 0 0]
</code>```

Where everything is zero, except for the column in the ith row represented by the ith element in the original vector A.

I can easily do this with a for loop:

```<code>newA = zeros(n,10);
for (i = 1:n)
    newA(i,A(i)) = 1;
end
A = newA;
</code>```

But is there a vectorized way to do this without a for loop?

答:
use sub2ind:

```<code>A = [4 3 7 9 0];
colIdx = A + 1; % indexing in matlab starts from 1
rowIdx = 1:length(A);
nRows = length(A);
nCols = max(colIdx);
B = zeros(nRows,nCols);
B(sub2ind([nRows nCols],rowIdx,colIdx)) = 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I have a 1xn dimensional vector with values between 0 - 9 like this:

A = [4 3 7 9 0]

I want to convert this to an nx10 matrix like so:

A = [0 0 0 0 1 0 0 0 0 0
     0 0 0 1 0 0 0 0 0 0
     0 0 0 0 0 0 0 1 0 0
     0 0 0 0 0 0 0 0 0 1
     1 0 0 0 0 0 0 0 0 0]

Where everything is zero, except for the column in the ith row represented by the ith element in the original vector A.

I can easily do this with a for loop:

newA = zeros(n,10);
for (i = 1:n)
    newA(i,A(i)) = 1;
end
A = newA;

But is there a vectorized way to do this without a for loop?

Body:
use sub2ind:

A = [4 3 7 9 0];
colIdx = A + 1; % indexing in matlab starts from 1
rowIdx = 1:length(A);
nRows = length(A);
nCols = max(colIdx);
B = zeros(nRows,nCols);
B(sub2ind([nRows nCols],rowIdx,colIdx)) = 1


问:
array_key_exists() expects parameter 2 to be array, string given
I have this bit of code:

```<code>if( array_key_exists('customtextcolor',$atts) ){
    // If in array, then check if none, if not none, add to CSS classes
    if ( 'none' !== $atts['customtextcolor'] ) {
        $custstyles[] = $atts['customtextcolor'];
    }
}
</code>```

Which is on line 90, and my php.log shows an error on line 90.

Apr  2 08:46:16 #####.net ool www: PHP Warning:  array_key_exists() expects parameter 2 to be array, string given in /var/www/####/wp-content/plugins/Fusion-Builder-Custom-Text-For-HP/fusion-builder-custom-text-for-hp.php on line 90

Which I thought was strange, because I was sure it is was an array, because the code works as expected. I also used echo gettype($atts); and it returns an array. When I var_dump($atts); it renders the full array.

Any idea what php.log is showing this error message?

If $atts is a string, why does gettype() identify it as an array? And why does var_dump() render it as an array?

I've looked at the other array_key_exists() questions on StackOverflow, but they aren't the same issue as far as I can tell.

答:
Change the if condition as below:

if(is_array($atts) && array_key_exists('customtextcolor', $atts))

This will check if $atts is an array at first then will check the array_key_exist operation.

Body:
I have this bit of code:

if( array_key_exists('customtextcolor',$atts) ){
    // If in array, then check if none, if not none, add to CSS classes
    if ( 'none' !== $atts['customtextcolor'] ) {
        $custstyles[] = $atts['customtextcolor'];
    }
}

Which is on line 90, and my php.log shows an error on line 90.

Apr  2 08:46:16 #####.net ool www: PHP Warning:  array_key_exists() expects parameter 2 to be array, string given in /var/www/####/wp-content/plugins/Fusion-Builder-Custom-Text-For-HP/fusion-builder-custom-text-for-hp.php on line 90

Which I thought was strange, because I was sure it is was an array, because the code works as expected. I also used echo gettype($atts); and it returns an array. When I var_dump($atts); it renders the full array.

Any idea what php.log is showing this error message?

If $atts is a string, why does gettype() identify it as an array? And why does var_dump() render it as an array?

I've looked at the other array_key_exists() questions on StackOverflow, but they aren't the same issue as far as I can tell.

ContentLicense: CC BY-SA 4.0


问:
Trouble creating foreign key in Oracle create table
I'm building some really simple tables in Oracle and I'm having trouble creating foreign keys.  The fac_ID in Equipment is the FK that references fac_ID in faculty, but it is creating an error.

I'm using Oracle 11g Express.  When I run "select * from equipment" it produces the error " ORA-00942: table or view does not exist"

```<code>CREATE TABLE Faculty(
fac_ID        VARCHAR(10)    NOT NULL,
fac_Street    VARCHAR(70)    NOT NULL,
fac_City    VARCHAR(30)    NOT NULL,
fac_PROV    VARCHAR(2)    NOT NULL,
fac_Phone    VARCHAR(12)    NOT NULL,
PRIMARY KEY (fac_ID)
);

CREATE TABLE Equipment(
equip_ID        VARCHAR(10)    NOT NULL,
fac_ID            VARCHAR(10)    NOT NULL,
equip_Name       VARCHAR(50)    NOT NULL,
equip_Quantity    VARCHAR(3)    NOT NULL,
equip_Purchase_Date    DATE    NOT NULL,
PRIMARY KEY (equip_ID),
CONSTRAINT fac_ID FOREIGN KEY (fac_ID) REFERENCES Faculty(fac_ID)
);
</code>```

答:
Me too got the following error

Error starting at line : 56 in command - drop table SONICLIVE.Address
  purge Error report - SQL Error: ORA-00942: table or view does not
  exist
  00942. 00000 -  "table or view does not exist"
  *Cause:

  *Action:

And what i did was change put the table name inside double quotes "Address"

```<code>CREATE TABLE "Studio" (
  "ID" NUMBER(5) PRIMARY KEY,
  "NAME" VARCHAR(20),
  "PHONE" VARCHAR(11),
  "ADDRESS_ID" NUMBER,
  "MANAGER_ID" NUMBER,
  CONSTRAINT fk_ADDRESS FOREIGN KEY (ADDRESS_ID) REFERENCES "Address"(ID)
);
</code>```

And it worked. I was using Oracle llg r2 XE for local testing

Body:
I'm building some really simple tables in Oracle and I'm having trouble creating foreign keys.  The fac_ID in Equipment is the FK that references fac_ID in faculty, but it is creating an error.

I'm using Oracle 11g Express.  When I run "select * from equipment" it produces the error " ORA-00942: table or view does not exist"

CREATE TABLE Faculty(
fac_ID        VARCHAR(10)    NOT NULL,
fac_Street    VARCHAR(70)    NOT NULL,
fac_City    VARCHAR(30)    NOT NULL,
fac_PROV    VARCHAR(2)    NOT NULL,
fac_Phone    VARCHAR(12)    NOT NULL,
PRIMARY KEY (fac_ID)
);

CREATE TABLE Equipment(
equip_ID        VARCHAR(10)    NOT NULL,
fac_ID            VARCHAR(10)    NOT NULL,
equip_Name       VARCHAR(50)    NOT NULL,
equip_Quantity    VARCHAR(3)    NOT NULL,
equip_Purchase_Date    DATE    NOT NULL,
PRIMARY KEY (equip_ID),
CONSTRAINT fac_ID FOREIGN KEY (fac_ID) REFERENCES Faculty(fac_ID)
);

Body:
Me too got the following error

Error starting at line : 56 in command - drop table SONICLIVE.Address
  purge Error report - SQL Error: ORA-00942: table or view does not
  exist
  00942. 00000 -  "table or view does not exist"
  *Cause:

  *Action:

And what i did was change put the table name inside double quotes "Address"

CREATE TABLE "Studio" (
  "ID" NUMBER(5) PRIMARY KEY,
  "NAME" VARCHAR(20),
  "PHONE" VARCHAR(11),
  "ADDRESS_ID" NUMBER,
  "MANAGER_ID" NUMBER,
  CONSTRAINT fk_ADDRESS FOREIGN KEY (ADDRESS_ID) REFERENCES "Address"(ID)
);

And it worked. I was using Oracle llg r2 XE for local testing


问:
Margin-top doesn't work as intended
Please look at the following example: https://jsfiddle.net/9wbm179c/

The margin-top:50px; is making this ugly gap between body and .outter. Just read the code and this message again: between body and .outter... Isn't it should be making the gap between .inner and .outter?

html,
body {
  padding: 0;
  margin: 0;
}

body {
  background: #777;
}

.outter {
  background: #099;
  text-align: center;
}

.inner {
  background: #ff0;
  width: 400px;
  height: 150px;
  margin: 0 auto;
  margin-top: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outter">
  <div class="inner">

  </div>
</div></code>```

答:
What you're seeing is called "margin collapse." https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Parent and first/last child - If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

You can address it a number of ways. One way is by using overflow:hidden; on the parent element .outter. You could also use padding-top: 50px on .outter instead of margin-top on .inner

html,body {
  padding:0;
  margin:0;
}
body {
  background:#777;
}
.outter {
  background:#099;
  text-align:center;
  overflow: hidden;
}
.inner {
  background:#ff0;
  width:400px;
  height:150px;
  margin:0 auto;
  margin-top:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outter">
  <div class="inner">

  </div>
</div></code>```

Title: Margin-top doesn't work as intended

Body:
What you're seeing is called "margin collapse." https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Parent and first/last child - If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

You can address it a number of ways. One way is by using overflow:hidden; on the parent element .outter. You could also use padding-top: 50px on .outter instead of margin-top on .inner

html,body {
  padding:0;
  margin:0;
}
body {
  background:#777;
}
.outter {
  background:#099;
  text-align:center;
  overflow: hidden;
}
.inner {
  background:#ff0;
  width:400px;
  height:150px;
  margin:0 auto;
  margin-top:50px;
}

<div class="outter">
  <div class="inner">

  </div>
</div>


问:
How to export dataframe to html with utf8 encoding
I'm using R2HTML package to export a dataframe to html, using example code below:

```<code>library(R2HTML)

HTML(dataframe_name,
     Border = 0,
     align = "center",
     classfirstline = "firstline",
     classcellinside = "cellinside",
     row.names = FALSE,
     append = TRUE)
</code>```

The store column though isn't displaying some of the characters correctly

Dataframe in R:

```<code> store          store_spend
 H.Králové      10,000
</code>```

Dataframe in HTML:

```<code> store          store_spend
 H.KrÃ¡lovÃ©    10,000
</code>```

Is there a way to keep the utf8 encoding whilst transferring it to html?

答:
Probably it is not an R2HTML issue, but the default HTML page encoding: that is, R2HTML is creating the HTML file properly, but it is not correctly rendered in your web browser.

You need to insert something like <meta charset="UTF-8"> in the HTML code, e.g., using HTML("<meta charset=\"UTF-8\">", file) in your R code.

For instance:

```<code>library(R2HTML)
dir.create(file.path(tempdir(),"R2HTML"))
target <- HTMLInitFile(file.path(tempdir(),"R2HTML"),filename="sample",
                       BackGroundColor="#BBBBEE")
HTML("<meta charset=\"UTF-8\">", file = target)
HTML(dataframe_name,
     Border = 0,
     align = "center",
     classfirstline = "firstline",
     classcellinside = "cellinside",
     row.names = FALSE,
     append = TRUE)
</code>```

I hope it helps.

Body:
I'm using R2HTML package to export a dataframe to html, using example code below:

library(R2HTML)

HTML(dataframe_name,
     Border = 0,
     align = "center",
     classfirstline = "firstline",
     classcellinside = "cellinside",
     row.names = FALSE,
     append = TRUE)

The store column though isn't displaying some of the characters correctly

Dataframe in R:

 store          store_spend
 H.Králové      10,000

Dataframe in HTML:

 store          store_spend
 H.KrÃ¡lovÃ©    10,000

Is there a way to keep the utf8 encoding whilst transferring it to html?

Body:
Probably it is not an R2HTML issue, but the default HTML page encoding: that is, R2HTML is creating the HTML file properly, but it is not correctly rendered in your web browser.

You need to insert something like <meta charset="UTF-8"> in the HTML code, e.g., using HTML("<meta charset=\"UTF-8\">", file) in your R code.

For instance:

library(R2HTML)
dir.create(file.path(tempdir(),"R2HTML"))
target <- HTMLInitFile(file.path(tempdir(),"R2HTML"),filename="sample",
                       BackGroundColor="#BBBBEE")
HTML("<meta charset=\"UTF-8\">", file = target)
HTML(dataframe_name,
     Border = 0,
     align = "center",
     classfirstline = "firstline",
     classcellinside = "cellinside",
     row.names = FALSE,
     append = TRUE)

I hope it helps.


问:
freemarker don't recognize my ftl file
I have a project use spring MVC, with Tiles3 use Freemarker as view engine, I have a page addItem.ftl

```<code><div id="content">
<fieldset>
    <legend>Add Item</legend>
    <form name="item" action="add" method="post">
        <label>
            name商品名称
            <input type="text" name="name"/>
        </label><br/>
        <label>
            serialNumber
            <input type="text" name="serialCode"/>
        </label><br/>
        <label>
            weight重量
            <input type="text" name="weight"/>
        </label><br/>

        <input type="submit" value="Save"/>
    </form>
</fieldset>
<br/>
<table class="datatable">
    <tr>
        <th>Make</th>
        <th>Model</th>
    </tr>
<#list model["carList"] as Item>
    <tr>
        <td>${Item.id}</td>
        <td>${Item.name}</td>
    </tr>
</#list>
</code>```

I have a form for user input and a table to pull data from database and display them dynamicly.
But the page display like this

as you can see, the Chinese I put in the ftl file are not displayed properly, but the Chinese I get from database and add to the page works fine. I'm sure my file encoding is utf-8. I suspect that it's the freeMarkerRenderer not configured properly, but I tryed all I can, just doesn't work, you can check out the whole project here github

答: Start the template with <#ftl encoding="UTF-8">, and now it should work properly. Of course it's annoying to do for each template, so instead you should set the default_encoding configuration setting to "UTF-8".

Title: freemarker don't recognize my ftl file

Body:
I have a project use spring MVC, with Tiles3 use Freemarker as view engine, I have a page addItem.ftl

<fieldset>
    <legend>Add Item</legend>
    <form name="item" action="add" method="post">

            name商品名称
            <input type="text" name="name"/>

            serialNumber
            <input type="text" name="serialCode"/>

            weight重量
            <input type="text" name="weight"/>

        <input type="submit" value="Save"/>
    </form>
</fieldset>

        Make
        Model

<#list model["carList"] as Item>

        ${Item.id}
        ${Item.name}

</#list>

I have a form for user input and a table to pull data from database and display them dynamicly.
But the page display like this

as you can see, the Chinese I put in the ftl file are not displayed properly, but the Chinese I get from database and add to the page works fine. I'm sure my file encoding is utf-8. I suspect that it's the freeMarkerRenderer not configured properly, but I tryed all I can, just doesn't work, you can check out the whole project here github


问:
Pagination and alternative solution
Let's suppose I have a table with 10 000 rows. Some user (for example on web site) wants to work with this table applying some where conditions and order by conditions.

Variant #1 - using sql limit and usual pagination

As I understand database must 1)find all(!) rows that meet where conditions, 2) database must sort all(!) found rows at step 1 and from these found rows 3) it must return some set defined by limit and offset.

Variant #2 - reading all ids in list structure

Another solution is do a first query to get list of ids for certain where conditions and order by conditions and save it. For every page we get rows where id in {..} and sort on client side by list we have (because database will return rows in unsorted order). Advantage of this variant is not to filter and sort all rows for every page. Disadvantage is necessity to save rather long list. Besides this variant can be used only if data don't change frequently.

Is my understand of variant #1 right? Is variant #2 used in practice or it is bad solution?

答:
Variant 1 is the "normal" way of approaching this.  In many cases, you would be surprised at how well it works.  Here are some reasons:

What looks like complex processing may actually be pretty fast, particularly by judicious use of indexes.  (For instance, the sort may not be necessary.)

The results of the query may be cached between runs.

The second approach has some downsides:

If the underlying data changes, the ids may no longer be valid.

The entire result set (in terms of ids) needs to be generated up front.  That can be expensive.  I must admit, though, that if the query has an order by, this probably is no more expensive than the first run for Variant 1.

All the ids need to be returned to the application.  This is the big killer, particularly if you can have really large numbers of ids being returned.

The application cannot continue processing until all the rows are returned, although there may be some ways around this.

That said, Variant 2 might be the best solution under some circumstances.  However, the more typical solution is to let the database handle the pagination.

Title: Pagination and alternative solution


问:
Node JS prompt library doesn't hide password
I'm using the prompt library for Node.js and I have this code:

```<code>// Entry point for the program
var prompt =require ('prompt' )
var Basic = require('./helper/basic')
var program = require('./helper/cli-args')

var pwd = new Basic()

var promptSchema = {
  properties: {
    sprintID: {
      description: "Enter sprint ID",
      type: 'integer'
    },
    password: {
      description: "Enter the password for " + program.user,
      hidden: true
    }
  }
}
prompt.start()
prompt.get(promptSchema, function (err,result) {
  if (err) console.log(err)
  program.sprint = result.sprintID
  pwd.setDigest(result.password)
  prompt.stop()
  console.log ("Sprint ID: ", program.sprint)
  console.log("Basic: ", pwd.digest);
})
</code>```

The Basic class is very simple :

```<code>// Basic authentication
var base64 = require('base-64')
var program = require ('../helper/cli-args')

class Basic {
  setDigest(pwd) {
    this.digest = base64.encode(program.user.concat(":").concat(pwd))
  }
}
module.exports = Basic
</code>```

The problem I have is that the promp doesn't hide the password.
Here is an output:

$ npm start

jira@1.0.0 start D:\Documents\Programmation\NodeJS\jira
node index.js

prompt: Enter sprint ID: 156
prompt: Enter the password for sikkache: Not the real Password
Sprint ID:  156
Basic:  c2lra2FjaGU6Tm90IHRoZSByZWFsIFBhc3N3b3Jk

As you can see, the password is clear.

Can anyone help me, I really need the password to be hidden.

答:
you can try readline-sync module

it has an option called hideEchoBack which hides typed text on screen with *

```<code>var readlineSync = require('readline-sync');

// Wait for user's response.
var userName = readlineSync.question('May I have your name? ');
console.log('Hi ' + userName + '!');

// Handle the secret text (e.g. password).
var favFood = readlineSync.question('What is your favorite food? ', {
  hideEchoBack: true // The typed text on screen is hidden by `*` (default).
});
console.log('Oh, ' + userName + ' loves ' + favFood + '!');
</code>```

Body:
I'm using the prompt library for Node.js and I have this code:

// Entry point for the program
var prompt =require ('prompt' )
var Basic = require('./helper/basic')
var program = require('./helper/cli-args')

var pwd = new Basic()

var promptSchema = {
  properties: {
    sprintID: {
      description: "Enter sprint ID",
      type: 'integer'
    },
    password: {
      description: "Enter the password for " + program.user,
      hidden: true
    }
  }
}
prompt.start()
prompt.get(promptSchema, function (err,result) {
  if (err) console.log(err)
  program.sprint = result.sprintID
  pwd.setDigest(result.password)
  prompt.stop()
  console.log ("Sprint ID: ", program.sprint)
  console.log("Basic: ", pwd.digest);
})

The Basic class is very simple :

// Basic authentication
var base64 = require('base-64')
var program = require ('../helper/cli-args')

class Basic {
  setDigest(pwd) {
    this.digest = base64.encode(program.user.concat(":").concat(pwd))
  }
}
module.exports = Basic

The problem I have is that the promp doesn't hide the password.
Here is an output:

$ npm start

jira@1.0.0 start D:\Documents\Programmation\NodeJS\jira
node index.js

prompt: Enter sprint ID: 156
prompt: Enter the password for sikkache: Not the real Password
Sprint ID:  156
Basic:  c2lra2FjaGU6Tm90IHRoZSByZWFsIFBhc3N3b3Jk

As you can see, the password is clear.

Can anyone help me, I really need the password to be hidden.

Body:
you can try readline-sync module

it has an option called hideEchoBack which hides typed text on screen with *

var readlineSync = require('readline-sync');

// Wait for user's response.
var userName = readlineSync.question('May I have your name? ');
console.log('Hi ' + userName + '!');

// Handle the secret text (e.g. password).
var favFood = readlineSync.question('What is your favorite food? ', {
  hideEchoBack: true // The typed text on screen is hidden by `*` (default).
});
console.log('Oh, ' + userName + ' loves ' + favFood + '!');


问:
Different ways of declaring user defined types in C and C++
Defined here is an enumeration in ANSI C.

```<code>enum Security_Levels
{
    black_ops,
    top_secret,
    secret,
    non_secret
};
</code>```

Now to declare s[4] of type Security_Levels , I wrote this in the main() code

```<code>    Security_Levels s[4];
</code>```

And I get this error:

```<code>file.c: In function ‘main’:
file.c:13:3: error: unknown type name ‘Security_Levels’
Security_Levels s[4];
</code>```

But when I declared it like this

```<code>enum Security_Levels s[4];
</code>```

IT WORKED!

```<code>Security_Levels s[4];
</code>```

This ^Worked in C++ but throws the aforementioned error in C

I have a similar question while using struct in C and C++ as well.

```<code>struct structure_name variable_name; //this is how it works in C
structure_name variable_name; // in  case of C++
</code>```

So, why the difference in declaring vars of user defined types?

答:
The following function will return different values in C and C++:

```<code>extern int T;

int size(void)
{
    struct T {  int i;  int j;  };

    return sizeof(T);
    /* C:   return sizeof(int)
     * C++: return sizeof(struct T)
     */
}
</code>```

This is due to C requiring struct in front of structure tags (and so sizeof(T) refers to the variable), but C++ allowing it to be omitted (and so sizeof(T) refers to the implicit typedef). Beware that the outcome is different when the extern declaration is placed inside the function: then the presence of an identifier with same name in the function scope inhibits the implicit typedef to take effect for C++, and the outcome for C and C++ would be the same. Observe also that the ambiguity in the example above is due to the use of the parenthesis with the sizeof operator. Using sizeof T would expect T to be an expression and not a type, and thus the example would not compile with C++.

From Wikipedia.

Body:
Defined here is an enumeration in ANSI C.

enum Security_Levels
{
    black_ops,
    top_secret,
    secret,
    non_secret
};

Now to declare s[4] of type Security_Levels , I wrote this in the main() code

    Security_Levels s[4];

And I get this error:

file.c: In function ‘main’:
file.c:13:3: error: unknown type name ‘Security_Levels’
Security_Levels s[4];

But when I declared it like this

enum Security_Levels s[4];

IT WORKED!

Security_Levels s[4];

This ^Worked in C++ but throws the aforementioned error in C

I have a similar question while using struct in C and C++ as well.

struct structure_name variable_name; //this is how it works in C
structure_name variable_name; // in  case of C++

So, why the difference in declaring vars of user defined types?

Body:
The following function will return different values in C and C++:

extern int T;

int size(void)
{
    struct T {  int i;  int j;  };

    return sizeof(T);
    /* C:   return sizeof(int)
     * C++: return sizeof(struct T)
     */
}

This is due to C requiring struct in front of structure tags (and so sizeof(T) refers to the variable), but C++ allowing it to be omitted (and so sizeof(T) refers to the implicit typedef). Beware that the outcome is different when the extern declaration is placed inside the function: then the presence of an identifier with same name in the function scope inhibits the implicit typedef to take effect for C++, and the outcome for C and C++ would be the same. Observe also that the ambiguity in the example above is due to the use of the parenthesis with the sizeof operator. Using sizeof T would expect T to be an expression and not a type, and thus the example would not compile with C++.

From Wikipedia.


答:
I am not sure how you went from the data to the plot.
I suspect that the color was actually based on age
which was not provided, but since that was not the point,
I just made up some value. Also, because you used the
rainbow color palette I did too, but as noted by @KonradRudolph
there are problems with rainbow and you might want to
consider a different palette.

To address your questions, the SDMTools package
includes a legend.gradient function. The function grid
will add the background grid that you want. I use all of
that in the example below. It will have to be adjusted to
match the way you actually plotted this, but this should
be close enough for you to figure it out. I called the
data structure that you provided for data DR.

```<code>library(SDMTools)
age = floor((log(DR[,1])+6)*17)
plot(colnames(DR), log(DR[1,]), type="l", ylim=c(-10,0),
    col=rainbow(102)[age[1]], xlab="Years", ylab="log Death Rate")
for(i in 2:6) {
    lines(colnames(DR), log(DR[i,]), col=rainbow(102)[age[i]]) }

LegLoc   = cbind(x =c(1900,1903,1903,1900), y =c(-8,-8,-10,-10))
legend.gradient(pnts=LegLoc, cols=rainbow(102),
    limits=c(1, 100), title = "age")
grid()
</code>```

Title: Rainbow legend in R

Body:
I have a the death rate for ages 0-100 plotted in one graph. It's very color full but for a reader there is no explanation who is age 0, age 40 or age 100 for example. I have seen rainbow legends is pictures online, but gained no answer on how to write one out myself. The line I use to plot is

plot(m, series = "total", datatype="rate", plot.type="time", xlab="Years", main="Total death rate")

What can I change to get the rainbow legend? And is there a call for writing out the grid lines in the graph area?

Snippet of the data is

structure(c(0.107446, 0.02901, 0.015211, 0.010825, 0.008799,
0.006939, 0.110958, 0.028299, 0.014543, 0.010939, 0.00893, 0.007335,
0.091162, 0.026333, 0.013556, 0.009593, 0.007193, 0.005984, 0.097073,
0.026088, 0.012508, 0.008976, 0.007057, 0.005734, 0.089595, 0.022413,
0.011188, 0.008234, 0.006767, 0.005522, 0.093491, 0.02269, 0.011209,
0.009104, 0.00724, 0.006003, 0.08592, 0.019631, 0.009459, 0.006521,
0.005931, 0.004634, 0.080883, 0.019495, 0.009131, 0.006662, 0.004753,
0.004184, 0.09061, 0.021713, 0.008999, 0.006332, 0.004717, 0.004221,
0.076158, 0.016583, 0.008261, 0.005645, 0.004305, 0.003866, 0.078229,
0.019572, 0.008195, 0.005844, 0.004747, 0.003715, 0.07538, 0.01746,
0.008253, 0.006093, 0.004857, 0.003771, 0.074146, 0.01849, 0.008344,
0.005719, 0.004848, 0.004174, 0.072209, 0.015411, 0.007567, 0.005166,
0.004282, 0.003863, 0.076099, 0.016082, 0.006845, 0.005483, 0.004198,
0.003673, 0.077503, 0.017572, 0.007786, 0.005492, 0.004817, 0.003448,
0.072559, 0.018363, 0.007551, 0.005644, 0.004607, 0.003867, 0.067097,
0.014814, 0.007276, 0.005583, 0.004591, 0.003869, 0.066543, 0.019021,
0.011272, 0.009122, 0.007382, 0.00635, 0.071861, 0.016772, 0.009663,
0.007277, 0.006925, 0.005022, 0.072476, 0.014029, 0.007611, 0.005485,
0.004887, 0.003871, 0.064407, 0.012097, 0.005361, 0.004211, 0.003923,
0.002647, 0.062224, 0.011398, 0.005304, 0.003305, 0.003032, 0.002257,
0.057591, 0.010665, 0.004426, 0.002968, 0.002496, 0.002317, 0.061385,
0.012738, 0.005614, 0.003438, 0.003094, 0.002173, 0.057092, 0.009833,
0.004379, 0.003359, 0.002478, 0.002311, 0.056902, 0.009439, 0.004451,
0.002798, 0.002614, 0.002104, 0.060825, 0.011348, 0.0047, 0.003323,
0.002893, 0.002541, 0.061088, 0.011606, 0.004853, 0.002955, 0.002427,
0.002494, 0.059242, 0.008986, 0.003939, 0.002715, 0.002199, 0.002218,
0.057243, 0.007084, 0.003793, 0.002429, 0.00217, 0.001911, 0.057835,
0.008646, 0.003879, 0.002627, 0.002119, 0.001695, 0.05217, 0.007877,
0.003303, 0.002461, 0.001783, 0.001602, 0.049842, 0.007063, 0.003305,
0.002104, 0.001544, 0.001379, 0.048754, 0.006322, 0.003006, 0.00226,
0.001961, 0.001548, 0.047834, 0.006098, 0.002681, 0.002307, 0.001882,
0.001623, 0.045679, 0.006773, 0.00329, 0.002311, 0.001794, 0.00182,
0.046924, 0.006226, 0.003433, 0.002487, 0.001901, 0.001666, 0.044641,
0.005054, 0.003138, 0.001933, 0.001878, 0.001403, 0.041354, 0.004579,
0.0025, 0.001735, 0.001648, 0.001228, 0.040073, 0.004021, 0.002109,
0.001469, 0.001155, 0.001245, 0.038778, 0.004742, 0.002258, 0.001759,
0.001354, 0.001152, 0.031958, 0.002932, 0.001877, 0.001526, 0.001338,
0.001155, 0.030943, 0.003213, 0.00218, 0.001858, 0.001429, 0.001144,
0.032905, 0.003633, 0.002685, 0.001904, 0.001783, 0.001572, 0.030931,
0.003345, 0.002049, 0.00173, 0.00147, 0.001261, 0.026955, 0.002292,
0.001541, 0.001232, 0.001046, 0.001022, 0.025469, 0.002239, 0.001559,
0.001314, 0.000903, 0.000907, 0.023388, 0.001881, 0.001435, 0.001149,
0.000908, 0.000592, 0.023167, 0.002012, 0.001074, 0.001072, 0.00101,
0.000708, 0.020801, 0.00185, 0.00138, 0.001153, 0.000802, 0.000886,
0.021411, 0.001977, 0.001321, 0.000922, 0.000752, 0.000671, 0.020338,
0.001702, 0.001157, 0.000908, 0.000866, 0.000721, 0.019017, 0.001688,
0.001052, 0.000873, 0.000653, 0.000666, 0.018535, 0.001483, 0.001013,
0.000808, 0.000684, 0.00048, 0.017848, 0.001449, 0.001057, 0.000808,
0.000726, 0.00064, 0.017602, 0.001388, 0.001117, 0.000751, 0.000649,
0.000526, 0.017921, 0.001424, 0.000889, 0.000784, 0.000703, 5e-04,
0.01597, 0.001387, 0.00081, 0.00084, 0.000623, 0.000619, 0.016763,
0.001251, 0.000897, 0.000707, 0.000544, 0.000613, 0.016616, 0.001419,
0.000669, 0.000624, 0.000754, 0.000573, 0.01613, 0.001077, 0.000762,
0.000688, 0.00068, 0.000546, 0.01582, 0.00105, 0.00088, 0.000703,
0.000439, 0.000556, 0.015948, 0.000929, 0.000735, 0.000528, 0.000491,
0.000534, 0.014965, 8e-04, 0.000593, 0.000656, 0.000517, 0.000519,
0.013486, 0.000925, 0.00065, 6e-04, 0.00039, 0.000564, 0.012713,
0.00092, 0.000597, 0.000437, 0.000664, 0.000505, 0.012879, 0.000723,
0.000483, 0.000443, 0.000464, 0.00035, 0.012784, 0.000719, 0.000518,
0.000508, 0.000426, 0.000391, 0.011642, 0.000668, 0.000535, 0.000449,
0.000579, 0.00039, 0.011299, 0.000668, 0.000467, 0.000547, 0.000446,
0.000511, 0.011514, 0.000598, 0.000458, 0.000355, 0.000285, 0.000356,
0.010822, 0.000602, 0.00046, 0.000486, 0.000364, 4e-04, 0.009783,
0.000588, 0.000414, 0.000388, 0.000298, 0.000391, 0.009622, 0.000725,
0.000436, 0.000234, 0.00036, 0.000507, 0.008408, 0.000701, 0.000397,
0.000311, 0.000351, 0.000378, 0.008115, 0.000522, 0.000407, 0.00027,
0.000301, 0.000332, 0.007953, 0.000501, 0.000333, 0.000379, 0.000349,
0.000238, 0.007689, 0.000531, 0.000274, 0.000314, 0.000315, 0.000393,
0.007626, 0.000673, 0.000387, 0.000264, 0.000369, 0.000324, 0.006958,
0.000567, 0.000283, 0.000295, 0.000303, 0.000221, 0.006842, 0.000412,
0.000221, 0.000231, 0.000183, 0.000195, 0.006798, 0.000427, 0.000278,
0.000294, 0.000315, 0.000183, 0.007002, 0.000352, 0.000271, 0.000237,
2e-04, 0.000189, 0.006483, 0.000421, 0.00016, 0.000229, 0.000113,
0.000137, 0.006938, 0.000472, 0.00029, 0.000244, 0.000166, 0.000216,
0.00605, 0.000569, 0.000256, 0.000236, 0.000233, 0.000166, 0.006215,
0.000426, 0.000329, 0.000266, 0.000192, 0.000169, 0.006023, 0.00051,
0.000276, 0.000205, 0.000137, 0.000191, 0.00588, 0.000422, 0.000287,
0.000157, 0.000285, 0.000168, 0.006158, 0.000392, 0.000282, 0.000266,
0.000156, 0.000141, 0.006149, 0.000389, 0.000225, 0.000181, 0.000217,
6.8e-05, 0.005339, 0.000281, 0.000256, 0.000259, 0.000144, 0.000169,
0.004757, 3e-04, 0.000241, 0.000247, 0.00018, 0.000117, 0.004349,
0.000324, 0.000161, 0.000127, 0.00022, 0.000136, 0.003988, 0.000261,
0.000191, 8.8e-05, 0.000166, 0.000138, 0.003805, 0.000352, 0.000131,
0.000141, 0.000168, 0.00015, 0.003541, 0.000443, 0.000139, 0.000174,
0.000125, 0.000112, 0.003521, 0.000312, 0.000191, 0.000139, 0.000113,
0.000125, 0.003343, 0.000233, 0.000172, 8e-05, 8.3e-05, 7.8e-05,
0.00345, 0.000223, 0.00011, 6.4e-05, 1e-04, 6.5e-05, 0.003661,
0.000276, 0.000211, 0.000154, 0.000106, 1e-04, 0.003334, 0.00026,
0.000275, 0.00011, 0.000109, 9.5e-05, 0.003154, 0.000316, 0.000205,
0.000153, 0.00011, 0.000109, 0.003134, 0.000213, 0.000126, 7.5e-05,
8.7e-05, 8.7e-05, 0.002427, 0.000415, 0.000141, 0.000198, 8.6e-05,
0.00013, 0.002857, 0.000293, 0.000137, 0.00015, 0.000114, 0.000107,
0.002503, 0.000314, 0.000145, 8.8e-05, 0.000109, 0.000113, 0.002501,
0.000222, 0.00016, 6.7e-05, 9.7e-05, 8.9e-05, 0.002506, 0.000327,
0.000219, 0.000196, 4.8e-05, 7.7e-05, 0.002578, 0.00025, 0.000126,
0.000109, 0.000111, 3.8e-05, 0.002061, 0.00026, 4.4e-05, 0.000117,
0.000108, 5.5e-05, 0.002597, 0.000156, 0.000129, 0.000105, 0.000125,
6.3e-05, 0.002689, 0.000123, 9.5e-05, 0.000136, 9.6e-05, 7.1e-05,
0.002183, 0.000217, 4.3e-05, 0.000119, 5.9e-05, 9.5e-05), .Dim = c(6L,
115L), .Dimnames = list(c("0", "1", "2", "3", "4", "5"), c("1900",
"1901", "1902", "1903", "1904", "1905", "1906", "1907", "1908",
"1909", "1910", "1911", "1912", "1913", "1914", "1915", "1916",
"1917", "1918", "1919", "1920", "1921", "1922", "1923", "1924",
"1925", "1926", "1927", "1928", "1929", "1930", "1931", "1932",
"1933", "1934", "1935", "1936", "1937", "1938", "1939", "1940",
"1941", "1942", "1943", "1944", "1945", "1946", "1947", "1948",
"1949", "1950", "1951", "1952", "1953", "1954", "1955", "1956",
"1957", "1958", "1959", "1960", "1961", "1962", "1963", "1964",
"1965", "1966", "1967", "1968", "1969", "1970", "1971", "1972",
"1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980",
"1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988",
"1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996",
"1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
"2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012",
"2013", "2014")))

Body:
I am not sure how you went from the data to the plot.
I suspect that the color was actually based on age
which was not provided, but since that was not the point,
I just made up some value. Also, because you used the
rainbow color palette I did too, but as noted by @KonradRudolph
there are problems with rainbow and you might want to
consider a different palette.

To address your questions, the SDMTools package
includes a legend.gradient function. The function grid
will add the background grid that you want. I use all of
that in the example below. It will have to be adjusted to
match the way you actually plotted this, but this should
be close enough for you to figure it out. I called the
data structure that you provided for data DR.

library(SDMTools)
age = floor((log(DR[,1])+6)*17)
plot(colnames(DR), log(DR[1,]), type="l", ylim=c(-10,0),
    col=rainbow(102)[age[1]], xlab="Years", ylab="log Death Rate")
for(i in 2:6) {
    lines(colnames(DR), log(DR[i,]), col=rainbow(102)[age[i]]) }

LegLoc   = cbind(x =c(1900,1903,1903,1900), y =c(-8,-8,-10,-10))
legend.gradient(pnts=LegLoc, cols=rainbow(102),
    limits=c(1, 100), title = "age")
grid()


问:
What does entity.Items.Clear() do in EF?
In a project I'm working on, whenever I call SaveChanges() after clearing list of items, I get this error:

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.

I have these two classes with one to many relationship (simplest implementation):

```<code>public class Company
{
  public int Id {get; set;}
  public string Name {get; set;}
  public virtual List<Vehicle> Vehicles {get; set;}
}

public class Vehicle
{
    public int Id {get; set;}
    public string Model {get; set;}

}
</code>```

I'm guessing that calling company.Vehicles.Clear() should update the auto generated column Company_Id in the Vehicle table, setting its value to null, but that not seems the case which the error above indicating.
So I'me wondering what exactly company.Vehicles.Clear() do in the database side?

EDIT

Thanks to the answer by @McKabue and the link he provided, I found this is the solution, this is the complete code:

```<code>var company = context.Set<GENCompany>().
                        Include(m => m.Vehicles).
                        Include(m => m.Quotes).
                        Include(m => m.Phones).
                        Include(m => m.Persons).
                        Include(m => m.Leads).
                        Include(m => m.Emails).
                        Include(m => m.Drivers).
                        Include(m => m.Deals).
                        Include(m => m.Comments).
                        Include(m => m.Branches).
                        Include(m => m.Addresses).
                        SingleOrDefault(m => m.Id == companyModel.Id);

                    context.Entry(company).State = EntityState.Modified;

                    company.Vehicles.Clear();
                    company.Drivers.Clear();
                    company.Quotes.Clear();
                    company.Persons.Clear();
                    company.Leads.Clear();
                    company.Deals.Clear();
                    company.Branches.Clear();

                    var phones = context.CompanyPhones.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyPhones.RemoveRange(phones);

                    var emails = context.CompanyEmails.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyEmails.RemoveRange(emails);

                    var comments = context.CompanyComments.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyComments.RemoveRange(comments);

                    var addresses = context.CompanyAddresses.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyAddresses.RemoveRange(addresses);
</code>```

For some entities they are removed using .Clear() syntax, other entities are removed by fetching their records and deleteing them all (not only the relation). It makes perfect sense in the current design, for example in the create page of the company, the phone data is added manually, while vehicles are selected from drop down menu, while it makes this perfect sense I feel so confused to determine why this happen, for example here is the CompanyPhone class:

```<code> public class GENCompanyPhone
    {
        [Key]
        public long PhoneId { get; set; }
        public long CompanyId { get; set; }
        public long PhoneTypeId { get; set; }
        public DateTime DateCreated { get; set; } = DateTime.Now;
        public DateTime DateUpdated { get; set; } = DateTime.Now;
        public Guid? CreatedById { get; set; }
        public bool IsPublish { get; set; } = false;
        public bool IsActive { get; set; } = false;

        [MaxLength(255)]
        [Index(IsUnique = true)]
        public string PhoneNumber { get; set; }
        [ForeignKey("CompanyId")]
        public virtual GENCompany Company { get; set; }
    }
</code>```

on the other hand this is the vehicle class:

```<code>public class GENVehicle
    {
        public long Id { get; set; }
        public long? BrandId { get; set; }
        [ForeignKey("BrandId")]
        public GENBrand Brand { get; set; }
        public string Model { get; set; }
        public DateTime? LicenseIssueDate { get; set; }

        public Guid? CreatedById { get; set; }

        [ForeignKey("VehicleTypeId")]
        public virtual GENVehicleType VehicleType { get; set; }
        public long? VehicleTypeId { get; set; }
        public long? LicenseIssuerId { get; set; }
        [ForeignKey("LicenseIssuerId")]
        public GENEmployee LicenseIssuer { get; set; }

    }
</code>```

I can't determine exactly why EF deal differently with Vehicle and CompanyPhone

答:
It means that you are clearing a record that is referenced in another table. So, EF warns you...there are ways you can avoid this by setting Cascade delete

Edit
To remove child elements from a parent table, the children entities need to be loaded.

Edit 2

```<code>var company = context.Set<GENCompany>().Where(m => m.Id == companyModel.Id);
                        Include(m => m.Vehicles).
                        Include(m => m.Quotes).
                        Include(m => m.Phones).
                        Include(m => m.Persons).
                        Include(m => m.Leads).
                        Include(m => m.Emails).
                        Include(m => m.Drivers).
                        Include(m => m.Deals).
                        Include(m => m.Comments).
                        Include(m => m.Branches).
                        Include(m => m.Addresses).SingleOrDefault();

                    company.Vehicles.Clear();
                    company.Drivers.Clear();
                    company.Quotes.Clear();
                    company.Persons.Clear();
                    company.Leads.Clear();
                    company.Deals.Clear();
                    company.Branches.Clear();
</code>```

THAT WILL WORK

Query before Including

Include All entities you want to remove;

Clear / RemoveRange / Remove one by one from the parent (company object)

Body:
In a project I'm working on, whenever I call SaveChanges() after clearing list of items, I get this error:

The operation failed: The relationship could not be changed because
  one or more of the foreign-key properties is non-nullable. When a
  change is made to a relationship, the related foreign-key property is
  set to a null value. If the foreign-key does not support null values,
  a new relationship must be defined, the foreign-key property must be
  assigned another non-null value, or the unrelated object must be
  deleted.

I have these two classes with one to many relationship (simplest implementation):

public class Company
{
  public int Id {get; set;}
  public string Name {get; set;}
  public virtual List<Vehicle> Vehicles {get; set;}
}

public class Vehicle
{
    public int Id {get; set;}
    public string Model {get; set;}

}

I'm guessing that calling company.Vehicles.Clear() should update the auto generated column Company_Id in the Vehicle table, setting its value to null, but that not seems the case which the error above indicating.
So I'me wondering what exactly company.Vehicles.Clear() do in the database side?

EDIT

Thanks to the answer by @McKabue and the link he provided, I found this is the solution, this is the complete code:

var company = context.Set<GENCompany>().
                        Include(m => m.Vehicles).
                        Include(m => m.Quotes).
                        Include(m => m.Phones).
                        Include(m => m.Persons).
                        Include(m => m.Leads).
                        Include(m => m.Emails).
                        Include(m => m.Drivers).
                        Include(m => m.Deals).
                        Include(m => m.Comments).
                        Include(m => m.Branches).
                        Include(m => m.Addresses).
                        SingleOrDefault(m => m.Id == companyModel.Id);

                    context.Entry(company).State = EntityState.Modified;

                    company.Vehicles.Clear();
                    company.Drivers.Clear();
                    company.Quotes.Clear();
                    company.Persons.Clear();
                    company.Leads.Clear();
                    company.Deals.Clear();
                    company.Branches.Clear();

                    var phones = context.CompanyPhones.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyPhones.RemoveRange(phones);

                    var emails = context.CompanyEmails.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyEmails.RemoveRange(emails);

                    var comments = context.CompanyComments.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyComments.RemoveRange(comments);

                    var addresses = context.CompanyAddresses.Where(x => x.CompanyId == companyModel.Id);
                    context.CompanyAddresses.RemoveRange(addresses);

For some entities they are removed using .Clear() syntax, other entities are removed by fetching their records and deleteing them all (not only the relation). It makes perfect sense in the current design, for example in the create page of the company, the phone data is added manually, while vehicles are selected from drop down menu, while it makes this perfect sense I feel so confused to determine why this happen, for example here is the CompanyPhone class:

 public class GENCompanyPhone
    {
        [Key]
        public long PhoneId { get; set; }
        public long CompanyId { get; set; }
        public long PhoneTypeId { get; set; }
        public DateTime DateCreated { get; set; } = DateTime.Now;
        public DateTime DateUpdated { get; set; } = DateTime.Now;
        public Guid? CreatedById { get; set; }
        public bool IsPublish { get; set; } = false;
        public bool IsActive { get; set; } = false;

        [MaxLength(255)]
        [Index(IsUnique = true)]
        public string PhoneNumber { get; set; }
        [ForeignKey("CompanyId")]
        public virtual GENCompany Company { get; set; }
    }

on the other hand this is the vehicle class:

public class GENVehicle
    {
        public long Id { get; set; }
        public long? BrandId { get; set; }
        [ForeignKey("BrandId")]
        public GENBrand Brand { get; set; }
        public string Model { get; set; }
        public DateTime? LicenseIssueDate { get; set; }

        public Guid? CreatedById { get; set; }

        [ForeignKey("VehicleTypeId")]
        public virtual GENVehicleType VehicleType { get; set; }
        public long? VehicleTypeId { get; set; }
        public long? LicenseIssuerId { get; set; }
        [ForeignKey("LicenseIssuerId")]
        public GENEmployee LicenseIssuer { get; set; }

    }

I can't determine exactly why EF deal differently with Vehicle and CompanyPhone

Body:
It means that you are clearing a record that is referenced in another table. So, EF warns you...there are ways you can avoid this by setting Cascade delete

Edit
To remove child elements from a parent table, the children entities need to be loaded.

Edit 2

var company = context.Set<GENCompany>().Where(m => m.Id == companyModel.Id);
                        Include(m => m.Vehicles).
                        Include(m => m.Quotes).
                        Include(m => m.Phones).
                        Include(m => m.Persons).
                        Include(m => m.Leads).
                        Include(m => m.Emails).
                        Include(m => m.Drivers).
                        Include(m => m.Deals).
                        Include(m => m.Comments).
                        Include(m => m.Branches).
                        Include(m => m.Addresses).SingleOrDefault();

                    company.Vehicles.Clear();
                    company.Drivers.Clear();
                    company.Quotes.Clear();
                    company.Persons.Clear();
                    company.Leads.Clear();
                    company.Deals.Clear();
                    company.Branches.Clear();

THAT WILL WORK

Query before Including

Include All entities you want to remove;

Clear / RemoveRange / Remove one by one from the parent (company object)


问:
C++ static pointer to function
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

```<code>//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}
</code>```

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

```<code>int (X::*staticFunc)(const X&) = NULL;
</code>```

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

答:
```<code>//file.cpp
int (*X::staticFunc)(const X&);

void X::f()
{
staticFunc(*this);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++ static pointer to function

Body:
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

int (X::*staticFunc)(const X&) = NULL;

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.


问:
How to make the VS Code PowerShell integrated console commands code the same color as the color theme in VS Code
I've been trying to find if there is a way to make the PowerShell integrated console commands code the same color as the color theme in VS Code.

So far everything I've found has only been about the theme colors for code inside files but nothing about changing the integrated console code colors.  I'm not even sure if this is possible inside the integrated PowerShell console.

答:
I would have expected that you could change the colours using the Set-PSReadLineOption command as you can in the terminal but whilst Get-ReadLineOption returns results Set-PsReadLineOption does not change the colours so I expect that it is not possible

Also you won't be able to match the formatting exactly anyway as the colours available in Set-PsReadlineOption and the options are not compatible


问:
Output of a function in maxima
I have programmed a function F which round the input following some specific rules. For example, if my input is F(0.1355) it gives as output 1.4b-1. The problem is that, when I do F(0.1355)^2, it gives me 1.96382999420166b-2, when it should give me 0.14^2, i.e, 1.96b-2. Why is this happening? and, how can I fix it?

This is the code of my function:

```<code>F(x):=(block ([log10,aaa,fpprec],log10(x):=entier(log(x)/log(10)),
    vnorm(x):= if x/(10^(log10(x)))<2 then 1/(10^(log10(x)-1)) else 1/10^(log10(x)),
     aaa(x):= x*vnorm(x),
    fpprec:if aaa(x)<20 then 2 else 1,bfloat((round(aaa(x)))*1/vnorm(x)))); `
</code>```

More info: I can't declare fpprec as global variable. I know that would solve my problem.
Best regards,

Lievet.

答:
Well, the problem is that F(x)^2 is computed with the value of fpprec outside of the block, which is 16. First F(x) is computed with fpprec = 2; call that result foo. Then foo^2 is computed with fpprec = 16.

I don't know a way to limit the precision for bigfloat computations to the precision of the operands. It may be possible with simplification rules (tellsimp or tellsimpafter) but, if so, it is probably not easy.

Two ideas to make some progress here. (1) Consider using rational numbers instead of bigfloats. I.e. return 7/5 instead of 1.4b-1. (2) If you are just trying to limit the digits that are printed, use fpprintprec.

Maybe if you say more about what is your larger goal here, someone will have some advice.

Title: Output of a function in maxima

Body:
I have programmed a function F which round the input following some specific rules. For example, if my input is F(0.1355) it gives as output 1.4b-1. The problem is that, when I do F(0.1355)^2, it gives me 1.96382999420166b-2, when it should give me 0.14^2, i.e, 1.96b-2. Why is this happening? and, how can I fix it?

This is the code of my function:

F(x):=(block ([log10,aaa,fpprec],log10(x):=entier(log(x)/log(10)),
    vnorm(x):= if x/(10^(log10(x)))<2 then 1/(10^(log10(x)-1)) else 1/10^(log10(x)),
     aaa(x):= x*vnorm(x),
    fpprec:if aaa(x)<20 then 2 else 1,bfloat((round(aaa(x)))*1/vnorm(x)))); `

More info: I can't declare fpprec as global variable. I know that would solve my problem.
Best regards,

Lievet.


问:
Interfacing C with Java on Linux
For a project I need to be able to use some C programs through Java. Our teachers have told us we can use minGW but that only seems to work on Windows, and my machine is running Linux (Mint 18).
I saw posts about using javah, but when I attempt to use it, I get the following message

```<code>> javah HelloJNI The program 'javah' can be found in the following
> packages:  * gcj-4.8-jdk  * openjdk-7-jdk  * gcj-4.6-jdk  *
> openjdk-6-jdk Try: sudo apt-get install <selected package>
</code>```

So I try sudo apt-get install javah and I get

```<code>> sudo apt-get install javah [sudo] password for jess:  Reading package
> lists... Done Building dependency tree        Reading state
> information... Done E: Unable to locate package javah
</code>```

What am I doing wrong? can someone give me some pointers on how to do this? Thanks x

答:
javah is a part of JDK (Java Development Kit).

You can get it here:

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

After installing JDK, you will be able to use javac, javah, and lots more software related to Java development.

If you want to start with sample code, I suggest to go here:

http://jnicookbook.owsiak.org/recipe-No-001/

There, you can find step by step instruction on how to write, compile and run JNI based code. Have fun!

Title: Interfacing C with Java on Linux

Body:
For a project I need to be able to use some C programs through Java. Our teachers have told us we can use minGW but that only seems to work on Windows, and my machine is running Linux (Mint 18).
I saw posts about using javah, but when I attempt to use it, I get the following message

> javah HelloJNI The program 'javah' can be found in the following
> packages:  * gcj-4.8-jdk  * openjdk-7-jdk  * gcj-4.6-jdk  *
> openjdk-6-jdk Try: sudo apt-get install <selected package>

So I try sudo apt-get install javah and I get

> sudo apt-get install javah [sudo] password for jess:  Reading package
> lists... Done Building dependency tree        Reading state
> information... Done E: Unable to locate package javah

What am I doing wrong? can someone give me some pointers on how to do this? Thanks x


问:
Get data cursor callback in Matlab GUI
How can I set the Matlab GUI data cursor callback for a specific GUI axes?
I was able to add the data cursor icon in GUI toolbar. I can selected 3D point on the plotted data, but I need to add more info in the data cursor text and also do some other stuff with the coordinates it is getting.

I tried to follow "How to add additional info to the data cursor?", but doesn't work for GUI.

GUI axes are not figures, so I'm getting this error:

Error using datacursormode (line 149)
Invalid figure handle

I need the same here, but for GUI axes (figures?):

function test_main
% Plots graph and sets up a custom data tip update function
fig = figure('DeleteFcn','doc datacursormode');
X = 0:60;
t = (X)*0.02;
Y = sin(-16*t);
plot(X,Y)
dcm_obj = datacursormode(fig); % tried here "handles.MyFigHandle"
set(dcm_obj,'UpdateFcn',{@myupdatefcn,t})

function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
txt = {['X: ',num2str(pos(1))],...
       ['Y: ',num2str(pos(2))],...
       ['I: ',num2str(I)],...
       ['T: ',num2str(t(I))]};
```

For now I can get only the default datacursor behavior, like this image:

答:
I've not found any difference between the use of the data cursor in a GUI and in a figure.

Re-using part of your code, I've created a GUI in which a checkbox enable / disable the datacursormode.

The GUI contains two axes in which two lines and a 3D surface are plotted respectively.

Also three radiobuttons control the string that will be printed in the textbox generated when the datacursormode is enabled.

The tags of the GUI are the folowing:

left axes: axes_2d

right axes: axes_3d

left pushbutton: pushbutton_2d

right pushbutton: pushbutton_3d

checkbox: checkbox_enable_dc

left radiobutton: radiobutton1

middle radiobutton: radiobutton2

righ radiobutton: radiobutton3

The GUI works this way:

the pushbuttons plot in the axes and enable the checkbox

the checkbox enable / disable the datacursormode

by default, the left radiobutton is selected and sets the default string

the other two radiobutton set a different string

Based on the selected radiobutton, the first line of the string in the textbox will be either:

DEFAULT STRING

STRING OPTION ONE

STRING OPTION TWO

the string to be written in the textbox is created in your myupdatefcn that has been modified to handle the options selected by the radiobutton.

Notice: in order not to limit the modification to your version of the myupdatefcn function, I've hard coded the t array.

This is the .m file of the GUI:

```<code>function varargout = gui_datacursormode(varargin)
% GUI_DATACURSORMODE MATLAB code for gui_datacursormode.fig
%      GUI_DATACURSORMODE, by itself, creates a new GUI_DATACURSORMODE or raises the existing
%      singleton*.
%
%      H = GUI_DATACURSORMODE returns the handle to a new GUI_DATACURSORMODE or the handle to
%      the existing singleton*.
%
%      GUI_DATACURSORMODE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_DATACURSORMODE.M with the given input arguments.
%
%      GUI_DATACURSORMODE('Property','Value',...) creates a new GUI_DATACURSORMODE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before gui_datacursormode_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to gui_datacursormode_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help gui_datacursormode

% Last Modified by GUIDE v2.5 02-Apr-2017 17:45:45

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_datacursormode_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_datacursormode_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_datacursormode is made visible.
function gui_datacursormode_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to gui_datacursormode (see VARARGIN)

% Choose default command line output for gui_datacursormode
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui_datacursormode wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_datacursormode_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton_2d.
function pushbutton_2d_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_2d (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Plot two lines in the first axes
t=0:.1:2*pi;
plot(handles.axes_2d,t,sin(t),'r');
hold(handles.axes_2d,'on')
plot(handles.axes_2d,t,cos(t),'b');
% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';

% --- Executes on button press in pushbutton_3d.
function pushbutton_3d_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_3d (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Plot a 3D graph in the second axes
axes(handles.axes_3d);
peaks

% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';

function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips

% Get the handles of the GUI to access to the radiobuttons
my_guidata=guidata(gcf);
% Define the additional string to be written
if(my_guidata.radiobutton1.Value)
   str='DEFAULT STRING ';
elseif(my_guidata.radiobutton2.Value)
   str='STRING OPTION ONE ';
else
   str='STRING OPTION TWO ';
end

% Get the datacursor data
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
% Create the whole string to be written
txt = {[str], ...
       ['X: ',num2str(pos(1))],...
       ['Y: ',num2str(pos(2))],...
       ['I: ',num2str(I)],...
       ['T: ',num2str(t(I))]}

% --- Executes on button press in checkbox_enable_dc.
function checkbox_enable_dc_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_enable_dc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% If the checkbox is set
if(hObject.Value)
   %  enable the radiobuttons that control the string to be written
   handles.radiobutton1.Enable='on';
   handles.radiobutton1.Value=1;
   handles.radiobutton2.Enable='on';
   handles.radiobutton3.Enable='on';
   % Create the datacursormode object
   dcm_obj = datacursormode(gcf)
   t=rand(1,10000);
   set(dcm_obj,'DisplayStyle','datatip',...
      'SnapToDataVertex','off','Enable','on', ...
      'UpdateFcn',{@myupdatefcn,t})
else
   % If the checkbox is not set, disable the datacursormode
   datacursormode 'off'
end

% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton2.Value=0
handles.radiobutton3.Value=0

% --- Executes on button press in radiobutton1.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton3.Value=0

% --- Executes on button press in radiobutton1.
function radiobutton3_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton2.Value=0
</code>```

Hope this helps,

Qapla'

Title: Get data cursor callback in Matlab GUI

Body:
How can I set the Matlab GUI data cursor callback for a specific GUI axes?
I was able to add the data cursor icon in GUI toolbar. I can selected 3D point on the plotted data, but I need to add more info in the data cursor text and also do some other stuff with the coordinates it is getting.

I tried to follow "How to add additional info to the data cursor?", but doesn't work for GUI.

GUI axes are not figures, so I'm getting this error:

Error using datacursormode (line 149)
Invalid figure handle

I need the same here, but for GUI axes (figures?):

function test_main
% Plots graph and sets up a custom data tip update function
fig = figure('DeleteFcn','doc datacursormode');
X = 0:60;
t = (X)*0.02;
Y = sin(-16*t);
plot(X,Y)
dcm_obj = datacursormode(fig); % tried here "handles.MyFigHandle"
set(dcm_obj,'UpdateFcn',{@myupdatefcn,t})

function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
txt = {['X: ',num2str(pos(1))],...
       ['Y: ',num2str(pos(2))],...
       ['I: ',num2str(I)],...
       ['T: ',num2str(t(I))]};

For now I can get only the default datacursor behavior, like this image:

Body:
I've not found any difference between the use of the data cursor in a GUI and in a figure.

Re-using part of your code, I've created a GUI in which a checkbox enable / disable the datacursormode.

The GUI contains two axes in which two lines and a 3D surface are plotted respectively.

Also three radiobuttons control the string that will be printed in the textbox generated when the datacursormode is enabled.

The tags of the GUI are the folowing:

left axes: axes_2d

right axes: axes_3d

left pushbutton: pushbutton_2d

right pushbutton: pushbutton_3d

checkbox: checkbox_enable_dc

left radiobutton: radiobutton1

middle radiobutton: radiobutton2

righ radiobutton: radiobutton3

The GUI works this way:

the pushbuttons plot in the axes and enable the checkbox

the checkbox enable / disable the datacursormode

by default, the left radiobutton is selected and sets the default string

the other two radiobutton set a different string

Based on the selected radiobutton, the first line of the string in the textbox will be either:

DEFAULT STRING

STRING OPTION ONE

STRING OPTION TWO

the string to be written in the textbox is created in your myupdatefcn that has been modified to handle the options selected by the radiobutton.

Notice: in order not to limit the modification to your version of the myupdatefcn function, I've hard coded the t array.

This is the .m file of the GUI:

function varargout = gui_datacursormode(varargin)
% GUI_DATACURSORMODE MATLAB code for gui_datacursormode.fig
%      GUI_DATACURSORMODE, by itself, creates a new GUI_DATACURSORMODE or raises the existing
%      singleton*.
%
%      H = GUI_DATACURSORMODE returns the handle to a new GUI_DATACURSORMODE or the handle to
%      the existing singleton*.
%
%      GUI_DATACURSORMODE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_DATACURSORMODE.M with the given input arguments.
%
%      GUI_DATACURSORMODE('Property','Value',...) creates a new GUI_DATACURSORMODE or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before gui_datacursormode_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to gui_datacursormode_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help gui_datacursormode

% Last Modified by GUIDE v2.5 02-Apr-2017 17:45:45

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_datacursormode_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_datacursormode_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before gui_datacursormode is made visible.
function gui_datacursormode_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to gui_datacursormode (see VARARGIN)

% Choose default command line output for gui_datacursormode
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes gui_datacursormode wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = gui_datacursormode_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in pushbutton_2d.
function pushbutton_2d_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_2d (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Plot two lines in the first axes
t=0:.1:2*pi;
plot(handles.axes_2d,t,sin(t),'r');
hold(handles.axes_2d,'on')
plot(handles.axes_2d,t,cos(t),'b');
% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';

% --- Executes on button press in pushbutton_3d.
function pushbutton_3d_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_3d (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Plot a 3D graph in the second axes
axes(handles.axes_3d);
peaks

% Enable the checkbox that will set datacorsormode on
handles.checkbox_enable_dc.Enable='on';

function txt = myupdatefcn(~,event_obj,t)
% Customizes text of data tips

% Get the handles of the GUI to access to the radiobuttons
my_guidata=guidata(gcf);
% Define the additional string to be written
if(my_guidata.radiobutton1.Value)
   str='DEFAULT STRING ';
elseif(my_guidata.radiobutton2.Value)
   str='STRING OPTION ONE ';
else
   str='STRING OPTION TWO ';
end

% Get the datacursor data
pos = get(event_obj,'Position');
I = get(event_obj, 'DataIndex');
% Create the whole string to be written
txt = {[str], ...
       ['X: ',num2str(pos(1))],...
       ['Y: ',num2str(pos(2))],...
       ['I: ',num2str(I)],...
       ['T: ',num2str(t(I))]}

% --- Executes on button press in checkbox_enable_dc.
function checkbox_enable_dc_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_enable_dc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% If the checkbox is set
if(hObject.Value)
   %  enable the radiobuttons that control the string to be written
   handles.radiobutton1.Enable='on';
   handles.radiobutton1.Value=1;
   handles.radiobutton2.Enable='on';
   handles.radiobutton3.Enable='on';
   % Create the datacursormode object
   dcm_obj = datacursormode(gcf)
   t=rand(1,10000);
   set(dcm_obj,'DisplayStyle','datatip',...
      'SnapToDataVertex','off','Enable','on', ...
      'UpdateFcn',{@myupdatefcn,t})
else
   % If the checkbox is not set, disable the datacursormode
   datacursormode 'off'
end

% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton2.Value=0
handles.radiobutton3.Value=0

% --- Executes on button press in radiobutton1.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton3.Value=0

% --- Executes on button press in radiobutton1.
function radiobutton3_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton1

% Toggle the other radiobuttons
handles.radiobutton1.Value=0
handles.radiobutton2.Value=0

Hope this helps,

Qapla'


问:
Ruby: Avoiding infinite loop in an array that doubles each number
So there is an infinte loop here, but I'm not seeing it.

```<code># Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers
</code>```

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

答:
Since nobody mentioned the obvious answer, here it is :

```<code>numbers = [1, 2, 3, 4]
double_numbers = []
numbers.each do |number|
  double_numbers << number * 2
end
p double_numbers
# [2, 4, 6, 8]
</code>```

This would be the way to do it if you didn't know about map or map!. Note that you iterate on one array and create another one in order to avoid messing with the each loop.

Body:
So there is an infinte loop here, but I'm not seeing it.

# Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

Body:
Since nobody mentioned the obvious answer, here it is :

numbers = [1, 2, 3, 4]
double_numbers = []
numbers.each do |number|
  double_numbers << number * 2
end
p double_numbers
# [2, 4, 6, 8]

This would be the way to do it if you didn't know about map or map!. Note that you iterate on one array and create another one in order to avoid messing with the each loop.


问:
MonoDevelop Addon-ons like Eclipse
Are there refactoring and other addons for MonoDevelop like there are for Eclipse and Visual Studio, there does not appear to be an ecosystem of addons to help development.</p>

答: As of now, there aren't third party refactoring add-ins for MonoDevelop. However, the IDE itself includes many refactoring operations and coding helpers, so maybe you'll find what you need without having to use an add-in.</p>

Title: MonoDevelop Addon-ons like Eclipse


问:
Call webpack bundled function/class from console.log
Is it possible to access the exported modules(ES6->ES5 compiled) from web inspector console? They are bundled together using webpack

I am trying to call Session.setSessionInLocalStorage('test key', 'test object');

/******/ (function(modules) { // webpackBootstrap
/******/  // The module cache
/******/  var installedModules = {};
/******/
/******/  // The require function
/******/  function __webpack_require__(moduleId) {
/******/
/******/   // Check if module is in cache
/******/   if(installedModules[moduleId])
/******/    return installedModules[moduleId].exports;
/******/
/******/   // Create a new module (and put it into the cache)
/******/   var module = installedModules[moduleId] = {
/******/    exports: {},
/******/    id: moduleId,
/******/    loaded: false
/******/   };
/******/
/******/   // Execute the module function
/******/   modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/   // Flag the module as loaded
/******/   module.loaded = true;
/******/
/******/   // Return the exports of the module
/******/   return module.exports;
/******/  }
/******/
/******/
/******/  // expose the modules object (__webpack_modules__)
/******/  __webpack_require__.m = modules;
/******/
/******/  // expose the module cache
/******/  __webpack_require__.c = installedModules;
/******/
/******/  // __webpack_public_path__
/******/  __webpack_require__.p = "";
/******/
/******/  // Load entry module and return exports
/******/  return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!*********************!*\
  !*** ./app/main.js ***!
  \*********************/
/***/ function(module, exports, __webpack_require__) {

 'use strict';

 var _CoreUtils = __webpack_require__(/*! ./Core/utils/session/Core.utils.Session */ 4);

 var mySession = new _CoreUtils.Session();

 mySession.setSessionInLocalStorage('key', 'my object');

/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */
/*!******************************************************!*\
  !*** ./app/Core/utils/session/Core.utils.Session.js ***!
  \******************************************************/
/***/ function(module, exports) {

 "use strict";

 Object.defineProperty(exports, "__esModule", {
     value: true
 });

 var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

 var Session = function () {
     function Session(sessionId) {
         _classCallCheck(this, Session);

         this.sessionId = sessionId;
     }

     _createClass(Session, [{
         key: "getSessionFromLocalStorage",
         value: function getSessionFromLocalStorage(sessionKey) {
             return localStorage.getItem(sessionKey);
         }
     }, {
         key: "setSessionInLocalStorage",
         value: function setSessionInLocalStorage(sessionKey, sessionData) {
             localStorage.setItem(sessionKey, JSON.stringify(sessionData));
         }
     }]);

     return Session;
 }();

 exports.Session = Session;

/***/ }
/******/ ]);
//# sourceMappingURL=app.js.map```

答:
If you don't want to add special code to your app. You can follow these steps:

Place a breakpoint where you use the service/class that you later wish to   debug

In the console, save it on the window for example window.myService = this.props.myService

Use the saved reference on the window


问:
Recorded the live streaming video in portrait mode but in youtube in browser displayed landscape mode
I successfully integrate the live streaming video in my application. I recorded the live stream video in portrait mode. but the live streaming video displayed in you tube landscape How to solve this issue?

Please see the below link

https://www.youtube.com/watch?v=aXv5fKY8AFM

答:
Based from this documentation, if you want to force the video to landscape mode, you need to add the screenOrientation flag inside your Activity in the AndroidManifest.xml file:

```<code><activity
  android:name=".SampleActivity"
  android:screenOrientation="landscape">
</activity>
</code>```

Hope this helps!

Body:
Based from this documentation, if you want to force the video to landscape mode, you need to add the screenOrientation flag inside your Activity in the AndroidManifest.xml file:

<activity
  android:name=".SampleActivity"
  android:screenOrientation="landscape">
</activity>

Hope this helps!


问:
XAML Master / Template pages with MVVM
Is there a way to create master / template pages in XAML (for UWP applications)?

The problem I'm trying to solve:

I have an application with a lot of similar sites, where only the content changes slightly but not the Buttons and the Layout. Example:

```<code><Page
    DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Text="Edit Webpage" Style="{StaticResource BigTexBlock}" />
            <ScrollViewer  Style="{StaticResource ContentScrollViewer}" Grid.Row="1" VerticalScrollMode="Enabled">
                <StackPanel Margin="10,0">
                    <webpage:EditWebpage DataContext="{Binding }" />
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>
                <!-- more buttons -->
                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>
</code>```

Only three parts of this template will change; the ViewModel in the DataContext, the Text of the TextBlock, and the UserControl which contains the editable fields.

As this is an application with a lot of CRUD happening with simple Entities the amount of code to be repeated over and over again is a lot if I keep "solving" the problem like this. In the separated business logic I could avoid this problem with inheritance, but I'm struggling to find a elegant solution in XAML.

Is there a way to refactor this so I may have a "Template Page"?

I like how for example twig has solved this problem: http://twig.sensiolabs.org/. You define a master/template page and override parts of it in the children templates.

Important to me is that

I don't break the MVVM pattern.

I don't want to hide/show UserControls in one "Main" XAML as the amount of different entities may become quite large

I want navigation happening between the pages that the user sees the expected animations, and it does not break the separated view code I already have

答:
There isn't a master page or template mechanism that other technologies, like MVC, have. But you can use frames and navigation to do what you're looking for.

You could keep the page defined the way you currently have it. All of the fixed elements on the page are in the layout. Now instead of using a UserControl for your specific edit UI, replace that with a frame.

```<code><StackPanel Margin="10,0">
    <Frame Name="EditFrame" DataContext="{Binding }" />
</StackPanel>
</code>```

Now when you navigate to the Main Edit page, also pass the type for the view you want in the frame. Then on your OnNavigatedTo override for the main page, you can navigate the frame to the view type as the parameter.

You can also use the EditFrame to page through multiple editing pages, like if you had a wizard UI with Next and Previous buttons, without leaving the main page.

You can either do this in your OnNavigatedTo method or modify your NavigationService to be able to handle this behavior.

Title: XAML Master / Template pages with MVVM

Body:
Is there a way to create master / template pages in XAML (for UWP applications)?

The problem I'm trying to solve:

I have an application with a lot of similar sites, where only the content changes slightly but not the Buttons and the Layout. Example:

<Page
    DataContext="{Binding WebpageViewModel, Source={StaticResource Locator}}">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Text="Edit Webpage" Style="{StaticResource BigTexBlock}" />
            <ScrollViewer  Style="{StaticResource ContentScrollViewer}" Grid.Row="1" VerticalScrollMode="Enabled">
                <StackPanel Margin="10,0">
                    <webpage:EditWebpage DataContext="{Binding }" />
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Grid>

    <Page.BottomAppBar>
        <CommandBar>
            <CommandBar.PrimaryCommands>

                <AppBarButton IsCompact="True" Command="{Binding SaveEntryCommand}" Icon="Save" Label="Save" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
</Page>

Only three parts of this template will change; the ViewModel in the DataContext, the Text of the TextBlock, and the UserControl which contains the editable fields.

As this is an application with a lot of CRUD happening with simple Entities the amount of code to be repeated over and over again is a lot if I keep "solving" the problem like this. In the separated business logic I could avoid this problem with inheritance, but I'm struggling to find a elegant solution in XAML.

Is there a way to refactor this so I may have a "Template Page"?

I like how for example twig has solved this problem: http://twig.sensiolabs.org/. You define a master/template page and override parts of it in the children templates.

Important to me is that

I don't break the MVVM pattern.

I don't want to hide/show UserControls in one "Main" XAML as the amount of different entities may become quite large

I want navigation happening between the pages that the user sees the expected animations, and it does not break the separated view code I already have

Body:
There isn't a master page or template mechanism that other technologies, like MVC, have. But you can use frames and navigation to do what you're looking for.

You could keep the page defined the way you currently have it. All of the fixed elements on the page are in the layout. Now instead of using a UserControl for your specific edit UI, replace that with a frame.

<StackPanel Margin="10,0">
    <Frame Name="EditFrame" DataContext="{Binding }" />
</StackPanel>

Now when you navigate to the Main Edit page, also pass the type for the view you want in the frame. Then on your OnNavigatedTo override for the main page, you can navigate the frame to the view type as the parameter.

You can also use the EditFrame to page through multiple editing pages, like if you had a wizard UI with Next and Previous buttons, without leaving the main page.

You can either do this in your OnNavigatedTo method or modify your NavigationService to be able to handle this behavior.


问:
Why does NewStaticCredentials return a blank Credentials object?
I am trying to read S3 objects in Account A from Account B.

I am able to assume a role in Account B and retrieve sts.Credentials object.

```<code>stsClient := sts.New(session.Must(session.NewSession()))
params := &sts.AssumeRoleInput{
    RoleArn:         aws.String(roleArn),
    RoleSessionName: aws.String("role-session-name"),
}
stsResp, err := stsClient.AssumeRole(params)
checkErr(err)
// stsResp.Credentials.AccessKeyId     = ASIA...
// stsResp.Credentials.SecretAccessKey = abc...
// stsResp.Credentials.SessionToken    = xyz...
</code>```

I then have to convert sts.Credentials object to a credentials.Credentials object in order to use it in

```<code>s3Client := s3.New(session.Must(session.NewSession()), &aws.Config{Credentials: creds})
</code>```

However, when I do:

```<code>creds := credentials.NewStaticCredentials(*stsResp.Credentials.AccessKeyId, *stsResp.Credentials.SecretAccessKey, *stsResp.Credentials.SessionToken)
</code>```

creds for some reason is a pointer to an empty credentials.Credentials object:

```<code>&{creds:{AccessKeyID: SecretAccessKey: SessionToken: ProviderName:} forceRefresh:true m:{state:0 sema:0} provider:0xc4201a2840}
</code>```

I have also tried:

```<code>values, err := creds.Get()
checkErr(err)
fmt.Println(values) // prints out credentials values as expected
</code>```

So, it's not quite clear to me why credentials.NewStaticCredentials() returns an empty credentials object.

答:
When printing out the credentials.Credentials value returned by credentials.NewStaticCredentials() the creds value you see printed is the cached AWS credentials stored in the Credentials type that has not been populated yet. This field is populated when Credentials.Get is called. The value is invalid prior to Get being called.

The NewStaticCredentials will create a StaticProvider value which satisfies the Provider interface. The Credentials type will use the Provider.Retrieve() method to retrieve the latest credential Values from the Provider. The Credentials type will cache the creds response from Retrieve() until the Provider flags the credentials as expired. In the case of StaticProvider the credentials never expire.

This is why creds.Get() returns the values without an error. If you were to print creds after Get was called you'd see the cached static values in the Credentials type.

Body:
I am trying to read S3 objects in Account A from Account B.

I am able to assume a role in Account B and retrieve sts.Credentials object.

stsClient := sts.New(session.Must(session.NewSession()))
params := &sts.AssumeRoleInput{
    RoleArn:         aws.String(roleArn),
    RoleSessionName: aws.String("role-session-name"),
}
stsResp, err := stsClient.AssumeRole(params)
checkErr(err)
// stsResp.Credentials.AccessKeyId     = ASIA...
// stsResp.Credentials.SecretAccessKey = abc...
// stsResp.Credentials.SessionToken    = xyz...

I then have to convert sts.Credentials object to a credentials.Credentials object in order to use it in

s3Client := s3.New(session.Must(session.NewSession()), &aws.Config{Credentials: creds})

However, when I do:

creds := credentials.NewStaticCredentials(*stsResp.Credentials.AccessKeyId, *stsResp.Credentials.SecretAccessKey, *stsResp.Credentials.SessionToken)

creds for some reason is a pointer to an empty credentials.Credentials object:

&{creds:{AccessKeyID: SecretAccessKey: SessionToken: ProviderName:} forceRefresh:true m:{state:0 sema:0} provider:0xc4201a2840}

I have also tried:

values, err := creds.Get()
checkErr(err)
fmt.Println(values) // prints out credentials values as expected

So, it's not quite clear to me why credentials.NewStaticCredentials() returns an empty credentials object.


问:
Delete files contained in repeated directory locations
I'm looking for a way to script a repeating deletion task. We have a standard directory template which is used repeatedly with the top level renamed. I want to target a named folder in all these directories to delete the files e.g.

```<code>wxyz\TemporaryFiles
acbd\TemporaryFiles
</code>```

etc. I have tried the following:

```<code>for /d %%i in (X:\Company\Projects\*) do cd TemporaryFiles && del /f /s /q %%i\*.*
</code>```

I must have my syntax wrong and would appreciate some help - thanks.

答:
The main problem in your code is that once the cd is executed, as it is not reverted, the rest of the cd operations are executed in a wrong place.

Try with

for /d %%i in ("X:\Company\Projects\*") do (
    pushd "%%~fi\TemporaryFiles" && (
        rmdir . /s /q
        popd
    )
)
```

That is, for each folder inside Projects folder, change current active directory to the folder found + subfolder TemporaryFiles and remove anything inside. Once done, revert the directory change and continue with the next folder

Body:
I'm looking for a way to script a repeating deletion task. We have a standard directory template which is used repeatedly with the top level renamed. I want to target a named folder in all these directories to delete the files e.g.

wxyz\TemporaryFiles
acbd\TemporaryFiles

etc. I have tried the following:

for /d %%i in (X:\Company\Projects\*) do cd TemporaryFiles && del /f /s /q %%i\*.*

I must have my syntax wrong and would appreciate some help - thanks.

Body:
The main problem in your code is that once the cd is executed, as it is not reverted, the rest of the cd operations are executed in a wrong place.

Try with

for /d %%i in ("X:\Company\Projects\*") do (
    pushd "%%~fi\TemporaryFiles" && (
        rmdir . /s /q
        popd
    )
)

That is, for each folder inside Projects folder, change current active directory to the folder found + subfolder TemporaryFiles and remove anything inside. Once done, revert the directory change and continue with the next folder


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
To wait 10 seconds:</p>

```<code>choice /T 10 /C X /D X /N
</code>```

Title: Windows batch: sleep

Body:
To wait 10 seconds:

choice /T 10 /C X /D X /N


问:
JUnit 5: How to assert an exception is thrown?
Is there a better way to assert that a method throws an exception in JUnit 5?

Currently, I have to use an @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.

答:
They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:</p>

```<code>@Test
public void wrongInput() {
    Throwable exception = assertThrows(InvalidArgumentException.class,
            ()->{objectName.yourMethod("WRONG");} );
}
</code>```

Body:
They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:

@Test
public void wrongInput() {
    Throwable exception = assertThrows(InvalidArgumentException.class,
            ()->{objectName.yourMethod("WRONG");} );
}