问:
Angular2: Use Pipe to render templates dynamically
I am creating a form where I get the  fields from the backend. After mapping, I have something like this:

```<code>genericFilters: {
        iboId: {
            'display': false,
            'template': ''
        },
        iboCode: {
            'display': true,
            'template': 'text_input_iboCode',
            /*'template': 'text/iboCode'*/
        },
        iboName: {
            'display': true,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': true,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'multiselect_iboRank',
            /*'template': 'select/multi_iboRank',*/
        },
        iboEmail: {
            'display': false,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': true,
            'template': 'simple_select_iboNewsletter',
            /*'template': 'select/simple_iboNewsletter',*/
        },
    };
</code>```

My idea behind this is to create each field type (checkbox, multiselect, text, radio, etc.) for the form field at an app level. And use the mapped JSON above to apply a certain field type to every receieved field from the back end.

In my example, the field iboId should have the field type <text_input_iboCode>.

So, in my view, I don't want to have something like this:

```<code><text_input_iboCode></text_input_iboCode>
<text_input_iboName></text_input_iboName>
<text_input_iboSurname></text_input_iboSurname>
</code>```

I would actually like to have the form creation more abstract, something like this:

```<code><div *ngFor="let field of genericFilters | dynamicTemplateProcessorPipe">
    {{field.template}} <!--This should equal '<text_input_iboName>' for example-->
</div>
</code>```

Questions:

Am I asking for the moon? Is this even possible? Are there other or better approaches to achieve this? Am I abusing the @Pipe functionality?

I am actually using @Pipe for translations, formatting, looping through objects in templates, etc. I guessed I could also use them to return a <fieldTemplate>.

I will start a research to see if the usage of <ng-template #fieldTemplate> could also be a viable option, in the meanwhile I hope someone could lay some light on the doability of this functionality with @Pipe.

答:
After continuing my research I could not find out a way of implementing what I want with @Pipe, and for a good reason: @Pipe is not meant to work like that.

I found instead Angular 4's NgComponentOutlet.

I am starting to work with it, but my first example would be something like this:

```<code>@Component({selector: 'text-input-ibo-name', template: '<input type="text" name="ibo_name">'})
class TextIboName {
}
@Component({
  selector: 'ng-my-form',
  template: `<ng-container *ngComponentOutlet="TextIboName"></ng-container>`
})
class NgMyForm {
  // This field is necessary to expose HelloWorld to the template.
  TextIboName = TextIboName;
}
</code>```

This is the basis. Now I just need to see how to apply <ng-container *ngComponentOutlet="TextIboName"></ng-container> in my *ngFor (see OP).

If people request it, I can update this answer with more concrete and 'final' code.

Update:

This would be my first approach to select the template for that field that is declared on the mapped JSON.

```<code><div *ngFor="let field of genericFilters | dynamicTemplateProcessorPipe">
    <ng-container *ngComponentOutlet="{{field.template}}"></ng-container>
</div>
</code>```

The classes TextIboName, TextIboCode, TextIboSurname, etc. Will be declared in a common folder and imported to the current component, just to have a more abstract approach.

The goal is to be able to reuse these fields throughout all the App. Like this, I will be able to replicate the field TextIboName in other places without having to Copy/Paste HTML code or templates.

Update 2:

If we move our 'field component', in my example would be TextIboName to an external folder within another @ngModule or we simply want to use an external class from another @ngModule we will have to use NgModuleFactory.

Adapted above code:

```<code>@Component({
  selector: 'ng-my-form',
  template: `
    <ng-container *ngComponentOutlet="TextIboName;
                                      ngModuleFactory: myModule;"></ng-container>`
})
class NgMyForm {
  // This field is necessary to expose OtherModuleComponent to the template.
  TextIboName = TextIboName;
  myModule: NgModuleFactory<any>;
  constructor(compiler: Compiler) { this.myModule = compiler.compileModuleSync(OtherModule); }
}
</code>```

Body:
I am creating a form where I get the  fields from the backend. After mapping, I have something like this:

genericFilters: {
        iboId: {
            'display': false,
            'template': ''
        },
        iboCode: {
            'display': true,
            'template': 'text_input_iboCode',
            /*'template': 'text/iboCode'*/
        },
        iboName: {
            'display': true,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': true,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'multiselect_iboRank',
            /*'template': 'select/multi_iboRank',*/
        },
        iboEmail: {
            'display': false,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': true,
            'template': 'simple_select_iboNewsletter',
            /*'template': 'select/simple_iboNewsletter',*/
        },
    };

My idea behind this is to create each field type (checkbox, multiselect, text, radio, etc.) for the form field at an app level. And use the mapped JSON above to apply a certain field type to every receieved field from the back end.

In my example, the field iboId should have the field type <text_input_iboCode>.

So, in my view, I don't want to have something like this:

<text_input_iboCode></text_input_iboCode>
<text_input_iboName></text_input_iboName>
<text_input_iboSurname></text_input_iboSurname>

I would actually like to have the form creation more abstract, something like this:

    {{field.template}}

Questions:

Am I asking for the moon? Is this even possible? Are there other or better approaches to achieve this? Am I abusing the @Pipe functionality?

I am actually using @Pipe for translations, formatting, looping through objects in templates, etc. I guessed I could also use them to return a <fieldTemplate>.

I will start a research to see if the usage of <ng-template #fieldTemplate> could also be a viable option, in the meanwhile I hope someone could lay some light on the doability of this functionality with @Pipe.

Body:
After continuing my research I could not find out a way of implementing what I want with @Pipe, and for a good reason: @Pipe is not meant to work like that.

I found instead Angular 4's NgComponentOutlet.

I am starting to work with it, but my first example would be something like this:

@Component({selector: 'text-input-ibo-name', template: '<input type="text" name="ibo_name">'})
class TextIboName {
}
@Component({
  selector: 'ng-my-form',
  template: `<ng-container *ngComponentOutlet="TextIboName"></ng-container>`
})
class NgMyForm {
  // This field is necessary to expose HelloWorld to the template.
  TextIboName = TextIboName;
}

This is the basis. Now I just need to see how to apply <ng-container *ngComponentOutlet="TextIboName"></ng-container> in my *ngFor (see OP).

If people request it, I can update this answer with more concrete and 'final' code.

Update:

This would be my first approach to select the template for that field that is declared on the mapped JSON.

<div *ngFor="let field of genericFilters | dynamicTemplateProcessorPipe">
    <ng-container *ngComponentOutlet="{{field.template}}"></ng-container>
</div>

The classes TextIboName, TextIboCode, TextIboSurname, etc. Will be declared in a common folder and imported to the current component, just to have a more abstract approach.

The goal is to be able to reuse these fields throughout all the App. Like this, I will be able to replicate the field TextIboName in other places without having to Copy/Paste HTML code or templates.

Update 2:

If we move our 'field component', in my example would be TextIboName to an external folder within another @ngModule or we simply want to use an external class from another @ngModule we will have to use NgModuleFactory.

Adapted above code:

@Component({
  selector: 'ng-my-form',
  template: `
    <ng-container *ngComponentOutlet="TextIboName;
                                      ngModuleFactory: myModule;"></ng-container>`
})
class NgMyForm {
  // This field is necessary to expose OtherModuleComponent to the template.
  TextIboName = TextIboName;
  myModule: NgModuleFactory<any>;
  constructor(compiler: Compiler) { this.myModule = compiler.compileModuleSync(OtherModule); }
}


来源: stackexchange

问:
Input string was not in a correct format , with form 1 and 2
why it says

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Here is my Code

```<code> public  int transCode = 0;

        con.Open();
        cmd = new SqlCommand("SELECT MAX(TransactionCode) FROM TRANSACTIONS",con);
        rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
           transCode = Convert.ToInt32(rdr[0].ToString()); // Here is the     line where the problem go
        }

        con.Close();
</code>```

答: This exception means that the value that is being returned by the Reader is not convertible to an Int32.  You may have a NULL, or a non-integer TransactionCode value.  Try examining the value in a debugger to see what the value actually looks like, or reconsider whether or not it will always be an Int32 value.

ContentLicense: CC BY-SA 3.0

Body:
why it says

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Here is my Code

 public  int transCode = 0;

        con.Open();
        cmd = new SqlCommand("SELECT MAX(TransactionCode) FROM TRANSACTIONS",con);
        rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
           transCode = Convert.ToInt32(rdr[0].ToString()); // Here is the     line where the problem go
        }

        con.Close();


问:
Dynamic event template in FullCalendar
Is there any way to dynamically change event template in FullCalendar?

Update. What I want is to specify new event html (e. g. in eventRender callback) and make FullCalendar to use it for my event rendering. Something like this:

```<code>eventRender: function(event, element, view) {
  var template = '<div class="customEvent"></div>';
  return $.parse(template);
}
</code>```

Tried the sample above - didn't work.

答:
You may append new information like this  </p>

```<code>eventRender: function( event, element, view ) {
       element.find('.fc-title').append('<span class="yourCSS"></span> ');
}
</code>```

Title: Dynamic event template in FullCalendar

Body:
Is there any way to dynamically change event template in FullCalendar?

Update. What I want is to specify new event html (e. g. in eventRender callback) and make FullCalendar to use it for my event rendering. Something like this:

eventRender: function(event, element, view) {
  var template = '

';
  return $.parse(template);
}

Tried the sample above - didn't work.

Body:
You may append new information like this

eventRender: function( event, element, view ) {
       element.find('.fc-title').append('<span class="yourCSS"></span> ');
}


问:
Set Button icon using attached file
I'm creating a kind of template for users to fill out in Adobe Acrobat Pro X, but they also need to attach photos. I've created a button based on this thread here which, when clicked, prompts the user to select a file and then attaches the file to the PDF. It works beautifully, except the template pdf has multiple pages with multiple locations for photos.

I need a way to keep track of which (picture) attachment belongs to which location. My main idea so far is to simply insert code that will take the file and use it as the button's icon. (This is also good in the case where the user accidentally attaches the wrong file, then goes and uploads the right one without deleting the old one; I'll see the most recent choice and assume it's the correct one).

The other idea would be to rename the files as they get attached (to Attachment1, etc.) but this doesn't seem to be as feasible.

There are 2 different functions for the button depending on if the users are using Reader 11 or not.

When they are not using Reader, the main code looks like this:

```<code>app.alert({
        cMsg: "Please select a file to attach.",
        cTitle: "Attach File",
        nIcon: 3,
        nType: 0
    });

    try {

        var rc = this.importDataObject("Attachment" + attachment_num);
        if (rc) {
            attachment_num += 1;
            app.alert({
                cMsg: "Attachment successful.",
                cTitle: "Attachment Successful",
                nIcon: 3,
                nType: 0
            });
</code>```

I was thinking as the first line of the if statement, I could insert code to change the icon of the button that this code is running from, but I can't figure out the right thing to try. I was looking at using buttonSetIcon based on here but I'm doing something wrong, probably because of my lack of JavaScript knowledge.

What I was trying was something along the lines of this

```<code>var f = this.getField("ImageButton");
f.buttonSetIcon(rc);
</code>```

It doesn't work though. I am not sure what exactly importDataObject returns in the variable rc but I was hoping it would be the file itself.

When the user is using Reader 11, this gets even more confusing because everything seems to just be one line of code, annot.cAttachmentPath;, but I'll focus on the other version first.

Any ideas?

答:
Put the following line of code in the Mouse Up action of the button.

```<code>event.target.buttonImportIcon();
</code>```

This will open a file selection dialog where the user can select the image to import and set it as the "normal" button icon. It will import the icon into the button that was pressed so you can use it for multiple buttons.

Note that in Reader, the image will need to be converted to PDF first. In Acrobat, the conversion will be automatic.

If you need a way to add images (as images) to Reader and you can tolerate the user positioning them manually, you can simply paste the image from the clipboard and it will show up in the PDF as a stamp. You need to instruct the user on how to get the image onto the clipboard though. Then they need to scale and position the image.

Title: Set Button icon using attached file

Body:
I'm creating a kind of template for users to fill out in Adobe Acrobat Pro X, but they also need to attach photos. I've created a button based on this thread here which, when clicked, prompts the user to select a file and then attaches the file to the PDF. It works beautifully, except the template pdf has multiple pages with multiple locations for photos.

I need a way to keep track of which (picture) attachment belongs to which location. My main idea so far is to simply insert code that will take the file and use it as the button's icon. (This is also good in the case where the user accidentally attaches the wrong file, then goes and uploads the right one without deleting the old one; I'll see the most recent choice and assume it's the correct one).

The other idea would be to rename the files as they get attached (to Attachment1, etc.) but this doesn't seem to be as feasible.

There are 2 different functions for the button depending on if the users are using Reader 11 or not.

When they are not using Reader, the main code looks like this:

app.alert({
        cMsg: "Please select a file to attach.",
        cTitle: "Attach File",
        nIcon: 3,
        nType: 0
    });

    try {

        var rc = this.importDataObject("Attachment" + attachment_num);
        if (rc) {
            attachment_num += 1;
            app.alert({
                cMsg: "Attachment successful.",
                cTitle: "Attachment Successful",
                nIcon: 3,
                nType: 0
            });

I was thinking as the first line of the if statement, I could insert code to change the icon of the button that this code is running from, but I can't figure out the right thing to try. I was looking at using buttonSetIcon based on here but I'm doing something wrong, probably because of my lack of JavaScript knowledge.

What I was trying was something along the lines of this

var f = this.getField("ImageButton");
f.buttonSetIcon(rc);

It doesn't work though. I am not sure what exactly importDataObject returns in the variable rc but I was hoping it would be the file itself.

When the user is using Reader 11, this gets even more confusing because everything seems to just be one line of code, annot.cAttachmentPath;, but I'll focus on the other version first.

Any ideas?

Body:
Put the following line of code in the Mouse Up action of the button.

event.target.buttonImportIcon();

This will open a file selection dialog where the user can select the image to import and set it as the "normal" button icon. It will import the icon into the button that was pressed so you can use it for multiple buttons.

Note that in Reader, the image will need to be converted to PDF first. In Acrobat, the conversion will be automatic.

If you need a way to add images (as images) to Reader and you can tolerate the user positioning them manually, you can simply paste the image from the clipboard and it will show up in the PDF as a stamp. You need to instruct the user on how to get the image onto the clipboard though. Then they need to scale and position the image.


问:
scikit-image pixel by pixel manipulation
I need to read an image and then perform a function on each pixel, and then save it as a new image. I use scikit-image for the first and last part (reading and writing) but I'm having trouble doing the second operation (the actual conversion) in a fast way.

The result of the read operation in scikit-image is a numpy array of the shape (WIDTH, HEIGHT, N_CHANNELS) where WIDTH and HEIGHT is of the image and N_CHANNELS is either 3 or 4. I need to apply a function such as one that converts the pixel from [R, G, B] to [R - B, G - B, B - R] to each pixel individually.

I've spend a few days trying to get this working, but the only working solution that I have so far is to loop over each row and column and perform the calculation. This takes an extremely long time to complete.

I've tried to vectorize the array but the result is a 1D array and it isn't possible to work with that. Is there any other performant way to get this done?

```<code>def calculate_ndvi(nir, red):
    if red == 0 and nir == 0:
        return 0.5
    else:
        num = int(nir) - int(red)
        den = int(nir) + int(red)
        return num / den

zero_uint = numpy.uint8(0)

def process_color(clr):
    ndvi = calculate_ndvi(clr[2], clr[0])
    return [-ndvi, ndvi, zero_uint]

def save_ndvi_file():
    image = io.imread(input_path)

    rows = image.shape[0]
    cols = image.shape[1]

    out = numpy.empty(shape=(rows, cols, 3))
    for i in range(rows):
        for j in range(cols):
            out[i][j] = process_color(image[i][j])

    io.imsave('output.jpg', out)
</code>```

答:
You can vectorize this by using multi-dimensional broadcasting of operations. Here is a version of your function that does everything in a vectorized manner:

```<code>def save_ndvi_file():
    image = io.imread(input_path)

    nir = image[:, :, 2]
    red = image[:, :, 0]
    ndvi = (nir - red) / (nir + red)
    ndvi[(nir == 0) & (red == 0)] = 0.5
    out = ndvi[:, :, np.newaxis] * np.array([[[-1, 1, 0]]])

    io.imsave('output.jpg', out)
</code>```

Notice that all the things you had looped over are now done via broadcasted numpy operations, rather than by looping over external function calls. Writing code this way requires a slightly different way of thinking about the algorithm, but it is quite intuitive once you're used to it.

Body:
I need to read an image and then perform a function on each pixel, and then save it as a new image. I use scikit-image for the first and last part (reading and writing) but I'm having trouble doing the second operation (the actual conversion) in a fast way.

The result of the read operation in scikit-image is a numpy array of the shape (WIDTH, HEIGHT, N_CHANNELS) where WIDTH and HEIGHT is of the image and N_CHANNELS is either 3 or 4. I need to apply a function such as one that converts the pixel from [R, G, B] to [R - B, G - B, B - R] to each pixel individually.

I've spend a few days trying to get this working, but the only working solution that I have so far is to loop over each row and column and perform the calculation. This takes an extremely long time to complete.

I've tried to vectorize the array but the result is a 1D array and it isn't possible to work with that. Is there any other performant way to get this done?

def calculate_ndvi(nir, red):
    if red == 0 and nir == 0:
        return 0.5
    else:
        num = int(nir) - int(red)
        den = int(nir) + int(red)
        return num / den

zero_uint = numpy.uint8(0)

def process_color(clr):
    ndvi = calculate_ndvi(clr[2], clr[0])
    return [-ndvi, ndvi, zero_uint]

def save_ndvi_file():
    image = io.imread(input_path)

    rows = image.shape[0]
    cols = image.shape[1]

    out = numpy.empty(shape=(rows, cols, 3))
    for i in range(rows):
        for j in range(cols):
            out[i][j] = process_color(image[i][j])

    io.imsave('output.jpg', out)

Body:
You can vectorize this by using multi-dimensional broadcasting of operations. Here is a version of your function that does everything in a vectorized manner:

def save_ndvi_file():
    image = io.imread(input_path)

    nir = image[:, :, 2]
    red = image[:, :, 0]
    ndvi = (nir - red) / (nir + red)
    ndvi[(nir == 0) & (red == 0)] = 0.5
    out = ndvi[:, :, np.newaxis] * np.array([[[-1, 1, 0]]])

    io.imsave('output.jpg', out)

Notice that all the things you had looped over are now done via broadcasted numpy operations, rather than by looping over external function calls. Writing code this way requires a slightly different way of thinking about the algorithm, but it is quite intuitive once you're used to it.


问:
Bootstrap navbar width issue
I have annoying problem in my bootstrap menu, when I added " navbar Form" in the menu the width of the menu become larger than the width of the screen in mobile mode (when I decrease browser width for example, or when I open the page on the mobile). Knowing that the issue disappear whenever I remove the form code.
See my code:

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

          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">

                    <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">

        </form>

```

What Should I do?

答:
We would need to see the rest of the DOM for the nav bar that you used to fully know the issue, but you can try this, it should work:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

Link (current)

Link

          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">

              <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">

          </form>

```

Title: Bootstrap navbar width issue

Body:
I have annoying problem in my bootstrap menu, when I added " navbar Form" in the menu the width of the menu become larger than the width of the screen in mobile mode (when I decrease browser width for example, or when I open the page on the mobile). Knowing that the issue disappear whenever I remove the form code.
See my code:

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

          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">

                    <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">

        </form>

What Should I do?

Body:
We would need to see the rest of the DOM for the nav bar that you used to fully know the issue, but you can try this, it should work:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li>
          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">
            <div class="input-group">
              <div class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-search" style="font-size:large"></span></div>
              <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">
            </div>
          </form>
        </li>
      </ul>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container-fluid -->
</nav>


问:
Null-Conditional Operator

var a = b?.c.d;

Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding usage of this operator in an expression spreads viral.

But neither Visual Studio 2015 nor Resharper says anything to me, am I missing something here?

答:
```<code>var a = b == null ? null : b.c.d
</code>```

This is what that statement would look like in the old way, the ?. operator doesn't look deeper when what is before it is null, it just returns null, you WILL however get an error where b is defined but b.c == null since you didn't write as var a = b?.c?.d.

Title: Null-Conditional Operator

Body:
var a = b == null ? null : b.c.d

This is what that statement would look like in the old way, the ?. operator doesn't look deeper when what is before it is null, it just returns null, you WILL however get an error where b is defined but b.c == null since you didn't write as var a = b?.c?.d.


问:
failed to open stream: Permission denied in /opt/lampp/htdocs
I am using Ubuntu 16.04 & xampp 5.6.30.  I am trying to create a simple login program using file with validation but I am facing problem while putting my data into a file named "login.txt".

Error:

```<code>file_put_contents(login.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.php on line 38
</code>```

My code:

```<code>$input = $userName.'|'.$userPassword.'\n';

$myfile = file_put_contents('login.txt', $input.PHP_EOL , FILE_APPEND | LOCK_EX);
</code>```

答:
I would recommend two things. Firstly, define the full path to your login.txt file.

```<code>$input = $userName.'|'.$userPassword.'\n';

$loginFile = "/opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.txt"

$myfile = file_put_contents($loginFile, $input.PHP_EOL , FILE_APPEND | LOCK_EX);
</code>```

Secondly, the directly you are trying to write to:

```<code>/opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/
</code>```

Is not writable. Check what user the web server is running as and give that user read/write permissions to that folder.

Body:
I am using Ubuntu 16.04 & xampp 5.6.30.  I am trying to create a simple login program using file with validation but I am facing problem while putting my data into a file named "login.txt".

Error:

file_put_contents(login.txt): failed to open stream: Permission denied in /opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.php on line 38

My code:

$input = $userName.'|'.$userPassword.'\n';

$myfile = file_put_contents('login.txt', $input.PHP_EOL , FILE_APPEND | LOCK_EX);

Body:
I would recommend two things. Firstly, define the full path to your login.txt file.

$input = $userName.'|'.$userPassword.'\n';

$loginFile = "/opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/login.txt"

$myfile = file_put_contents($loginFile, $input.PHP_EOL , FILE_APPEND | LOCK_EX);

Secondly, the directly you are trying to write to:

/opt/lampp/htdocs/PHP/Practice/PHP Functions/Login Validation/

Is not writable. Check what user the web server is running as and give that user read/write permissions to that folder.


问:
gridview with more than one data source
I have the following case::

Before:

one Grid view ,,this grid view has two object data sources , bind each one of these sources in two separate states in my business logic.. every thing is okay..

After: i have to add one more column to my Grid view this column belongs to the first object data source but does not exist as a property in the second data source..

what i wanna is to do is ::using the same grid view with the two data sources instead of create another grid view with the same fields except the last added field..how to do some thing like this .how to exclude the last added field from grid view for the second object data source..

答:
You should be able to just add/remove the column from the DataGridView.Columns collection depending on which data source you are bound to. When you bind to the source that needs the column, add it to the collection. When you bind to the other source, before binding, remove the column from the collection.

Here is a link about the Columns collection http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columns.aspx. Note the mention on the page that you can add/remove and obtain a count of columns by using the collection returned from the Columns property.

ContentLicense: CC BY-SA 2.5

Title: gridview with more than one data source


问:
Multiplying matrix with another one in C++
I have problem with my assignment, where I have three matrixes. I should multiply first one(a) by second(b) and the result return in third one(c). What is also worth to say is i can only move by pointers, I can't use index in loops.

The main problem is in case where dim1 == dim and matrix is not square one. All should be written in C++. My code returns almost good result but it looks like in the first row I pass garbage values. It looks like I don't fill these with values. I'd appreciate any help. Thanks

```<code>void multiply(int* a[], int* b[], int* c[], int dim1, int dim2, int
        dim3){

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            for( int k = 0; k < dim2; k++){
                *(*(c+i)+j) += *(*(a+i)+k) * *(*(b+k)+j);
            }
        }
    }

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            cout << *(*(c+i)+j) << "\t";
        }
        cout << endl;
    }
}

int main(){
    const int dim1 = 3;
    const int dim2 = 2;
    const int dim3 = 3;

    int a[dim1][dim2] = {{1,2},{3,4},{5,6}};
    int b[dim2][dim3] = {{1,2,3},{4,5,6}};
    int c[dim1][dim3] = {};

    int *tab1 [dim1];
    int *tab2 [dim2];
    int *tab3 [dim3];

    for(int i = 0; i < dim1; i++){
        *(tab1+i) = *(a+i);
        *(tab2+i) = *(b+i);
        *(tab3+i) = *(c+i);
    }

    multiply(tab1,tab2,tab3,dim1,dim2,dim3);
}
</code>```

答:
Everything is correct except tab initialization. You iterator to dim1=3, but tab2 is dim2=2 size. Try this:

```<code>const int dim1 = 3;
const int dim2 = 2;
const int dim3 = 3;

void multiply(int a[dim1][dim2], int b[dim2][dim3], int c[dim1][dim3], int dim1, int dim2, int
        dim3){

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            for( int k = 0; k < dim2; k++){
                *(*(c+i)+j) += *(*(a+i)+k) * *(*(b+k)+j);
            }
        }
    }

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            cout << *(*(c+i)+j) << "\t";
        }
        cout << endl;
    }
}

int main()
{
    int a[dim1][dim2] = {{1,2},{3,4},{5,6}};
    int b[dim2][dim3] = {{1,2,3},{4,5,6}};
    int c[dim1][dim3] = {};

    multiply(a,b,c,dim1,dim2,dim3);
}
</code>```

Body:
I have problem with my assignment, where I have three matrixes. I should multiply first one(a) by second(b) and the result return in third one(c). What is also worth to say is i can only move by pointers, I can't use index in loops.

The main problem is in case where dim1 == dim and matrix is not square one. All should be written in C++. My code returns almost good result but it looks like in the first row I pass garbage values. It looks like I don't fill these with values. I'd appreciate any help. Thanks

void multiply(int* a[], int* b[], int* c[], int dim1, int dim2, int
        dim3){

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            for( int k = 0; k < dim2; k++){
                *(*(c+i)+j) += *(*(a+i)+k) * *(*(b+k)+j);
            }
        }
    }

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            cout << *(*(c+i)+j) << "\t";
        }
        cout << endl;
    }
}

int main(){
    const int dim1 = 3;
    const int dim2 = 2;
    const int dim3 = 3;

    int a[dim1][dim2] = {{1,2},{3,4},{5,6}};
    int b[dim2][dim3] = {{1,2,3},{4,5,6}};
    int c[dim1][dim3] = {};

    int *tab1 [dim1];
    int *tab2 [dim2];
    int *tab3 [dim3];

    for(int i = 0; i < dim1; i++){
        *(tab1+i) = *(a+i);
        *(tab2+i) = *(b+i);
        *(tab3+i) = *(c+i);
    }

    multiply(tab1,tab2,tab3,dim1,dim2,dim3);
}

Body:
Everything is correct except tab initialization. You iterator to dim1=3, but tab2 is dim2=2 size. Try this:

const int dim1 = 3;
const int dim2 = 2;
const int dim3 = 3;

void multiply(int a[dim1][dim2], int b[dim2][dim3], int c[dim1][dim3], int dim1, int dim2, int
        dim3){

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            for( int k = 0; k < dim2; k++){
                *(*(c+i)+j) += *(*(a+i)+k) * *(*(b+k)+j);
            }
        }
    }

    for(int i = 0; i < dim1; i++){
        for(int j = 0; j < dim3; j++){
            cout << *(*(c+i)+j) << "\t";
        }
        cout << endl;
    }
}

int main()
{
    int a[dim1][dim2] = {{1,2},{3,4},{5,6}};
    int b[dim2][dim3] = {{1,2,3},{4,5,6}};
    int c[dim1][dim3] = {};

    multiply(a,b,c,dim1,dim2,dim3);
}


问:
Build HTTP request based on constituent parts
Say I have a representation of an HTTP request broken down to parts like so: method, URI, query params, headers, body.

So I might have something like:

```<code>Method: POST
Headers: [Content-Type: application/json, Host: localhost:8080, etc...]
Path: /home/sweet
Query: name=dan&id=1
Body: "some JSON here"
</code>```

How can I rebuild this into a valid net/http Request object? I would like to avoid string formatting and building as much as possible.

答:
There's really only one way to create an http.Request, and that is with http.NewRequest.  And it already takes three of your constituent parts as arguments: Method, path, and body.

You'll need to assemble your query params into the URL before calling NewRequest. The url package, and in particular, url.Values may be of assistance with this.

Once you have the new request, you can add headers as you would expect:

```<code>req, err := http.NewRequest("GET", "http://example.com/?foo=bar", body)
req.Header.Add("Content-Type", "application/json")
</code>```

And in case it needs stating, the body must be an io.Reader, but that gives you complete flexibility.

Body:
Say I have a representation of an HTTP request broken down to parts like so: method, URI, query params, headers, body.

So I might have something like:

Method: POST
Headers: [Content-Type: application/json, Host: localhost:8080, etc...]
Path: /home/sweet
Query: name=dan&id=1
Body: "some JSON here"

How can I rebuild this into a valid net/http Request object? I would like to avoid string formatting and building as much as possible.

Body:
There's really only one way to create an http.Request, and that is with http.NewRequest.  And it already takes three of your constituent parts as arguments: Method, path, and body.

You'll need to assemble your query params into the URL before calling NewRequest. The url package, and in particular, url.Values may be of assistance with this.

Once you have the new request, you can add headers as you would expect:

req, err := http.NewRequest("GET", "http://example.com/?foo=bar", body)
req.Header.Add("Content-Type", "application/json")

And in case it needs stating, the body must be an io.Reader, but that gives you complete flexibility.


问:
C++ source compilation using MATLAB Engine and g++
It would be helpful if you could  provide some guidance on how to compile  c++ source code files in an Ubuntu environment, using the MATLAB Engine with g++.</p>

答:
The compilation process in C/C++ is divided in two phases:

First, the compilation where source code is transformed into machines code with multiples object files (.o or .obj).

Then, the link to transform object files into a single executable file (.dll or .exe).

C/C++ programs that run matlab engine need three things:

1> A compiler that is compatible with matlab engine.

2> Reference to API header files('.h' for c or '.hpp' for c++) for compilation.

3> Reference to the libraries('.lib' for windows,'.so' for linux) for external symbol link.

You can see comptatible linux based system compiler here.
The GCC C/C++ 4.9.x is compatible so you can use g++.

As this pdf suggested, the API header files should be there $matlabroot/extern/include and the .so files should be in $matlabroot/
bin/glnax64 where $matlabroot is your matlab install folder

Set up Environment variables

Open your temnial with ctrl + alt + T and type :

```<code>setenv PATH $matlabroot/bin:$matlabroot/sys/os:$PATH
</code>```

You can then go to the folder where source file is located, let's say $matlabroot/extern/examples/eng_mat/ with the following command :

```<code>cd $matlabroot/extern/examples/eng_mat/
</code>```

You need to do the compilation with :

```<code>g++ -c engDemo.cpp -I '$matlabroot/extern/include' -leng -lmat -lmex -lut
</code>```

After that, a file named engDemo.o should be created.
The -leng -lmat -lmex -lut options are probably needed among other things because of the usage of the matlab interpreter that should be located in $matlabroot/bin

And the external symbol link with :

```<code>g++ -o engDemo -L '$matlabroot/bin/glnax64'
</code>```

Be careful as this path sugested that you are on a x64 architecture machine, if you are not,the path might be slightly different.

Then you can execute your file just by doing ./engDemo

I can't install the matlab engine on the laptot I am using so I'm unable to test the instruction I gave you but It should be done this way.

Hope it helps !!

ContentLicense: CC BY-SA 4.0

Body:
The compilation process in C/C++ is divided in two phases:

First, the compilation where source code is transformed into machines code with multiples object files (.o or .obj).

Then, the link to transform object files into a single executable file (.dll or .exe).

C/C++ programs that run matlab engine need three things:

1> A compiler that is compatible with matlab engine.

2> Reference to API header files('.h' for c or '.hpp' for c++) for compilation.

3> Reference to the libraries('.lib' for windows,'.so' for linux) for external symbol link.

You can see comptatible linux based system compiler here.
The GCC C/C++ 4.9.x is compatible so you can use g++.

As this pdf suggested, the API header files should be there $matlabroot/extern/include and the .so files should be in $matlabroot/
bin/glnax64 where $matlabroot is your matlab install folder

Set up Environment variables

Open your temnial with ctrl + alt + T and type :

setenv PATH $matlabroot/bin:$matlabroot/sys/os:$PATH

You can then go to the folder where source file is located, let's say $matlabroot/extern/examples/eng_mat/ with the following command :

cd $matlabroot/extern/examples/eng_mat/

You need to do the compilation with :

g++ -c engDemo.cpp -I '$matlabroot/extern/include' -leng -lmat -lmex -lut

After that, a file named engDemo.o should be created.
The -leng -lmat -lmex -lut options are probably needed among other things because of the usage of the matlab interpreter that should be located in $matlabroot/bin

And the external symbol link with :

g++ -o engDemo -L '$matlabroot/bin/glnax64'

Be careful as this path sugested that you are on a x64 architecture machine, if you are not,the path might be slightly different.

Then you can execute your file just by doing ./engDemo

I can't install the matlab engine on the laptot I am using so I'm unable to test the instruction I gave you but It should be done this way.

Hope it helps !!


问:
Does boto3 Bucket.object.filter retrieve object efficiently?
I want to get a list of all the objects(or max 1000) located at foo-bucket/foo-dir , e.g.

Bucket: foo-bucket

Directory: foo-dir

I see Bucket.objects boto3 API use filtering(Bucket.objects.filter)

I am wondering what it does internally? Does it list all the objects and filter? Or does AWS provide an API that takes filter arguments and return the filtered results.

答:
The S3 API supports a prefix on the ListObjects request that will filter the responses to include only those objects whose name matches the prefix.  So:

```<code>import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.filter(Prefix='foo/bar/fie/baz/'):
    # do something with obj here
</code>```

Would only return objects whose name begins with the prefix foo/bar/fie/baz/.

Body:
The S3 API supports a prefix on the ListObjects request that will filter the responses to include only those objects whose name matches the prefix.  So:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.filter(Prefix='foo/bar/fie/baz/'):
    # do something with obj here

Would only return objects whose name begins with the prefix foo/bar/fie/baz/.


问:
How to inject property values into Spring Boot beans
In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.

here is the configuration of my application.properties file:

```<code>  myapp.username=user@user.com
  myapp.password=user
</code>```

here is where i call the configuration entries:

```<code>@Component
public class MyClass{

        @Value("${myapp.username}")
        public String username;

        @Value("${myapp.password}")
        public String password;

        public static void main(String[] args)  {

             System.out.println(password);
        }

  }
</code>```

I hope there someone how did deal with the same problem, thanks.

答:
You are not even letting the Spring Boot container to boot (initialize) as you are are writing the code directly under main.

You should have an Application class as shown below to launch the Spring boot container properly, look here.

```<code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

As far as my understanding you wanted to execute your code once the container is started, so follow the below steps:

Add the above Application class and then in your NetClient component class add a @Postconstruct method & this method will be called automatically once the bean is ready, refer the code below:

```<code>@Component
public class NetClient {

    @Value("${bigwater.api_config.url.login}")
    public String url_login;

    @Value("${bigwater.api_config.url.ws}")
    public static String url_ws;

    @Value("${bigwater.api_config.username}")
    public String username;

    @Value("${bigwater.api_config.password}")
    public String password;

     @Postconstruct
     public void init() {
       //place all of your main(String[] args) method code here
     }

     //Add authentification() method here
}
</code>```

Body:
In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.

here is the configuration of my application.properties file:

  myapp.username=user@user.com
  myapp.password=user

here is where i call the configuration entries:

@Component
public class MyClass{

        @Value("${myapp.username}")
        public String username;

        @Value("${myapp.password}")
        public String password;

        public static void main(String[] args)  {

             System.out.println(password);
        }

  }

I hope there someone how did deal with the same problem, thanks.

Body:
You are not even letting the Spring Boot container to boot (initialize) as you are are writing the code directly under main.

You should have an Application class as shown below to launch the Spring boot container properly, look here.

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

As far as my understanding you wanted to execute your code once the container is started, so follow the below steps:

Add the above Application class and then in your NetClient component class add a @Postconstruct method & this method will be called automatically once the bean is ready, refer the code below:

@Component
public class NetClient {

    @Value("${bigwater.api_config.url.login}")
    public String url_login;

    @Value("${bigwater.api_config.url.ws}")
    public static String url_ws;

    @Value("${bigwater.api_config.username}")
    public String username;

    @Value("${bigwater.api_config.password}")
    public String password;

     @Postconstruct
     public void init() {
       //place all of your main(String[] args) method code here
     }

     //Add authentification() method here
}


问:
Xamarin.Android HTTP Random Delays
I have a method that executes several HTTP requests called LoadServers() A button that executes LoadServers(). For my issue I only tap the button once the previous LoadServers() call has finished. A progress dialog appears while loading so I can only execute them serially.

Once in about every 10-15 calls to LoadServers results in the first http request to delay for almost exactly 10 seconds. The average time for LoadServers to complete is less than a half second and never more than 1 second. This only happens on Xamarin.Android. The delay does not happen on Xamarin.iOS and all of this code is shared.

Here is my code

```<code>private async Task LoadServers() {
    await Get();
    await Post();
    await Get();
    await Get();
    await Post();
}

private async Task Get() {
    var url = _httpClient.BaseAddress + model.GetToken();
    Log("Attempting to send GET to: " + url);
    using (var response = await _httpClient.GetAsync(url))
    {
        var resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}

private async Task Post() {
    var content = requestData.GetToken() + "=" + requestData.PostBody ();
    var request = new StringContent(content)
    {
        Headers = { ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") }
    };
    var url = _httpClient.BaseAddress + "/No_content";
    Log ("Attempting to send POST to: " + url + "  with content: " + content);
    using (var response = await _httpClient.PostAsync(url, request))
    {
        string resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}
</code>```

Every 15 or so executions of LoadServers() results in the following log statements:

```<code>Thread started:  #37
Thread finished:  #37
[2017-01-21T13:42:30.8841620-06:00] [debug] Loading Servers
[2017-01-21T13:42:30.8946770-06:00] [debug] Attempting to send GET to: XXX
Thread finished: <Thread Pool> #23
Thread started: <Thread Pool> #38
[2017-01-21T13:42:40.9550360-06:00] [debug] Got response back from : XXX <-- Notice the time (~10 seconds)
</code>```

Does this have to do with resource consumption for the HTTP request? It attempts to clean up the resources and pauses execution until that happens? I'm not sure exactly what happens when it execute the request. Does it start a new thread?

答:
I experimented the same issue.
i'm using xamarin.android 6.6.1.2-21 and support stuff for Api 23.

I found that using the default httpHandler and creating 2 httpClients before your first call solve this issue.

```<code>new HttpClient( new Xamarin.Android.Net.AndroidClientHandler());
</code>```

and create 2 httpclients before start any real call in your code.

Also setup the "HttpClient implementation" to "AndroidClientHandler". You can find this option on: Project options > Android build > Code generation And Runtime.
This only work on android 5+

http implementation option

Title: Xamarin.Android HTTP Random Delays

Body:
I have a method that executes several HTTP requests called LoadServers() A button that executes LoadServers(). For my issue I only tap the button once the previous LoadServers() call has finished. A progress dialog appears while loading so I can only execute them serially.

Once in about every 10-15 calls to LoadServers results in the first http request to delay for almost exactly 10 seconds. The average time for LoadServers to complete is less than a half second and never more than 1 second. This only happens on Xamarin.Android. The delay does not happen on Xamarin.iOS and all of this code is shared.

Here is my code

private async Task LoadServers() {
    await Get();
    await Post();
    await Get();
    await Get();
    await Post();
}

private async Task Get() {
    var url = _httpClient.BaseAddress + model.GetToken();
    Log("Attempting to send GET to: " + url);
    using (var response = await _httpClient.GetAsync(url))
    {
        var resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}

private async Task Post() {
    var content = requestData.GetToken() + "=" + requestData.PostBody ();
    var request = new StringContent(content)
    {
        Headers = { ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") }
    };
    var url = _httpClient.BaseAddress + "/No_content";
    Log ("Attempting to send POST to: " + url + "  with content: " + content);
    using (var response = await _httpClient.PostAsync(url, request))
    {
        string resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}

Every 15 or so executions of LoadServers() results in the following log statements:

Thread started:  #37
Thread finished:  #37
[2017-01-21T13:42:30.8841620-06:00] [debug] Loading Servers
[2017-01-21T13:42:30.8946770-06:00] [debug] Attempting to send GET to: XXX
Thread finished: <Thread Pool> #23
Thread started: <Thread Pool> #38
[2017-01-21T13:42:40.9550360-06:00] [debug] Got response back from : XXX <-- Notice the time (~10 seconds)

Does this have to do with resource consumption for the HTTP request? It attempts to clean up the resources and pauses execution until that happens? I'm not sure exactly what happens when it execute the request. Does it start a new thread?

Body:
I experimented the same issue.
i'm using xamarin.android 6.6.1.2-21 and support stuff for Api 23.

I found that using the default httpHandler and creating 2 httpClients before your first call solve this issue.

new HttpClient( new Xamarin.Android.Net.AndroidClientHandler());

and create 2 httpclients before start any real call in your code.

Also setup the "HttpClient implementation" to "AndroidClientHandler". You can find this option on: Project options > Android build > Code generation And Runtime.
This only work on android 5+

http implementation option


问:
Plotting lm curve does not show using ggplot
As per ex18q1 in "R for Data Science" I am trying to find the best model for the data:

```<code>sim1a <- tibble(
  x = rep(1:10, each = 3),
  y = x * 1.5 + 6 + rt(length(x), df = 2)
)
</code>```

I've applied linear model and am trying to plot the results on a graph using ggplot:

```<code>sim1a_mod <- lm(x ~ y, data = sim1a)

ggplot(sim1a, aes(x, y)) +
  geom_point(size = 2, colour= "gray") +
  geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red")
</code>```

coef(sim1a_mod)[[1]] prints -1.14403

coef(sim1a_mod)[[2]] prints 0.4384473

I create the plot with the data points, but the model is not showing.  What am I doing wrong?

答:
The nomenclature for typing formulas for model functions like lm(), glm(), lmer() etc. in R is always DV ~ IV1 + IV2 + ... + IVn where DV is your dependent variable and IVn is your list of independent variables. We typically chart the dependent variable on the y-axis and the independent variable on the x-axis, so in your case you'll need to change your sim1a_mod model to lm(y ~ x, data = sim1a).

In your original code, because you were running a different model, your line was being charted, but it was outside of your view. If you attempt to chart again with your original model with the following code you will then see your regression line:

```<code>ggplot(sim1a, aes(x, y)) +
geom_point(size = 2, colour= "gray") +
geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red") +
scale_x_continuous(limits = c(-30, 30)) + scale_y_continuous(limits = c(-30, 30))
</code>```

Body:
As per ex18q1 in "R for Data Science" I am trying to find the best model for the data:

sim1a <- tibble(
  x = rep(1:10, each = 3),
  y = x * 1.5 + 6 + rt(length(x), df = 2)
)

I've applied linear model and am trying to plot the results on a graph using ggplot:

sim1a_mod <- lm(x ~ y, data = sim1a)

ggplot(sim1a, aes(x, y)) +
  geom_point(size = 2, colour= "gray") +
  geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red")

coef(sim1a_mod)[[1]] prints -1.14403

coef(sim1a_mod)[[2]] prints 0.4384473

I create the plot with the data points, but the model is not showing.  What am I doing wrong?

Body:
The nomenclature for typing formulas for model functions like lm(), glm(), lmer() etc. in R is always DV ~ IV1 + IV2 + ... + IVn where DV is your dependent variable and IVn is your list of independent variables. We typically chart the dependent variable on the y-axis and the independent variable on the x-axis, so in your case you'll need to change your sim1a_mod model to lm(y ~ x, data = sim1a).

In your original code, because you were running a different model, your line was being charted, but it was outside of your view. If you attempt to chart again with your original model with the following code you will then see your regression line:

ggplot(sim1a, aes(x, y)) +
geom_point(size = 2, colour= "gray") +
geom_abline(intercept = coef(sim1a_mod)[[1]], slope = coef(sim1a_mod)[[2]], colour = "red") +
scale_x_continuous(limits = c(-30, 30)) + scale_y_continuous(limits = c(-30, 30))


问:
Can I see code coverage on code executed by headless browser?
ATM I'm working on a small project with node.js + express + mongodb. The logic is on web, but  is loaded from my node.js server. Something like this in my index.html

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

var debug = false;

$(document).ready(function() {
    app.start();
});
</script>
</code>```

My test are functional -- meaning that I use a headless browser (Zombie) and I get good indications about the coverage with istanbul. I tried blanket unsuccessfully.

```<code>process.env['TEST'] = true;
var app = require('../server/JS_TPV.server.js');
var mongodb = require('mongodb');
var should = require("should");
var Browser = require("zombie");
var browser;
</code>```

Then something like:

```<code>before(function(done) {
    var populateDB = require('../install/JS_TPV.mongo_db_fill.js');
    populateDB.install(function() {
        browser = new Browser({debug:false, silent:false});
        browser.visit("http://localhost:8080").then(done,done);
        console.log("visited ending BEFORE");
    });
});
</code>```

But since index.html file is being accessed and all the js files on it are loaded, I think it should show it's coverage too.

Is any way to show this?

Or the only way to do this is by generating an html-kind of test where I check my web functions? (yeah, or with require.js and testing all the logic node-style).

Thanks!

答:
You can :)

The key points are

the code executed by the browser has to be instrumented

someone must collect the coverage information

You can find an example of this working here: https://github.com/ericminio/yop-promises/blob/master/test/promises.with.browser.spec.js

run in order npm run cover and npm run report and navigate to coverage folder to find the report. Play around with not running Zombie test to see how that impacts code coverage.

This is one example with Zombie and Istanbul, so it really deals specifically with how those two tools can let you go through the 2 points above.

Body:
ATM I'm working on a small project with node.js + express + mongodb. The logic is on web, but  is loaded from my node.js server. Something like this in my index.html

My test are functional -- meaning that I use a headless browser (Zombie) and I get good indications about the coverage with istanbul. I tried blanket unsuccessfully.

process.env['TEST'] = true;
var app = require('../server/JS_TPV.server.js');
var mongodb = require('mongodb');
var should = require("should");
var Browser = require("zombie");
var browser;

Then something like:

before(function(done) {
    var populateDB = require('../install/JS_TPV.mongo_db_fill.js');
    populateDB.install(function() {
        browser = new Browser({debug:false, silent:false});
        browser.visit("http://localhost:8080").then(done,done);
        console.log("visited ending BEFORE");
    });
});

But since index.html file is being accessed and all the js files on it are loaded, I think it should show it's coverage too.

Is any way to show this?

Or the only way to do this is by generating an html-kind of test where I check my web functions? (yeah, or with require.js and testing all the logic node-style).

Thanks!


问:
Get date from self object
I am attempting to pull the date field from the current item. I can't seem to get the syntax right. How would I go about getting the date data from the form I just submitted? Whenever I try the code below I get the following error:

```<code>'NoneType' object has no attribute 'get'
</code>```

views.py

```<code>class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        e_item = self.object.get()
        e_date = e_item.get('date')
        e_month = e_date.strftime('%B')
        e_year = e_date.year
        qs = MonthYear.objects.filter(month=e_month, year=e_year)
</code>```

models.py

```<code>class Entry(models.Model):
    date = models.DateField(blank=True, null=True,)
    euros = models.CharField(max_length=500, blank=True, null=True)
    comments = models.CharField(max_length=900, blank=True, null=True)
</code>```

Thanks in advance for your help.

答:
You should try using self.object.date.

I found this: Django Docs: Form Handling. The example here accesses the primary key by using self.object.pk

Here's an example of what I had done for one of my projects, but note that this was using Django-Rest-Framework so I'm not sure if this would work for you.

serializers.py

```<code>class JournalSerializer(serializers.ModelSerializer):

    class Meta:
        model = Journal
        exclude = ('id', 'user',)

    def get_date(self, obj):
        return obj.date.replace(microsecond=0)
</code>```

Title: Get date from self object

Body:
I am attempting to pull the date field from the current item. I can't seem to get the syntax right. How would I go about getting the date data from the form I just submitted? Whenever I try the code below I get the following error:

'NoneType' object has no attribute 'get'

views.py

class EntryCreate(CreateView):
    form_class = EntryForm
    template_name = 'argent/entry_form.html'

    def form_valid(self, form):
        e_item = self.object.get()
        e_date = e_item.get('date')
        e_month = e_date.strftime('%B')
        e_year = e_date.year
        qs = MonthYear.objects.filter(month=e_month, year=e_year)

models.py

class Entry(models.Model):
    date = models.DateField(blank=True, null=True,)
    euros = models.CharField(max_length=500, blank=True, null=True)
    comments = models.CharField(max_length=900, blank=True, null=True)

Thanks in advance for your help.

Body:
You should try using self.object.date.

I found this: Django Docs: Form Handling. The example here accesses the primary key by using self.object.pk

Here's an example of what I had done for one of my projects, but note that this was using Django-Rest-Framework so I'm not sure if this would work for you.

serializers.py

class JournalSerializer(serializers.ModelSerializer):

    class Meta:
        model = Journal
        exclude = ('id', 'user',)

    def get_date(self, obj):
        return obj.date.replace(microsecond=0)


问:
Your account already has a valid Developer ID Application certificate
The last couple of days I've struggled with code signing my cocoa app in Xcode. I've read through all similar topic that looked to be related, but nothing has helped.

Whenever I try to export my archive I get this error message:

I've tried to delete everything in my keychain and all profiles/certificates that I'm allowed to delete/revoke in the member center. However, I still get the same error with no "Fix" or "Reset" button. How should I proceed in order to get my application signed for distribution outside of store?

答:
Same issue here but i was using "automatically manage settings" on Xcode 8. And for a particular reason there were two distribution certificates in my developer account.

Xcode seems to choose the most recent automatically and I didn't have it installed on my mac. So I switch to the old way by creating manually my app ID and my provisioning profile (which use the appropriate certificate) and it works :)


问:
Xcode: Any way to refresh/re-run the playground?
The Playground in Xcode automatically updates as you type, but I can't figure out how to get the Playground to "re-compile".

In many cases this wouldn't matter, but if you're writing code that generates or uses random values it can be useful to run it a few times to make sure it's working. Is there any way to get the playground to reset / refresh / re-run?

Seen a few questions asking how to stop the Playground from auto-updating, but nothing for the opposite.

Easiest way to do this seems to be to just edit the code (add and remove a space), or put in some kind of a loop... Just wondering if there's a menu shortcut etc.

答:
In addition to the other responses, playground execution can also be controlled with the button on the bottom bar above the debugger console. There are two buttons on the left side of the console; the one on the left opens/closes the console and the one on the right controls the execution of the playground and changes depending on whether the playground is currently running.

If you hover over the button a small black triangle will appear in the bottom corner of the button. If you long press on the button the menu in the screenshot below will appear, where you can change the execution mode of the playground between automatically or manually running. If it's automatic, then it should run once every time you make a change (unless you make a change while it's running, then it will interrupt itself and run again). If it's manual then you have to press the button to run the playground.

While running the button is a hollow square, like a stop button on a VCR. Pressing it will stop the execution.

When it's not running it is a blue triangle, like a play button on a VCR. Pressing it will run the playground.

(Running Xcode 8.3)


问:
Hadoop Wordcount example failing due to AM container
I've been trying to run the hadoop wordcount example for a while now, however I am facing some issues. I have hadoop 2.7.1 and running it on Windows. Below are the error details:

command:

```<code>yarn jar C:\hadoop-2.7.1\share\hadoop\mapreduce\hadoop-mapreduce-examples-2.7.1.jar wordcount input output
</code>```

Output:

```<code>INFO input.FileInputFormat: Total input paths to process : 1
INFO mapreduce.JobSubmitter: number of splits:1
INFO mapreduce.JobSubmitter: Submitting tokens for job: job_14
90853163147_0009
INFO impl.YarnClientImpl: Submitted application application_14
90853163147_0009
INFO mapreduce.Job: The url to track the job: http://*****
*****/proxy/application_1490853163147_0009/
INFO mapreduce.Job: Running job: job_1490853163147_0009
INFO mapreduce.Job: Job job_1490853163147_0009 running in uber
 mode : false
INFO mapreduce.Job:  map 0% reduce 0%
INFO mapreduce.Job: Job job_1490853163147_0009 failed with sta
te FAILED due to: Application application_1490853163147_0009 failed 2 times due
to AM Container for appattempt_1490853163147_0009_000002 exited with  exitCode:
1639
For more detailed output, check application tracking page:http://********
:****/cluster/app/application_1490853163147_0009Then, click on links to logs of
each attempt.
Diagnostics: Exception from container-launch.
Container id: container_1490853163147_0009_02_000001
Exit code: 1639
Exception message: Incorrect command line arguments.

Stack trace: ExitCodeException exitCode=1639: Incorrect command line arguments.

        at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
        at org.apache.hadoop.util.Shell.run(Shell.java:456)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:
722)
        at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.la
unchContainer(DefaultContainerExecutor.java:211)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.C
ontainerLaunch.call(ContainerLaunch.java:302)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.C
ontainerLaunch.call(ContainerLaunch.java:82)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
        at java.lang.Thread.run(Thread.java:745)

Shell output:     Usage: task create [TASKNAME] [COMMAND_LINE] |
          task isAlive [TASKNAME] |
          task kill [TASKNAME]
          task processList [TASKNAME]
    Creates a new task jobobject with taskname
    Checks if task jobobject is alive
    Kills task jobobject
    Prints to stdout a list of processes in the task
    along with their resource usage. One process per line
    and comma separated info per process
    ProcessId,VirtualMemoryCommitted(bytes),
    WorkingSetSize(bytes),CpuTime(Millisec,Kernel+User)

Container exited with a non-zero exit code 1639
Failing this attempt. Failing the application.
INFO mapreduce.Job: Counters: 0
</code>```

Yarn-site.xml:

```<code><configuration>
<property>
       <name>yarn.application.classpath</name>
       <value>
            C:\hadoop-2.7.1\etc\hadoop,
            C:\hadoop-2.7.1\share\hadoop\common\*,
            C:\hadoop-2.7.1\share\hadoop\common\lib\*,
            C:\hadoop-2.7.1\share\hadoop\hdfs\*,
            C:\hadoop-2.7.1\share\hadoop\hdfs\lib\*,
            C:\hadoop-2.7.1\share\hadoop\mapreduce\*,
            C:\hadoop-2.7.1\share\hadoop\mapreduce\lib\*,
            C:\hadoop-2.7.1\share\hadoop\yarn\*,
            C:\hadoop-2.7.1\share\hadoop\yarn\lib\*
       </value>
    </property>
  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>
  <property>
        <name>yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage</name>
        <value>98.5</value>
</property>
<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
  <value>2200</value>
  <description>Amount of physical memory, in MB, that can be allocated for containers.</description>
</property>

<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
  <value>500</value>
</property>
<property>
    <name>yarn.log-aggregation-enable</name>
    <value>true</value>
</property>

<property>
    <description>Where to aggregate logs to.</description>
    <name>yarn.nodemanager.remote-app-log-dir</name>
    <value>/tmp/logs</value>
</property>

<property>
    <name>yarn.log-aggregation.retain-seconds</name>
    <value>259200</value>
</property>

<property>
    <name>yarn.log-aggregation.retain-check-interval-seconds</name>
    <value>3600</value>
</property>
</configuration>
</code>```

mapred.xml:

```<code><?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->

<!-- Put site-specific property overrides in this file. -->

<configuration>
  <property>
    <name>mapreduce.framework.name</name>
    <value>yarn</value>
  </property>
</configuration>
</code>```

Any idea on what is going wrong?

答:
exitCode:  1639  Looks like your are running hadoop on Windows .

https://github.com/OctopusDeploy/Issues/issues/1346

Body:
I've been trying to run the hadoop wordcount example for a while now, however I am facing some issues. I have hadoop 2.7.1 and running it on Windows. Below are the error details:

command:

yarn jar C:\hadoop-2.7.1\share\hadoop\mapreduce\hadoop-mapreduce-examples-2.7.1.jar wordcount input output

Output:

INFO input.FileInputFormat: Total input paths to process : 1
INFO mapreduce.JobSubmitter: number of splits:1
INFO mapreduce.JobSubmitter: Submitting tokens for job: job_14
90853163147_0009
INFO impl.YarnClientImpl: Submitted application application_14
90853163147_0009
INFO mapreduce.Job: The url to track the job: http://*****
*****/proxy/application_1490853163147_0009/
INFO mapreduce.Job: Running job: job_1490853163147_0009
INFO mapreduce.Job: Job job_1490853163147_0009 running in uber
 mode : false
INFO mapreduce.Job:  map 0% reduce 0%
INFO mapreduce.Job: Job job_1490853163147_0009 failed with sta
te FAILED due to: Application application_1490853163147_0009 failed 2 times due
to AM Container for appattempt_1490853163147_0009_000002 exited with  exitCode:
1639
For more detailed output, check application tracking page:http://********
:****/cluster/app/application_1490853163147_0009Then, click on links to logs of
each attempt.
Diagnostics: Exception from container-launch.
Container id: container_1490853163147_0009_02_000001
Exit code: 1639
Exception message: Incorrect command line arguments.

Stack trace: ExitCodeException exitCode=1639: Incorrect command line arguments.

        at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
        at org.apache.hadoop.util.Shell.run(Shell.java:456)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:
722)
        at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.la
unchContainer(DefaultContainerExecutor.java:211)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.C
ontainerLaunch.call(ContainerLaunch.java:302)
        at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.C
ontainerLaunch.call(ContainerLaunch.java:82)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
        at java.lang.Thread.run(Thread.java:745)

Shell output:     Usage: task create [TASKNAME] [COMMAND_LINE] |
          task isAlive [TASKNAME] |
          task kill [TASKNAME]
          task processList [TASKNAME]
    Creates a new task jobobject with taskname
    Checks if task jobobject is alive
    Kills task jobobject
    Prints to stdout a list of processes in the task
    along with their resource usage. One process per line
    and comma separated info per process
    ProcessId,VirtualMemoryCommitted(bytes),
    WorkingSetSize(bytes),CpuTime(Millisec,Kernel+User)

Container exited with a non-zero exit code 1639
Failing this attempt. Failing the application.
INFO mapreduce.Job: Counters: 0

Yarn-site.xml:

<configuration>
<property>
       <name>yarn.application.classpath</name>
       <value>
            C:\hadoop-2.7.1\etc\hadoop,
            C:\hadoop-2.7.1\share\hadoop\common\*,
            C:\hadoop-2.7.1\share\hadoop\common\lib\*,
            C:\hadoop-2.7.1\share\hadoop\hdfs\*,
            C:\hadoop-2.7.1\share\hadoop\hdfs\lib\*,
            C:\hadoop-2.7.1\share\hadoop\mapreduce\*,
            C:\hadoop-2.7.1\share\hadoop\mapreduce\lib\*,
            C:\hadoop-2.7.1\share\hadoop\yarn\*,
            C:\hadoop-2.7.1\share\hadoop\yarn\lib\*
       </value>
    </property>
  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>
  <property>
        <name>yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage</name>
        <value>98.5</value>
</property>
<property>
  <name>yarn.nodemanager.resource.memory-mb</name>
  <value>2200</value>
  <description>Amount of physical memory, in MB, that can be allocated for containers.</description>
</property>

<property>
  <name>yarn.scheduler.minimum-allocation-mb</name>
  <value>500</value>
</property>
<property>
    <name>yarn.log-aggregation-enable</name>
    <value>true</value>
</property>

<property>
    <description>Where to aggregate logs to.</description>
    <name>yarn.nodemanager.remote-app-log-dir</name>
    <value>/tmp/logs</value>
</property>

<property>
    <name>yarn.log-aggregation.retain-seconds</name>
    <value>259200</value>
</property>

<property>
    <name>yarn.log-aggregation.retain-check-interval-seconds</name>
    <value>3600</value>
</property>
</configuration>

mapred.xml:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>
  <property>
    <name>mapreduce.framework.name</name>
    <value>yarn</value>
  </property>
</configuration>

Any idea on what is going wrong?


问:
CSS3 Rounded corner for input element without js/images
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

```<code><!DOCTYPE html>
<html>
<head>
    <title>xx</title>
<style type="text/css">
input
{
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
}
</style>
</head>
<body>
<input type="text" value="test" />
</body>
</html>
</code>```

It does not work in firefox 3.6.12!

答:
For modern browsers, use the following CSS code:

```<code>input {
   -moz-border-radius:6px;
   -webkit-border-radius:6px;
   border-radius:6px;
}
</code>```

In other words, pretty much exactly what you've done already.

This should get you rounded corners in all major browsers apart from IE.

I suspect the reason it doesn't work is either (a) you're testing it in IE (see below for solution), or (b) because your

Body:
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

<!DOCTYPE html>

    <title>xx</title>

<input type="text" value="test" />

It does not work in firefox 3.6.12!

Body:
For modern browsers, use the following CSS code:

input {
   -moz-border-radius:6px;
   -webkit-border-radius:6px;
   border-radius:6px;
}

In other words, pretty much exactly what you've done already.

This should get you rounded corners in all major browsers apart from IE.

I suspect the reason it doesn't work is either (a) you're testing it in IE (see below for solution), or (b) because your <style> tag has an incorrect type attribute. You probably don't need the type attribute at all; I'd suggest dropping it entirely (it is usually only seen when loading stylesheets from an external source). If you do keep it, then drop the trailing slash, as that is definitely incorrect.

For IE, the solution is more complicated:

By far the best solution to the CSS3 rounded corners problem in IE is CSS3Pie.

It's an IE-only hack based on an IE feature called CSS Behaviors. This means that non-IE browsers will completely ignore it, and not even have to download the .HTC file that contains the hack.

It generates true rounded corners using IE's VML vector graphics library, so you will never have any jagged edges or mis-matched background colours or patterns.

Although it does have a few known issues, it is under active development, and even the issues it does have are far less problematic than those of any other solution.

CSS Behaviors is based on Javascript -- you won't find a solution to your problem that doesn't use Javascript somewhere along the line (unless you plan to use old fashioned corner graphics for everything), but because it is enclosed in a MS-specific HTC file, other browsers never need to know about it, so you can use normal CSS3 for them without any javascript.

This does mean that in the unlikely event of an IE users having Javascript turned off, then yes, they'll get square corners. But you can be fairly confident they'll be a vanishingly small minority.


问:
Newtonsoft.JSON Serialize\Deserialize Datatable with GUID
I have a Web API solution I'm using to work with various databases.  Everything was working until I accessed a table with a GUID number in it.  I finally narrowed down the problem to the Serialize/Deserialize methods.  When the DataTable is serialized to JSON and then subsequently deserialized back to a DataTable, the data type of the column containing the GUID becomes System.String instead of System.Guid like it was originally.

Take this simple example:

```<code>System.Data.DataTable myData = new DataTable();
myData.Columns.Add("ID", typeof(System.Guid));
myData.Columns.Add("Name", typeof(System.String));
myData.Rows.Add(System.Guid.NewGuid(), "Name1");

// Reports: System.Guid
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

string mySerializedString = Newtonsoft.Json.JsonConvert.SerializeObject(myData);
myData = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(mySerializedString);

// Reports: System.String
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);
</code>```

This is a generic API so I have no idea if the table(s) being passed around have columns containing GUIDs or any other data types that may cause issues with JSON.

Hopefully it's just because I'm missing something stupid and it's just a simple fix?

**** Update ****

Thanks for the tips all. In the meantime I have run into yet another problem that may just be the end of it all.

When you initially load a table from the database, every rowstate = unchanged. However going through the Serialize process, the result is every rowstate becomes "Added".

So take for example I query 1 record, modify that record and send it back. The DataTable has now flagged that record as "Added" which then breaks the primary key constraint and it blows up.

This sucks!

I'm basically looking at some sort of huge kludge job on both ends where I would have to pass a Dictionary of all the properties that I discover get hosed via the JSON process and then Rebuild it all on the other end.

All while trying to be generic and not knowing what kind of data I'm supposed to be dealing with.

&*(^% it!

答:
As @Craig H pointed out, JSON has a very limited type system-- it can differentiate numbers, booleans, strings, objects and arrays, and the null value.  If you need anything more specific than that, you have to resort to embedding type information as metadata in the JSON itself.

Json.Net has a TypeNameHandling setting which can be used to make it write type information into the JSON.  Unfortunately, the DataTableConverter that ships with Json.Net does not seem to honor this setting.  To work around this, you can use a custom JsonConverter for DataTables such as the one in How to include column metadata in JSON for an empty DataTable

Use it like this:

```<code>JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomDataTableConverter());

string mySerializedString = JsonConvert.SerializeObject(myData, settings);
myData = JsonConvert.DeserializeObject<DataTable>(mySerializedString, settings);
</code>```

Here is a demo with your example code: https://dotnetfiddle.net/wXNy9o

Body:
I have a Web API solution I'm using to work with various databases.  Everything was working until I accessed a table with a GUID number in it.  I finally narrowed down the problem to the Serialize/Deserialize methods.  When the DataTable is serialized to JSON and then subsequently deserialized back to a DataTable, the data type of the column containing the GUID becomes System.String instead of System.Guid like it was originally.

Take this simple example:

System.Data.DataTable myData = new DataTable();
myData.Columns.Add("ID", typeof(System.Guid));
myData.Columns.Add("Name", typeof(System.String));
myData.Rows.Add(System.Guid.NewGuid(), "Name1");

// Reports: System.Guid
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

string mySerializedString = Newtonsoft.Json.JsonConvert.SerializeObject(myData);
myData = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(mySerializedString);

// Reports: System.String
System.Diagnostics.Debug.Write(myData.Columns["ID"].DataType.FullName);

This is a generic API so I have no idea if the table(s) being passed around have columns containing GUIDs or any other data types that may cause issues with JSON.

Hopefully it's just because I'm missing something stupid and it's just a simple fix?

**** Update ****

Thanks for the tips all. In the meantime I have run into yet another problem that may just be the end of it all.

When you initially load a table from the database, every rowstate = unchanged. However going through the Serialize process, the result is every rowstate becomes "Added".

So take for example I query 1 record, modify that record and send it back. The DataTable has now flagged that record as "Added" which then breaks the primary key constraint and it blows up.

This sucks!

I'm basically looking at some sort of huge kludge job on both ends where I would have to pass a Dictionary of all the properties that I discover get hosed via the JSON process and then Rebuild it all on the other end.

All while trying to be generic and not knowing what kind of data I'm supposed to be dealing with.

&*(^% it!

Body:
As @Craig H pointed out, JSON has a very limited type system-- it can differentiate numbers, booleans, strings, objects and arrays, and the null value.  If you need anything more specific than that, you have to resort to embedding type information as metadata in the JSON itself.

Json.Net has a TypeNameHandling setting which can be used to make it write type information into the JSON.  Unfortunately, the DataTableConverter that ships with Json.Net does not seem to honor this setting.  To work around this, you can use a custom JsonConverter for DataTables such as the one in How to include column metadata in JSON for an empty DataTable

Use it like this:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomDataTableConverter());

string mySerializedString = JsonConvert.SerializeObject(myData, settings);
myData = JsonConvert.DeserializeObject<DataTable>(mySerializedString, settings);

Here is a demo with your example code: https://dotnetfiddle.net/wXNy9o


问:
launching SAS Management Console from a mac over SSH with X11
I have a remote instance of SAS Management Console in the following location:

/pub/sas/SASManagementConsole/9.4/sasmc_console

I'd like to be able to launch this as a GUI interface.  I've tried the following (in XQuartz):

```<code>export DISPLAY=:0
ssh -x myuser@app.myserver.com
cd /pub/sas/SASManagementConsole/9.4
./sasmc_console
</code>```

This returns:

```<code>Exception in thread "main" java.lang.InternalError: Can't connect to X11
window server using ':0' as the value of the DISPLAY variable.
</code>```

What should be the value of my display variable?

答:
doh..  So it appears I should have used an uppercase X as follows:

```<code>ssh -X myuser@app.myserver.com
</code>```

But there were other things I had to update before the window worked properly.  First, in the following file:

```<code>/private/etc/ssh_config
</code>```

I changed the following values:

```<code>#   ForwardX11 no
#   ForwardX11Trusted no
</code>```

to:

```<code>#   ForwardX11 yes
#   ForwardX11Trusted yes
</code>```

I also ran:

```<code>rm /tmp/.X11-unix/X0
</code>```

And restarted the machine...

Body:
I have a remote instance of SAS Management Console in the following location:

/pub/sas/SASManagementConsole/9.4/sasmc_console

I'd like to be able to launch this as a GUI interface.  I've tried the following (in XQuartz):

export DISPLAY=:0
ssh -x myuser@app.myserver.com
cd /pub/sas/SASManagementConsole/9.4
./sasmc_console

This returns:

Exception in thread "main" java.lang.InternalError: Can't connect to X11
window server using ':0' as the value of the DISPLAY variable.

What should be the value of my display variable?

Body:
doh..  So it appears I should have used an uppercase X as follows:

ssh -X myuser@app.myserver.com

But there were other things I had to update before the window worked properly.  First, in the following file:

/private/etc/ssh_config

I changed the following values:

#   ForwardX11 no
#   ForwardX11Trusted no

to:

#   ForwardX11 yes
#   ForwardX11Trusted yes

I also ran:

rm /tmp/.X11-unix/X0

And restarted the machine...


问:
Any success stories for JSF, GWT, Wicket or Tapestry on the web?
I am searching for framework references. In other words I am looking for companies, which have successfully implemented a framework solution in java web application environment (success stories). Frameworks I am interested in are JSF, GWT, Wicket and Tapestry. I wasn't able to google any results, nor to find any references at the official sites. At the end I am a bit confused if there are any. Can someone help me out?</p>

答:
mobile.walmart.com, that surely has some serious traffic, is built with Wicket.

One of the reasons to go for Wicket was the complete decoupling of code and markup. The site serves three different kinds of HTML for different classes off mobile devices from the exact same code on the server.

http://www.dzone.com/links/apache_wicket_powers_mobilewalmartcom.html


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
You'll sometimes see this in very old code, from before there was a C standard to spell out that (x > y) evaluates to numeric 1 or 0; some CPUs would rather make that evaluate to −1 or 0 instead, and some very old compilers may have just followed along, so some programmers felt they needed the extra defensiveness.

You'll sometimes also see this because similar expressions don't necessarily evaluate to numeric 1 or 0.  For instance, in

```<code>#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) ? 1 : 0)
</code>```

the inner &-expression evaluates to either 0 or the numeric value of F_DO_GRENFELZ, which is probably not 1, so the ? 1 : 0 serves to canonicalize it.  I personally think it's clearer to write that as

```<code>#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) != 0)
</code>```

but reasonable people can disagree.  If you had a whole bunch of these in a row, testing different kinds of expressions, someone might've decided that it was more maintainable to put ? 1 : 0 on the end of all of them than to worry about which ones actually needed it.

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

Body:
You'll sometimes see this in very old code, from before there was a C standard to spell out that (x > y) evaluates to numeric 1 or 0; some CPUs would rather make that evaluate to −1 or 0 instead, and some very old compilers may have just followed along, so some programmers felt they needed the extra defensiveness.

You'll sometimes also see this because similar expressions don't necessarily evaluate to numeric 1 or 0.  For instance, in

#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) ? 1 : 0)

the inner &-expression evaluates to either 0 or the numeric value of F_DO_GRENFELZ, which is probably not 1, so the ? 1 : 0 serves to canonicalize it.  I personally think it's clearer to write that as

#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) != 0)

but reasonable people can disagree.  If you had a whole bunch of these in a row, testing different kinds of expressions, someone might've decided that it was more maintainable to put ? 1 : 0 on the end of all of them than to worry about which ones actually needed it.


问:
Regular expression to accept only characters (a-z) in a textbox
What is a regular expression that accepts only characters ranging from a to z?</p>

答:
Just for people using bash shell, instead of "+" use "*"

"^[a-zA-Z]*$"


问:
App-Auth Android Example Error in AuthState constructor
I am using the example for AppAuth-Android from this github repository

The gradle configuration I am using is

```<code>compile 'net.openid:appauth:0.5.1'
</code>```

The error thrown is for the lines below:

AuthorizationServiceConfiguration config = new AuthorizationServiceConfiguration(
        mConfiguration.getAuthEndpointUri(),
        mConfiguration.getTokenEndpointUri(),
        mConfiguration.getRegistrationEndpointUri());

mAuthStateManager.replace(new AuthState(config));
```

The error states that AuthState(AuthorizationServiceConfiguration) constructor not defined.

Is the example not updated for the library version or is there any other error.

答: Lead maintainer of AppAuth here - I believe I added that method after the release of 0.5.1, you'll need to wait for the 0.6.0 release to use it.</p>

Body:
I am using the example for AppAuth-Android from this github repository

The gradle configuration I am using is

compile 'net.openid:appauth:0.5.1'

The error thrown is for the lines below:

AuthorizationServiceConfiguration config = new AuthorizationServiceConfiguration(
        mConfiguration.getAuthEndpointUri(),
        mConfiguration.getTokenEndpointUri(),
        mConfiguration.getRegistrationEndpointUri());

mAuthStateManager.replace(new AuthState(config));

The error states that AuthState(AuthorizationServiceConfiguration) constructor not defined.

Is the example not updated for the library version or is there any other error.


问:
What's the point of basis path coverage?
The article at onjava seems to imply that basis path coverage is a sufficient substitute for full path coverage, due to some linear-independence/cyclomatic-complexity magic.

Using an example similar to the article:

```<code>public int returnInput(int x, boolean one, boolean two)
{
    int y = x;
    if(one)
    {
        y = x-1;
    }
    if(two)
    {
        x = y;
    }
    return x;
}
</code>```

with the basis set {FF,TF,FT}, the bug is not exposed. Only the untested TT path would expose it.

So, how is basis path coverage useful? It doesn't seem much better than branch coverage.

答:
My recollection from McCabe's work on this exact subject is: you generate the basis paths systematically, changing one condition at a time, and only changing the last condition, until you can't change any new conditions.

Suppose we start with FF, which is the shortest path. Following the algorithm, we change the last if in the chain, yielding FT. We've covered the second if now, meaning: if there was a bug in the second if, surely our two tests were paying attention to what happened when the second if statement suddenly started executing, otherwise our tests aren't working or our code isn't verifiable. Both possibilities suggest our code needs reworking.

Having covered FT, we go back up one node in the path and change the first T to F. When building basis paths, we only change one condition at a time. So we are forced to leave the second if the same, yielding... TT!

We are left with these basis paths: {FF, FT, TT}. Which address the issue you raised.

But wait, you say, what if the bug occurs in the TF case?? The answer is: we should have already noticed it between two of the other three tests. Think about it:

The second if already had its chance to demonstrate its effect on the code independently any other changes to the execution of the program through the FF and FT tests.

The first if had its chance to demonstrate its independent effect going from FT to TT.

We could have started with the TT case (the longest path). We would have arrived at slightly different basis paths, but they would still exercise each if statement independently.

Notice in your simple example, there is no co-linearity in the conditions of the if statements. Co-linearity cripples basis path generation.

In short: basis path testing, done systematically, avoids the problems you think it has. Basis path testing doesn't tell you how to write verifiable code. (TDD does that.) More to the point, path testing doesn't tell you which assertions you need to make. That's your job as the human.

Source: this is my research area, but I read McCabe's paper on this exact subject a few years back: http://mccabe.com/pdf/mccabe-nist235r.pdf

OwnerDisplayName: ech

Body:
The article at onjava seems to imply that basis path coverage is a sufficient substitute for full path coverage, due to some linear-independence/cyclomatic-complexity magic.

Using an example similar to the article:

public int returnInput(int x, boolean one, boolean two)
{
    int y = x;
    if(one)
    {
        y = x-1;
    }
    if(two)
    {
        x = y;
    }
    return x;
}

with the basis set {FF,TF,FT}, the bug is not exposed. Only the untested TT path would expose it.

So, how is basis path coverage useful? It doesn't seem much better than branch coverage.