问:
After creating a local environment and confirming in Conda list I still get "No module named chainer" error.
I promise I've looked at suggestions for similiar problems but nothing has worked and I have no idea what to do.

Here are my exact steps. I've got Anaconda installed fine and have used it with other libraries and environments like tensorflow, now I'm just trying to use this one package called "chainer". The only windows version I could find was here:
https://anaconda.org/steerapi/chainer

So I went through these steps:

```<code>conda create -n p27 python=2.7
activate p27
</code>```

At this point it was clear I was now in the p27 environment, then I did...

```<code>conda install -c steerapi chainer=0
conda list
</code>```

Then to be safe, while still in the environment I did conda install ipython and conda install jupyter, because I had heard that if these are not installed in the local environment the dependencies might not work when you try to use either of them. I confirmed again with conda list outputting:

```<code># packages in environment at C:\Users\MrMoxie\AppData\Local\conda\conda\envs\py27:
#
backports                 1.0                      py27_0
backports_abc             0.5                      py27_0
bleach                    1.5.0                    py27_0
chainer                   0                        py27_0    steerapi
colorama                  0.3.7                    py27_0
configparser              3.5.0                    py27_0
decorator                 4.0.11                   py27_0
entrypoints               0.2.2                    py27_1
enum34                    1.1.6                    py27_0
filelock                  2.0.4                    py27_0    steerapi
functools32               3.2.3.2                  py27_0
get_terminal_size         1.0.0                    py27_0
html5lib                  0.999                    py27_0
ipykernel                 4.5.2                    py27_0
ipython                   5.3.0                    py27_0
ipython_genutils          0.1.0                    py27_0
jinja2                    2.9.5                    py27_0
jsonschema                2.5.1                    py27_0
jupyter_client            5.0.0                    py27_0
jupyter_core              4.3.0                    py27_0
markupsafe                0.23                     py27_2
mistune                   0.7.3                    py27_0
mkl                       2017.0.1                      0
nbconvert                 5.1.1                    py27_0
nbformat                  4.3.0                    py27_0
notebook                  4.3.1                    py27_1
numpy                     1.12.0                   py27_0
pandocfilters             1.4.1                    py27_0
path.py                   10.1                     py27_0
pathlib2                  2.2.0                    py27_0
pickleshare               0.7.4                    py27_0
pip                       9.0.1                    py27_1
prompt_toolkit            1.0.9                    py27_0
protobuf                  3.0.0a3                  py27_1    steerapi
pygments                  2.2.0                    py27_0
python                    2.7.13                        0
python-dateutil           2.6.0                    py27_0
pyzmq                     16.0.2                   py27_0
scandir                   1.5                      py27_0
setuptools                27.2.0                   py27_1
simplegeneric             0.8.1                    py27_1
singledispatch            3.4.0.3                  py27_0
six                       1.10.0                   py27_0
ssl_match_hostname        3.4.0.2                  py27_1
testpath                  0.3                      py27_0
tornado                   4.4.2                    py27_0
traitlets                 4.3.2                    py27_0
vs2008_runtime            9.00.30729.5054               0
wcwidth                   0.1.7                    py27_0
wheel                     0.29.0                   py27_0
win_unicode_console       0.5                      py27_0
</code>```

Yet even after all that every time in both ipython and in the jupyter notebook (where I prefer to do the coding/testing work) I get:

```<code>import chainer
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-10-9758b185b742> in <module>()
----> 1 import chainer

ImportError: No module named chainer
</code>```

Please help, I've googled as much as I can google and tried every idea I can think of, why why why doesn't it recognize a package installed in this environment as being there?

答:
This is because the modules you installed in this environment are only recognizable by the python kernel installed in the same environment. You need to add the environment as a kernel in jupyter, and then use that kernel in Jupyter notebook to correctly read and import all modules installed in that environment. The easiest way to do this is using ipykernel

After activating the environment, install ipykernel using conda as

```<code>conda install ipykernel
</code>```

You can then create a kernel with the desired python version installed in your environment using -

```<code>/path/to/env/bin/python(version) --name "name-of-kernel" --display-name "Display Name of Kernel" --user(or for whoever you want the kernel to be accessible)*
</code>```

You can view your Jupyter kernels using

```<code>jupyter kernelspec list
</code>```

After this, just select this kernel from jupyter notebook and you are good to go.

Body:
I promise I've looked at suggestions for similiar problems but nothing has worked and I have no idea what to do.

Here are my exact steps. I've got Anaconda installed fine and have used it with other libraries and environments like tensorflow, now I'm just trying to use this one package called "chainer". The only windows version I could find was here:
https://anaconda.org/steerapi/chainer

So I went through these steps:

conda create -n p27 python=2.7
activate p27

At this point it was clear I was now in the p27 environment, then I did...

conda install -c steerapi chainer=0
conda list

Then to be safe, while still in the environment I did conda install ipython and conda install jupyter, because I had heard that if these are not installed in the local environment the dependencies might not work when you try to use either of them. I confirmed again with conda list outputting:

# packages in environment at C:\Users\MrMoxie\AppData\Local\conda\conda\envs\py27:
#
backports                 1.0                      py27_0
backports_abc             0.5                      py27_0
bleach                    1.5.0                    py27_0
chainer                   0                        py27_0    steerapi
colorama                  0.3.7                    py27_0
configparser              3.5.0                    py27_0
decorator                 4.0.11                   py27_0
entrypoints               0.2.2                    py27_1
enum34                    1.1.6                    py27_0
filelock                  2.0.4                    py27_0    steerapi
functools32               3.2.3.2                  py27_0
get_terminal_size         1.0.0                    py27_0
html5lib                  0.999                    py27_0
ipykernel                 4.5.2                    py27_0
ipython                   5.3.0                    py27_0
ipython_genutils          0.1.0                    py27_0
jinja2                    2.9.5                    py27_0
jsonschema                2.5.1                    py27_0
jupyter_client            5.0.0                    py27_0
jupyter_core              4.3.0                    py27_0
markupsafe                0.23                     py27_2
mistune                   0.7.3                    py27_0
mkl                       2017.0.1                      0
nbconvert                 5.1.1                    py27_0
nbformat                  4.3.0                    py27_0
notebook                  4.3.1                    py27_1
numpy                     1.12.0                   py27_0
pandocfilters             1.4.1                    py27_0
path.py                   10.1                     py27_0
pathlib2                  2.2.0                    py27_0
pickleshare               0.7.4                    py27_0
pip                       9.0.1                    py27_1
prompt_toolkit            1.0.9                    py27_0
protobuf                  3.0.0a3                  py27_1    steerapi
pygments                  2.2.0                    py27_0
python                    2.7.13                        0
python-dateutil           2.6.0                    py27_0
pyzmq                     16.0.2                   py27_0
scandir                   1.5                      py27_0
setuptools                27.2.0                   py27_1
simplegeneric             0.8.1                    py27_1
singledispatch            3.4.0.3                  py27_0
six                       1.10.0                   py27_0
ssl_match_hostname        3.4.0.2                  py27_1
testpath                  0.3                      py27_0
tornado                   4.4.2                    py27_0
traitlets                 4.3.2                    py27_0
vs2008_runtime            9.00.30729.5054               0
wcwidth                   0.1.7                    py27_0
wheel                     0.29.0                   py27_0
win_unicode_console       0.5                      py27_0

Yet even after all that every time in both ipython and in the jupyter notebook (where I prefer to do the coding/testing work) I get:

import chainer
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-10-9758b185b742> in <module>()
----> 1 import chainer

ImportError: No module named chainer

Please help, I've googled as much as I can google and tried every idea I can think of, why why why doesn't it recognize a package installed in this environment as being there?

Body:
This is because the modules you installed in this environment are only recognizable by the python kernel installed in the same environment. You need to add the environment as a kernel in jupyter, and then use that kernel in Jupyter notebook to correctly read and import all modules installed in that environment. The easiest way to do this is using ipykernel

After activating the environment, install ipykernel using conda as

conda install ipykernel

You can then create a kernel with the desired python version installed in your environment using -

/path/to/env/bin/python(version) --name "name-of-kernel" --display-name "Display Name of Kernel" --user(or for whoever you want the kernel to be accessible)*

You can view your Jupyter kernels using

jupyter kernelspec list

After this, just select this kernel from jupyter notebook and you are good to go.


来源: stackexchange

问:
How to use Azure Data Factory for importing data incrementally from MySQL to Azure Data Warehouse?
I'm using Azure Data Factory to periodically import data from MySQL to Azure SQL Data Warehouse.

The data goes through a staging blob storage on an Azure storage account, but when I run the pipeline it fails because it can't separate the blob text back to columns. Each row that the pipeline tries to insert into the destination becomes a long string which contains all the column values delimited by a "⯑" character.

I used Data Factory before, without trying the incremental mechanism, and it worked fine. I don't see a reason it would cause such a behavior, but I'm probably missing something.

I'm attaching the JSON that describes the pipeline with some minor naming changes, please let me know if you see anything that can explain this.

Thanks!

EDIT: Adding exception message:

Failed execution Database operation failed. Error message from
  database execution :
  ErrorCode=FailedDbOperation,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Error
  happened when loading data into SQL Data
  Warehouse.,Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Data.SqlClient.SqlException,Message=Query
  aborted-- the maximum reject threshold (0 rows) was reached while
  reading from an external source: 1 rows rejected out of total 1 rows
  processed.
  (/f4ae80d1-4560-4af9-9e74-05de941725ac/Data.8665812f-fba1-407a-9e04-2ee5f3ca5a7e.txt)
             Column ordinal: 27, Expected data type: VARCHAR(45) collate SQL_Latin1_General_CP1_CI_AS, Offending value:* ROW OF VALUES
  * (Tokenization failed), Error: Not enough columns in this
  line.,},],'.

```<code>{
"name": "CopyPipeline-move_incremental_test",
"properties": {
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "RelationalSource",
                    "query": "$$Text.Format('select * from [table] where InsertTime >= \\'{0:yyyy-MM-dd HH:mm}\\' AND InsertTime < \\'{1:yyyy-MM-dd HH:mm}\\'', WindowStart, WindowEnd)"
                },
                "sink": {
                    "type": "SqlDWSink",
                    "sqlWriterCleanupScript": "$$Text.Format('delete [schema].[table] where [InsertTime] >= \\'{0:yyyy-MM-dd HH:mm}\\' AND [InsertTime] <\\'{1:yyyy-MM-dd HH:mm}\\'', WindowStart, WindowEnd)",
                    "allowPolyBase": true,
                    "polyBaseSettings": {
                        "rejectType": "Value",
                        "rejectValue": 0,
                        "useTypeDefault": true
                    },
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                },
                "translator": {
                    "type": "TabularTranslator",
                    "columnMappings": "column1:column1,column2:column2,column3:column3"
                },
                "enableStaging": true,
                "stagingSettings": {
                    "linkedServiceName": "StagingStorage-somename",
                    "path": "somepath"
                }
            },
            "inputs": [
                {
                    "name": "InputDataset-input"
                }
            ],
            "outputs": [
                {
                    "name": "OutputDataset-output"
                }
            ],
            "policy": {
                "timeout": "1.00:00:00",
                "concurrency": 10,
                "style": "StartOfInterval",
                "retry": 3,
                "longRetry": 0,
                "longRetryInterval": "00:00:00"
            },
            "scheduler": {
                "frequency": "Hour",
                "interval": 1
            },
            "name": "Activity-0-_Custom query_->[schema]_[table]"
        }
    ],
    "start": "2017-06-01T05:29:12.567Z",
    "end": "2099-12-30T22:00:00Z",
    "isPaused": false,
    "hubName": "datafactory_hub",
    "pipelineMode": "Scheduled"
}
</code>```

}

答:
It sounds like what your doing is right, but the data is poorly formed (common problem, none UTF-8 encoding) so ADF can't parse the structure as you require. When I encounter this I often have to add a custom activity to the pipeline that cleans and prepares the data so it can then be used in a structured way by downstream activities. Unfortunately this is a big be overhead in the development of the solution and will require you to write a C# class to deal with the data transformation.

Also remember ADF has none of its own compute, it only invokes other services, so you'll also need an Azure Batch Service to execute to compiled code.

Sadly there is no magic fix here. Azure is great to Extract and Load your perfectly structured data, but in the real world we need other services to do the Transform or Cleaning meaning we need a pipeline that can ETL or I prefer ECTL.

Here's a link on create ADF custom activities to get you started: https://www.purplefrogsystems.com/paul/2016/11/creating-azure-data-factory-custom-activities/

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm using Azure Data Factory to periodically import data from MySQL to Azure SQL Data Warehouse.

The data goes through a staging blob storage on an Azure storage account, but when I run the pipeline it fails because it can't separate the blob text back to columns. Each row that the pipeline tries to insert into the destination becomes a long string which contains all the column values delimited by a "⯑" character.

I used Data Factory before, without trying the incremental mechanism, and it worked fine. I don't see a reason it would cause such a behavior, but I'm probably missing something.

I'm attaching the JSON that describes the pipeline with some minor naming changes, please let me know if you see anything that can explain this.

Thanks!

EDIT: Adding exception message:

Failed execution Database operation failed. Error message from
  database execution :
  ErrorCode=FailedDbOperation,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Error
  happened when loading data into SQL Data
  Warehouse.,Source=Microsoft.DataTransfer.ClientLibrary,''Type=System.Data.SqlClient.SqlException,Message=Query
  aborted-- the maximum reject threshold (0 rows) was reached while
  reading from an external source: 1 rows rejected out of total 1 rows
  processed.
  (/f4ae80d1-4560-4af9-9e74-05de941725ac/Data.8665812f-fba1-407a-9e04-2ee5f3ca5a7e.txt)
             Column ordinal: 27, Expected data type: VARCHAR(45) collate SQL_Latin1_General_CP1_CI_AS, Offending value:* ROW OF VALUES
  * (Tokenization failed), Error: Not enough columns in this
  line.,},],'.

{
"name": "CopyPipeline-move_incremental_test",
"properties": {
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "RelationalSource",
                    "query": "$$Text.Format('select * from [table] where InsertTime >= \\'{0:yyyy-MM-dd HH:mm}\\' AND InsertTime < \\'{1:yyyy-MM-dd HH:mm}\\'', WindowStart, WindowEnd)"
                },
                "sink": {
                    "type": "SqlDWSink",
                    "sqlWriterCleanupScript": "$$Text.Format('delete [schema].[table] where [InsertTime] >= \\'{0:yyyy-MM-dd HH:mm}\\' AND [InsertTime] <\\'{1:yyyy-MM-dd HH:mm}\\'', WindowStart, WindowEnd)",
                    "allowPolyBase": true,
                    "polyBaseSettings": {
                        "rejectType": "Value",
                        "rejectValue": 0,
                        "useTypeDefault": true
                    },
                    "writeBatchSize": 0,
                    "writeBatchTimeout": "00:00:00"
                },
                "translator": {
                    "type": "TabularTranslator",
                    "columnMappings": "column1:column1,column2:column2,column3:column3"
                },
                "enableStaging": true,
                "stagingSettings": {
                    "linkedServiceName": "StagingStorage-somename",
                    "path": "somepath"
                }
            },
            "inputs": [
                {
                    "name": "InputDataset-input"
                }
            ],
            "outputs": [
                {
                    "name": "OutputDataset-output"
                }
            ],
            "policy": {
                "timeout": "1.00:00:00",
                "concurrency": 10,
                "style": "StartOfInterval",
                "retry": 3,
                "longRetry": 0,
                "longRetryInterval": "00:00:00"
            },
            "scheduler": {
                "frequency": "Hour",
                "interval": 1
            },
            "name": "Activity-0-_Custom query_->[schema]_[table]"
        }
    ],
    "start": "2017-06-01T05:29:12.567Z",
    "end": "2099-12-30T22:00:00Z",
    "isPaused": false,
    "hubName": "datafactory_hub",
    "pipelineMode": "Scheduled"
}

}


问:
How to add key with unique random value in HTTP Request defaults in Jmeter
I am trying to apply load  sample request is like

http://54.174.110.64:8080/adserver/html5/inwapads/?adFormat=preappvideo&ak=O4DCX2&version=1.0&adu=5&cb=1494853894218&output=vast&priority=1&size=[vdo_adSize]&pageURL=http://qa.vdopia.com/qa/Ruchi/ssp_preroll1.html?0.7888977&domain=vdopia.com&refURL=&category=[CATEGORY]&siteName=vdopia&displayManager=Vdopia-SPP-Web&di=[COOKIE_ID]&dif=fpcm&sex=[GENDER]&age=[AGE];ipAddress=203.122.9.130;di=abcdefghijklmn

I have single request, what I want is that same request should have unique di (last key in query param). Nothing else I want to change.

My test is based on unique di in request keeping other parameters constant.

答:
I have used below approach :

ad di=${di_random}in path of HTTP request


问:
Getting error in passing date value in ajax request
I am trying to pass a Datein ajax request here is my ajax call
I am getting value of Date06/13/2017

```<code>$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + Date,
                cache: false
            }).done(function (response) {

            });
</code>```

and here is my controller

```<code>[HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {
            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }
</code>```

but i am getting this error

```<code>**http://localhost:54850/api/ServiceProvider/GetUpdatedPrice/06/13/2017 404 (Not Found)**
</code>```

does I have to pass date in JSON format or any other thing i am missing ?
please help.

答:
this is happend because date formated in dd/mm/y in / formate</p>

```<code>$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();
            var newdate = Date.replace("/", "_");

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + newdate,
                cache: false
            }).done(function (response) {

            });

            [HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {

    //  again replace date from '_' to '/'

            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }
</code>```

Body:
I am trying to pass a Datein ajax request here is my ajax call
I am getting value of Date06/13/2017

$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + Date,
                cache: false
            }).done(function (response) {

            });

and here is my controller

[HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {
            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }

but i am getting this error

**http://localhost:54850/api/ServiceProvider/GetUpdatedPrice/06/13/2017 404 (Not Found)**

does I have to pass date in JSON format or any other thing i am missing ?
please help.

Body:
this is happend because date formated in dd/mm/y in / formate

$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();
            var newdate = Date.replace("/", "_");

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + newdate,
                cache: false
            }).done(function (response) {

            });

            [HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {

    //  again replace date from '_' to '/'

            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }


问:
PHP form can't be updated
I am currently making a system for a client database management. There are four tables in mySQL for this system, which are; admin, staff, client, and project. The project table has one foreign key from the client table, which is the clientid.

Now, I have made forms for all these tables so that the user can input the data into them. Weirdly, the only form that can be updated successfully is the staff one. Both the client and project forms cannot be updated at all. It returns as successful, but the data are not altered.

Below is the staff update code.

```<code>    <?php
    include 'database.php';

    $staffid = $_GET['staffid'];
    $sql = "SELECT * FROM staff WHERE staffid='$staffid'";
    $result = mysqli_query($conn,$sql);

    while ($row=mysqli_fetch_array($result)){
      $staffname = $row['staffname'];
      $staffemail = $row['staffemail'];
      $staffphone = $row['staffphone'];
    }

   if(isset($_POST['submit'])){
     $staffname = $_POST['staffname'];
     $staffemail = $_POST['staffemail'];
     $staffphone = $_POST['staffphone'];

   $sql = "UPDATE staff SET

    staffname='$staffname',staffemail='$staffemail',staffphone='$staffphone'  WHERE staffid='$staffid'";

    $result = mysqli_query($conn,$sql);

    if($result){
        echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
    }
    else {
        echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
    }
}
?>

<form action="" method="post">
<table class ="table1">
<tr>
<td>Staff Name:</td> <td><input type="text" name="staffname" size="50" value="<?php echo $staffname;?>"></td>
</tr>

<tr>
<td>Staff Email:</td> <td><input type="text" name="staffemail" size="50" value="<?php echo $staffemail;?>"></td>
</tr>

<tr>
<td>Staff Phone No:</td> <td><input type="text" name="staffphone" size="50" value="<?php echo $staffphone;?>"></td>
</tr>

<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewstaff.php"'></td>
</table>
</form>
</code>```

Okay now is the update code for the client table.

```<code><?php
include 'database.php';

$clientid = $_GET['clientid'];
$sql = "SELECT * FROM client WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());

while ($row=mysqli_fetch_array($result)){
    $clientid = $row['clientid'];
    $clientname = $row['clientname'];
    $clientno = $row['clientno'];
    $clientemail = $row['clientemail'];
    $clientadd = $row['clientadd'];
}

if(isset($_POST['submit'])){
    $clientid = $row['clientid'];
    $clientname = $row['clientname'];
    $clientno = $row['clientno'];
    $clientemail = $row['clientemail'];
    $clientadd = $row['clientadd'];

    $sql = "UPDATE client SET clientid='$clientid',clientname='$clientname',clientno='$clientno',clientemail='$clientemail',clientadd='$clientadd' WHERE clientid='$clientid'";

    $result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());

    if($result){
        echo "<table><td><tr><h4>Record has been updated successfully!<br></tr></td></h4></table>";
    }
    else {
        echo "<h4>Record has <b>NOT</b> been updated successfully<br></h4>";
    }
}
?>

<form action="" method="post">
<table class ="table1">
<tr>
<td>Client ID:</td> <td><input type="text" name="clientid" size="50" value="<?php echo $clientid;?>"></td>
</tr>

<tr>
<td>Client Name:</td> <td><input type="text" name="clientname" size="50" value="<?php echo $clientname;?>"></td>
</tr>

<tr>
<td>Client Phone No.:</td> <td><input type="text" name="clientno" size="50" value="<?php echo $clientno;?>"></td>
</tr>

<tr>
<td>Client Email:</td> <td><input type="text" name="clientemail" size="50" value="<?php echo $clientemail;?>"></td>
</tr>

<tr>
<td>Client Address:</td> <td><input type="text" name="clientadd" size="50" value="<?php echo $clientadd;?>"></td>
</tr>

<td><input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewclient.php"'></td>
</table>
</form>
</code>```

Maybe I'm stupid or what but I've been trying to figure out the problem for 3 hours and I'm this close to crying lol. Been reading all the threads here about updating form but still, no answer. Hope that anyone here could help me. Thank you.

答:
The code you use for the client table update uses this code:

```<code>if(isset($_POST['submit'])){
    $clientid = $row['clientid'];       // $row should be $_POST
    $clientname = $row['clientname'];   // $row should be $_POST
    $clientno = $row['clientno'];       // $row should be $_POST
    $clientemail = $row['clientemail']; // $row should be $_POST
    $clientadd = $row['clientadd'];     // $row should be $_POST
</code>```

But those $rows should be $_POST, else the updated data will be the same as the previous data (since $row is the result from the query SELECT * FROM client WHERE clientid='$clientid'). You do it correctly in the staff table update code:

```<code> if(isset($_POST['submit'])){
     $staffname = $_POST['staffname'];
     $staffemail = $_POST['staffemail'];
     $staffphone = $_POST['staffphone'];
</code>```

Please note that your your script is at risk of SQL Injection Attack. Have a look at what happened to Little Bobby Tables. Even if you are escaping inputs, its not safe!. Use prepared parameterized statements instead.

Title: PHP form can't be updated

Body:
I am currently making a system for a client database management. There are four tables in mySQL for this system, which are; admin, staff, client, and project. The project table has one foreign key from the client table, which is the clientid.

Now, I have made forms for all these tables so that the user can input the data into them. Weirdly, the only form that can be updated successfully is the staff one. Both the client and project forms cannot be updated at all. It returns as successful, but the data are not altered.

Below is the staff update code.

    <?php
    include 'database.php';

    $staffid = $_GET['staffid'];
    $sql = "SELECT * FROM staff WHERE staffid='$staffid'";
    $result = mysqli_query($conn,$sql);

    while ($row=mysqli_fetch_array($result)){
      $staffname = $row['staffname'];
      $staffemail = $row['staffemail'];
      $staffphone = $row['staffphone'];
    }

   if(isset($_POST['submit'])){
     $staffname = $_POST['staffname'];
     $staffemail = $_POST['staffemail'];
     $staffphone = $_POST['staffphone'];

   $sql = "UPDATE staff SET

    staffname='$staffname',staffemail='$staffemail',staffphone='$staffphone'  WHERE staffid='$staffid'";

    $result = mysqli_query($conn,$sql);

    if($result){
        echo "

Record has been updated successfully!

";
    }
    else {
        echo "
Record has NOT been updated successfully

";
    }
}
?>

<form action="" method="post">

Staff Name:	 <input type="text" name="staffname" size="50" value="<?php echo $staffname;?>">

Staff Email:	 <input type="text" name="staffemail" size="50" value="<?php echo $staffemail;?>">

Staff Phone No:	 <input type="text" name="staffphone" size="50" value="<?php echo $staffphone;?>">

<input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewstaff.php"'>

</form>

Okay now is the update code for the client table.

<?php
include 'database.php';

$clientid = $_GET['clientid'];
$sql = "SELECT * FROM client WHERE clientid='$clientid'";
$result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());

while ($row=mysqli_fetch_array($result)){
    $clientid = $row['clientid'];
    $clientname = $row['clientname'];
    $clientno = $row['clientno'];
    $clientemail = $row['clientemail'];
    $clientadd = $row['clientadd'];
}

if(isset($_POST['submit'])){
    $clientid = $row['clientid'];
    $clientname = $row['clientname'];
    $clientno = $row['clientno'];
    $clientemail = $row['clientemail'];
    $clientadd = $row['clientadd'];

    $sql = "UPDATE client SET clientid='$clientid',clientname='$clientname',clientno='$clientno',clientemail='$clientemail',clientadd='$clientadd' WHERE clientid='$clientid'";

    $result = mysqli_query($conn,$sql) or die ("Error in query: $query. ".mysqli_error());

    if($result){
        echo "

Record has been updated successfully!

";
    }
    else {
        echo "
Record has NOT been updated successfully

";
    }
}
?>

<form action="" method="post">

Client ID:	 <input type="text" name="clientid" size="50" value="<?php echo $clientid;?>">

Client Name:	 <input type="text" name="clientname" size="50" value="<?php echo $clientname;?>">

Client Phone No.:	 <input type="text" name="clientno" size="50" value="<?php echo $clientno;?>">

Client Email:	 <input type="text" name="clientemail" size="50" value="<?php echo $clientemail;?>">

Client Address:	 <input type="text" name="clientadd" size="50" value="<?php echo $clientadd;?>">

<input type="submit" value="Update" name="submit"> <input type="button" value="View" name="view" onclick='location.href="viewclient.php"'>

</form>

Maybe I'm stupid or what but I've been trying to figure out the problem for 3 hours and I'm this close to crying lol. Been reading all the threads here about updating form but still, no answer. Hope that anyone here could help me. Thank you.

Body:
The code you use for the client table update uses this code:

if(isset($_POST['submit'])){
    $clientid = $row['clientid'];       // $row should be $_POST
    $clientname = $row['clientname'];   // $row should be $_POST
    $clientno = $row['clientno'];       // $row should be $_POST
    $clientemail = $row['clientemail']; // $row should be $_POST
    $clientadd = $row['clientadd'];     // $row should be $_POST

But those $rows should be $_POST, else the updated data will be the same as the previous data (since $row is the result from the query SELECT * FROM client WHERE clientid='$clientid'). You do it correctly in the staff table update code:

 if(isset($_POST['submit'])){
     $staffname = $_POST['staffname'];
     $staffemail = $_POST['staffemail'];
     $staffphone = $_POST['staffphone'];

Please note that your your script is at risk of SQL Injection Attack. Have a look at what happened to Little Bobby Tables. Even if you are escaping inputs, its not safe!. Use prepared parameterized statements instead.


问:
Jquery Datatable in Angular 2 Application
I'm trying to import Metronic datatable in my angular 2 app, I import all the script and reference (with the html tag  and <link>) in the main html page, the same where I initialize angular 2 (with System.import()..), but it don't work, it show me the table without the search/reordering feature.
Any advice? How can I import these in angular 2?
Thanks in advance

```<code><script src="/core-js/client/shim.min.js"></script>
<script src="/zone.js/dist/zone.js"></script>
<script src="/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
    System.import('main.js').catch(function(err){ console.error(err); });
</script>

<link href="/theme2/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="/theme2/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />

<script src="/theme2/global/scripts/datatable.js" type="text/javascript"></script>
<script src="/theme2/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="/theme2/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
</code>```

答:
Try to import library in .angular-cli.json file

```<code>{
"scripts": [/themes/..*.js],
}
</code>```

Also , make sure if the library can be installed using npm install package.

Body:
I'm trying to import Metronic datatable in my angular 2 app, I import all the script and reference (with the html tag  and <link>) in the main html page, the same where I initialize angular 2 (with System.import()..), but it don't work, it show me the table without the search/reordering feature.
Any advice? How can I import these in angular 2?
Thanks in advance

<link href="/theme2/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="/theme2/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />

Body:
Try to import library in .angular-cli.json file

{
"scripts": [/themes/..*.js],
}

Also , make sure if the library can be installed using npm install package.


问:
oracle sql query error while comparing date columns
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.</p>

```<code>select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'
</code>```

答: select * from tbltlcrconfighistory where TO_DATE(STARTDATE,'dd-mon-yyyy') = TO_DATE('14-dec-2010','dd-mon-yyyy');</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.

select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'


问:
Google map not showing in android activity?
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

```<code>public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
</code>```

Here is the xml for the content of the main activity which holds the google map fragment:

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>
</code>```

Here is the manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>
</code>```

答:
You need to enable google map api from google console for your project. And also you need to download json file from the console.

1. Go to google console

2. click on your project.

3. Click on library section from left menu panel. see below image

In google maps api, click on Google maps android api

Than enable that.

Now Goto firebase console

Click on your project and goto project settings and download the json file.

Add that json file in your application.

Body:
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

Here is the xml for the content of the main activity which holds the google map fragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>

Here is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>


问:
Between Date function MM/DD/YYYY Mysql
I'm trying to get all the records between two dates. However, I'm getting only record with 1 date only. My date structure is Varchar(20).

Here's my query:

Can you help me with this? :(

```<code>SELECT a.DOB as `DATE`,
       (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
             else 'AM' END) as Shift,
       concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
       a.Amount as DECLARED,
       SUM(c.Amount) as CALCULATED,
       a.AMOUNT as `NET OF SPECIAL SALES`,
       d.Amount as `CASH OVER SHORT`,
       a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
and (a.DOB BETWEEN '5/1/2017' AND '5/19/2017')
GROUP BY b.ID
</code>```

答:
If your DOB column really be text, then you should seriously consider switching that column to a date type.  That being said, if you must proceed as is, you can leverage MySQL's STR_TO_DATE() function, which can convert your text dates into actual date types.  Then, use the same BETWEEN comparison.  Note also that I replaced your incorrect mm/DD/YYYY date literals with ANSI compliant literals of then form YYYY/mm/DD.

```<code>WHERE
    STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-19'
</code>```

Title: Between Date function MM/DD/YYYY Mysql

Body:
I'm trying to get all the records between two dates. However, I'm getting only record with 1 date only. My date structure is Varchar(20).

Here's my query:

Can you help me with this? :(

SELECT a.DOB as `DATE`,
       (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
             else 'AM' END) as Shift,
       concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
       a.Amount as DECLARED,
       SUM(c.Amount) as CALCULATED,
       a.AMOUNT as `NET OF SPECIAL SALES`,
       d.Amount as `CASH OVER SHORT`,
       a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
and (a.DOB BETWEEN '5/1/2017' AND '5/19/2017')
GROUP BY b.ID

Body:
If your DOB column really be text, then you should seriously consider switching that column to a date type.  That being said, if you must proceed as is, you can leverage MySQL's STR_TO_DATE() function, which can convert your text dates into actual date types.  Then, use the same BETWEEN comparison.  Note also that I replaced your incorrect mm/DD/YYYY date literals with ANSI compliant literals of then form YYYY/mm/DD.

WHERE
    STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-19'


问:
Charles proxy HTTPS in Linux
I launch Charles 4.1.2 on my Linux Mint and try to map remote HTTPS request. So, I generated an SSL key like in that article
http://codeblog.shape.dk/blog/2014/01/06/custom-ssl-certificate-with-charles-web-proxy/
and added it to the SSL Proxy client and root certificates
(Charles proxY: rewrite on https does not work). But it still doesn't work.

```<code>Error code: SEC_ERROR_UNKNOWN_ISSUER
</code>```

I'm also added this certificate to the Mozilla certifications and enabled that site in always trusted

答: It repairs by re-adding the certificate</p>

Title: Charles proxy HTTPS in Linux

Body:
I launch Charles 4.1.2 on my Linux Mint and try to map remote HTTPS request. So, I generated an SSL key like in that article
http://codeblog.shape.dk/blog/2014/01/06/custom-ssl-certificate-with-charles-web-proxy/
and added it to the SSL Proxy client and root certificates
(Charles proxY: rewrite on https does not work). But it still doesn't work.

Error code: SEC_ERROR_UNKNOWN_ISSUER

I'm also added this certificate to the Mozilla certifications and enabled that site in always trusted

Body: It repairs by re-adding the certificate


问:
getter always returns 0
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

```<code>public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}
</code>```

答:
I'm also still new but try this:</p>

```<code>public int drawLoop() {
        while (draws < computerCanDraw) {
                int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                randomCard = (cards[new Random().nextInt(cards.length)]);
                computerSumCards += randomCard;

        }
        return computerSumCards;
}

public int getComputerSumCards() {
        return drawLoop();
}
</code>```

Title: getter always returns 0

Body:
I'm new to java coding, so sorry for the beginner question. I'm pretty sure I'm overlooking something easy but I couldn't find a solution in earlier topics.

I'm trying to build an object "computerDraw". When I create a new "computerDraw" I want the computer to decide whether he pulls 1, 2 or 3 numbers out of the int array. The numbers are pulled out random.

The numbers that are drawn should be stored in the variable "computerSumCards".

I created a getter to return computerSumCards but it returns "0" every time.

I can't figure out why that is. Thanks for the help!

public class computerDraw {
    int computerSumCards;
    int getAmountOfComputerCards;
    int randomCard;
    int draws = 0;

    private int[] possibleDraws = {1, 2, 3};
    int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);

    public void drawLoop() {
            while (draws < computerCanDraw) {
                    int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                    randomCard = (cards[new Random().nextInt(cards.length)]);
                    computerSumCards += randomCard;

            }
    }

    public int getComputerSumCards() {
            return computerSumCards;
    }

    public int getAmountOfComputerCards() {
            getAmountOfComputerCards = draws;
            return getAmountOfComputerCards;
    }
}

Body:
I'm also still new but try this:

public int drawLoop() {
        while (draws < computerCanDraw) {
                int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
                randomCard = (cards[new Random().nextInt(cards.length)]);
                computerSumCards += randomCard;

        }
        return computerSumCards;
}

public int getComputerSumCards() {
        return drawLoop();
}


问:
How to read Data from a TBlobField using ADO in Delphi?
I was trying to read data from a TBlobField using TADOBlobStream. I wrote the following function

```<code>function DecompressBlobFieldCustom(AField:TBlobField):String;
    var
      BLOBStream:TADOBlobStream;
      Size:Integer;
    begin
      BLOBStream:= TADOBlobStream.Create(AField,bmRead);
      Size:= BLOBStream.Size;
      BLOBStream.Read(Result,Size);
    end;
</code>```

and i use the function as follows

```<code> Data := DecompressBlobFieldCustom(FldImage);
</code>```

But when i try to do if Length(Data) > 0 then i am getting Access violation at address XXXX error. I couldn't figure out the problem. Please Help.

答:
Result is a string type, but a blob stream operates on byte arrays. It is usually a mistake to try to treat a byte array as though it were a string. Furthermore, you did not allocate a buffer into which to read, which is the actual cause of the error.

Read into a byte array like this:

```<code>function ReadBlobField(Field: TBlobField): TBytes;
var
  Stream: TStream;
begin
  Stream := TADOBlobStream.Create(Field, bmRead);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size>0 then
      Stream.ReadBuffer(Result[0], Stream.Size);
  finally
    Stream.Free;
  end;
end;
</code>```

It is preferable to use the CreateBlobStream method of TDataSet to create blob streams, as discussed in the documentation. So the code would be better like this:

```<code>function ReadBlobField(DataSet: TDataSet; Field: TField): TBytes;
var
  Stream: TStream;
begin
  Stream := DataSet.CreateBlobStream(Field, bmRead);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size>0 then
      Stream.ReadBuffer(Result[0], Stream.Size);
  finally
    Stream.Free;
  end;
end;
</code>```

I've assumed that the data really is a byte array and is not holding text. The fact that it is held in a blob suggests that, as does the mention of decompression and images.

Some other comments:

You must destroy the stream when you are finished with it.

It is generally preferable to use ReadBuffer rather than Read because ReadBuffer raises an exception if the requested number of bytes are not read.

Body:
I was trying to read data from a TBlobField using TADOBlobStream. I wrote the following function

function DecompressBlobFieldCustom(AField:TBlobField):String;
    var
      BLOBStream:TADOBlobStream;
      Size:Integer;
    begin
      BLOBStream:= TADOBlobStream.Create(AField,bmRead);
      Size:= BLOBStream.Size;
      BLOBStream.Read(Result,Size);
    end;

and i use the function as follows

 Data := DecompressBlobFieldCustom(FldImage);

But when i try to do if Length(Data) > 0 then i am getting Access violation at address XXXX error. I couldn't figure out the problem. Please Help.

Body:
Result is a string type, but a blob stream operates on byte arrays. It is usually a mistake to try to treat a byte array as though it were a string. Furthermore, you did not allocate a buffer into which to read, which is the actual cause of the error.

Read into a byte array like this:

function ReadBlobField(Field: TBlobField): TBytes;
var
  Stream: TStream;
begin
  Stream := TADOBlobStream.Create(Field, bmRead);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size>0 then
      Stream.ReadBuffer(Result[0], Stream.Size);
  finally
    Stream.Free;
  end;
end;

It is preferable to use the CreateBlobStream method of TDataSet to create blob streams, as discussed in the documentation. So the code would be better like this:

function ReadBlobField(DataSet: TDataSet; Field: TField): TBytes;
var
  Stream: TStream;
begin
  Stream := DataSet.CreateBlobStream(Field, bmRead);
  try
    SetLength(Result, Stream.Size);
    if Stream.Size>0 then
      Stream.ReadBuffer(Result[0], Stream.Size);
  finally
    Stream.Free;
  end;
end;

I've assumed that the data really is a byte array and is not holding text. The fact that it is held in a blob suggests that, as does the mention of decompression and images.

Some other comments:

You must destroy the stream when you are finished with it.

It is generally preferable to use ReadBuffer rather than Read because ReadBuffer raises an exception if the requested number of bytes are not read.


问:
Why my ASP.NET Core C# Application automatically logout after 10 to 15 min?
I have made a C# Asp.net Core application it's working fine. But problem is that it will automatically logout user after 10 to 20 minutes or after one operation is over then automatically user logout from the system.

I am using Azure database.

答:
Most login schemes on .NET CORE use CookieAuthentication somehow. Most likely your problem lies there.
If you check out the documentation about cookie authentication, you'll see that you can set a timespan for which the cookie should be valid.

cookie options

```<code>app.UseCookieAuthentication(options =>
{
   options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});
</code>```

Should fix your problem.

You can also make it "sliding", that means your cookie will get extended when half of the timespan has passed and the user makes a new request.

Body:
Most login schemes on .NET CORE use CookieAuthentication somehow. Most likely your problem lies there.
If you check out the documentation about cookie authentication, you'll see that you can set a timespan for which the cookie should be valid.

cookie options

app.UseCookieAuthentication(options =>
{
   options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});

Should fix your problem.

You can also make it "sliding", that means your cookie will get extended when half of the timespan has passed and the user makes a new request.


问:
uninformative error using boost::iterator_adaptor
I am trying to wrap a istream with boost's progress_display using boost::iterator_adaptor. What I have written is

```<code>class ifstreamWithProgress: public boost::iterator_adaptor <
  ifstreamWithProgress,
  char*,
  boost::use_default,
    boost::forward_traversal_tag > {
public:
//  ifstreamWithProgress(const char* fname_) {}
  ifstreamWithProgress(): iter(std::istream_iterator<char>()), pd(0)
  {}

  ifstreamWithProgress(const std::string& fname_): fname(fname_), fsize(0), pd(fsize) {
    std::ifstream file(fname.c_str(), std::ios::binary);
    fsize = file.tellg();
    file.seekg(0, std::ios::end);
    fsize = file.tellg() -  fsize;
    file.seekg(0, std::ios::beg);
    iter = std::istream_iterator<char>(file);
    pd.restart(fsize);
  }

  ~ifstreamWithProgress() {
    while( ++pd < fsize);
  }

  const std::istream_iterator<char> getRawIstream() const {
    return iter;
  }

private:
  std::string fname;
  friend class boost::iterator_core_access;
  std::istream_iterator<char> iter;
  std::streampos fsize;
  progress_display pd;

  void increments() {
    iter++;
    ++pd;
  }

  bool equal(const ifstreamWithProgress& rhs) const {
    return this->iter == rhs.getRawIstream();
  }
};
</code>```

This compiles. However when I started to do something like

```<code>  ifstreamWithProgress is("data.txt");
  ifstreamWithProgress eos;
  is != eos;
</code>```

I get a compile time error saying that it is not copyable. This makes some sense because the display class is derived from boost::noncopyable. However what I do not get is where the copying occurs. Any pointers?

PS: the error message is

```<code>1>c:\users\leon.sit\documents\myprojects\c++\general_models\phoenixdsm\phx\fileProgressBarWrapper.hpp(58) : error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in class 'boost::noncopyable_::noncopyable'
1>        C:\Program Files\boost\boost_1_44\boost/noncopyable.hpp(27) : see declaration of 'boost::noncopyable_::noncopyable::noncopyable'
1>        C:\Program Files\boost\boost_1_44\boost/noncopyable.hpp(22) : see declaration of 'boost::noncopyable_::noncopyable'
1>        This diagnostic occurred in the compiler generated function 'ifstreamWithProgress::ifstreamWithProgress(const ifstreamWithProgress &)'
</code>```

which does not point to anywhere in source. However it compiles after commenting the comparison line.

答:
Copying doesn't have to occur anywhere to produce this error. It is a simple reflection of the fact that the compiler must generate a copy constructor. But to do it, it has to copy progress_display as well, which is impossible, since the copy constructor of the latter is private.

You can work around by declaring a pointer to the progress_display member and defining your own copy constructor and = operator. For example:

```<code>class ifstreamWithProgress: public boost::iterator_adaptor <
  ifstreamWithProgress,
  char*,
  boost::use_default,
    boost::forward_traversal_tag > {
public:
  ifstreamWithProgress() : pd(0) {
    pd = new progress_display(...);
  }

  ifstreamWithProgress::ifstreamWithProgress(const ifstreamWithProgress &r) : pd(0) {
    pd = new progress_display(...);
  }

  ~ifstreamWithProgress() {
    if (0 != pd) {
      delete pd;
    }
  }

  ifstreamWithProgress& operator= (const ifstreamWithProgress &r) {
    if (0 != pd) {
      delete pd;
    }
    pd = new progress_display(...);
    return *this;
  }

private:
  progress_display *pd;
};
</code>```

Or you can use shared_ptr<progress_display>.

Body:
I am trying to wrap a istream with boost's progress_display using boost::iterator_adaptor. What I have written is

class ifstreamWithProgress: public boost::iterator_adaptor <
  ifstreamWithProgress,
  char*,
  boost::use_default,
    boost::forward_traversal_tag > {
public:
//  ifstreamWithProgress(const char* fname_) {}
  ifstreamWithProgress(): iter(std::istream_iterator<char>()), pd(0)
  {}

  ifstreamWithProgress(const std::string& fname_): fname(fname_), fsize(0), pd(fsize) {
    std::ifstream file(fname.c_str(), std::ios::binary);
    fsize = file.tellg();
    file.seekg(0, std::ios::end);
    fsize = file.tellg() -  fsize;
    file.seekg(0, std::ios::beg);
    iter = std::istream_iterator<char>(file);
    pd.restart(fsize);
  }

  ~ifstreamWithProgress() {
    while( ++pd < fsize);
  }

  const std::istream_iterator<char> getRawIstream() const {
    return iter;
  }

private:
  std::string fname;
  friend class boost::iterator_core_access;
  std::istream_iterator<char> iter;
  std::streampos fsize;
  progress_display pd;

  void increments() {
    iter++;
    ++pd;
  }

  bool equal(const ifstreamWithProgress& rhs) const {
    return this->iter == rhs.getRawIstream();
  }
};

This compiles. However when I started to do something like

  ifstreamWithProgress is("data.txt");
  ifstreamWithProgress eos;
  is != eos;

I get a compile time error saying that it is not copyable. This makes some sense because the display class is derived from boost::noncopyable. However what I do not get is where the copying occurs. Any pointers?

PS: the error message is

1>c:\users\leon.sit\documents\myprojects\c++\general_models\phoenixdsm\phx\fileProgressBarWrapper.hpp(58) : error C2248: 'boost::noncopyable_::noncopyable::noncopyable' : cannot access private member declared in class 'boost::noncopyable_::noncopyable'
1>        C:\Program Files\boost\boost_1_44\boost/noncopyable.hpp(27) : see declaration of 'boost::noncopyable_::noncopyable::noncopyable'
1>        C:\Program Files\boost\boost_1_44\boost/noncopyable.hpp(22) : see declaration of 'boost::noncopyable_::noncopyable'
1>        This diagnostic occurred in the compiler generated function 'ifstreamWithProgress::ifstreamWithProgress(const ifstreamWithProgress &)'

which does not point to anywhere in source. However it compiles after commenting the comparison line.

Body:
Copying doesn't have to occur anywhere to produce this error. It is a simple reflection of the fact that the compiler must generate a copy constructor. But to do it, it has to copy progress_display as well, which is impossible, since the copy constructor of the latter is private.

You can work around by declaring a pointer to the progress_display member and defining your own copy constructor and = operator. For example:

class ifstreamWithProgress: public boost::iterator_adaptor <
  ifstreamWithProgress,
  char*,
  boost::use_default,
    boost::forward_traversal_tag > {
public:
  ifstreamWithProgress() : pd(0) {
    pd = new progress_display(...);
  }

  ifstreamWithProgress::ifstreamWithProgress(const ifstreamWithProgress &r) : pd(0) {
    pd = new progress_display(...);
  }

  ~ifstreamWithProgress() {
    if (0 != pd) {
      delete pd;
    }
  }

  ifstreamWithProgress& operator= (const ifstreamWithProgress &r) {
    if (0 != pd) {
      delete pd;
    }
    pd = new progress_display(...);
    return *this;
  }

private:
  progress_display *pd;
};

Or you can use shared_ptr<progress_display>.


问:
QT auto save screenshot with naming template
I want to save multiple screenshot every 10 second with different name,

i want to save like this

here my current code

```<code>      QScreen *screen = QGuiApplication::primaryScreen();
      QPixmap pic  = screen->grabWindow(0);
      pic.save("C:/Users/Coding/Desktop/img/desktop_1.png");
</code>```

答:
Wrap this functionality into a class.
Add static counter to your class (for example static long long counter {0};)
Declare something like: QString m_path_to_image;
change your code to

```<code>pic.save(path_to_image.arg(m_counter));
</code>```

Body:
I want to save multiple screenshot every 10 second with different name,

i want to save like this

here my current code

      QScreen *screen = QGuiApplication::primaryScreen();
      QPixmap pic  = screen->grabWindow(0);
      pic.save("C:/Users/Coding/Desktop/img/desktop_1.png");

Body:
Wrap this functionality into a class.
Add static counter to your class (for example static long long counter {0};)
Declare something like: QString m_path_to_image;
change your code to

pic.save(path_to_image.arg(m_counter));


问:
Need to run .jar from console for it to work
I have a java application.
I'm using eclipse to write, compile and create a runnable .jar.

The program is used to discover OCF devices.

It uses UDP and multicast.

Multicast code

```<code>public static void sendMulticast(byte[] data) throws Exception{
        DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
        msocket.send(pack);
    }
public static byte[] recieveMulticast(int timeout) throws Exception{
        DatagramPacket packet;
        byte[] data = new byte[AppConfig.ocf_buffer_size];

        packet = new DatagramPacket(data, data.length);
        msocket.setSoTimeout(timeout);
        msocket.receive(packet);

        return data;
    }
</code>```

The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.

But when I start it with a double click, it doesn't work.

When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever.

I haven't tested it on Windows yet, but the problem remains on Linux all the same.

What is the difference when you start .jar from console or by double clicking?
Why is it effecting messages on multicast?

I'm using "Package required libraries into generated JAR".
I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work?
I would understand if I used sudo, but I didn't.

答:
When you are running any jar from console, Console/Terminal knows which program responsible to run the any jar i.e

```<code>java -jar example.jar
</code>```

but when double-clicking environment, OS/GUI manager doesn't know default responsible program to run the jar. ( Same way when you try to open some unknown extension file, Operating system will ask you open with which program/application)

To make Java open .jar files per default (i.e. double click) right click on any .jar file to select Properties. In the following window select the "Open With" tab to see e.g. the follwing choice:

Body:
I have a java application.
I'm using eclipse to write, compile and create a runnable .jar.

The program is used to discover OCF devices.

It uses UDP and multicast.

Multicast code

public static void sendMulticast(byte[] data) throws Exception{
        DatagramPacket pack = new DatagramPacket(data, data.length, mgroup, mport);
        msocket.send(pack);
    }
public static byte[] recieveMulticast(int timeout) throws Exception{
        DatagramPacket packet;
        byte[] data = new byte[AppConfig.ocf_buffer_size];

        packet = new DatagramPacket(data, data.length);
        msocket.setSoTimeout(timeout);
        msocket.receive(packet);

        return data;
    }

The code works when I start it from eclipse. It also works when I run the .jar from console on Linux.

But when I start it with a double click, it doesn't work.

When started from console, it finds my test device in less then a second. When started with a double click it doesn't find it ever.

I haven't tested it on Windows yet, but the problem remains on Linux all the same.

What is the difference when you start .jar from console or by double clicking?
Why is it effecting messages on multicast?

I'm using "Package required libraries into generated JAR".
I'm using java 1.7 in eclipse, and 1.8 on Linux, maybe thats the problem? But why does running it from console work?
I would understand if I used sudo, but I didn't.

Body:
When you are running any jar from console, Console/Terminal knows which program responsible to run the any jar i.e

java -jar example.jar

but when double-clicking environment, OS/GUI manager doesn't know default responsible program to run the jar. ( Same way when you try to open some unknown extension file, Operating system will ask you open with which program/application)

To make Java open .jar files per default (i.e. double click) right click on any .jar file to select Properties. In the following window select the "Open With" tab to see e.g. the follwing choice:


问:
Angular2 - formData values are passed as null to HTTP POST
I post my data to service in postman it works fine. But when I call the service in HTTP post request, it shows success in console but formData goes as null and nothing is saved on the server.

Any help would be appreciated. My code:

```<code>import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test',
      'newstype': 'Test',
      'priority': 'Test',
      'place': 'Test',
      'publishedon': 'Test',
      'publishedby': 'Test',
      'websiteurl': 'Test',
      'contactpersonname': 'Test',
      'mobile1': 'Test',
      'mobile2': 'Test',
      'email': 'Test',
      'display': 'Test',
      'rating': 'Test'
    };
  }

  onSubmit() {
    let formData:FormData = new FormData(this.news);
    console.log(this.news);
    let headers = new Headers({'encrypt': 'multipart/form-data'});
    let options = new RequestOptions({ headers: headers });
    this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
  }
  }
</code>```

Add.html

```<code><h2>ADD CONFIGS</h2>
  <div class="row">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">NEWS TITLE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newsdescription">NEWS DESCRIPTION:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newstype">NEWS TYPE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="priority">PRIORITY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="place">PLACE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedon">PUBLISHED ON:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedby">PUBLISHED BY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="websiteurl">WEBSITE URL:</label>
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="contactpersonname">CONTACT PERSON NAME:</label>
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile1">MOBILE 1:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile2">MOBILE 2:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="email">EMAIL:</label>
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="status">STATUS:</label>
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="display">DISPLAY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="rating">RATING:</label>
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>
    </div>

    <div class="form-group col-xs-6">
            <label for="usr">City Image:</label>
            <img width="50px" height="50px" id="cimage">
            <input type="file" (change)="fileChange($event)" placeholder="Upload file">
    </div>

    <button type="submit" class="btn btn-success">Add</button>

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

答:
APPEND FORM VALUES (WITH FILE) TO FORMDATA IN ANGULAR2.

Actually someone had posted answer to my question, credit actually goes to him, I made some modification in appending the object to form data to get it working.
People can append the form data directly or iterate over the object to add values to formData.
Below is my working code:

Component.ts

```<code>import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
news;
fileList;
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test Title',
      'newstype': 'Test Title',
      'priority': 'Test Title',
      'place': 'Test Title',
      'publishedon': 'Test Title',
      'publishedby': 'Test Title',
      'websiteurl': 'Test Title',
      'contactpersonname': 'Test Title',
      'mobile1': 'Test Title',
      'mobile2': 'Test Title',
      'email': 'Test Title',
      'status': 'Test Title',
      'display': 'Test Title',
      'rating': 'Test Title'
    };
  }

      fileChange(event) {
        this.fileList = event.target.files;
      }

  onSubmit() {
    let formData:FormData = new FormData();

    formData.append('newstitle', this.news.newstitle);
    formData.append('newsdescription', this.news.newsdescription);
    formData.append('newstype', this.news.newstype);
    formData.append('priority', this.news.priority);
    formData.append('place', this.news.place);
    formData.append('publishedon', this.news.newstitlpublishedone);
    formData.append('publishedby', this.news.publishedby);
    formData.append('websiteurl', this.news.websiteurl);
    formData.append('contactpersonname', this.news.contactpersonname);
    formData.append('mobile1', this.news.mobile1);
    formData.append('mobile2', this.news.mobile2);
    formData.append('email', this.news.email);
    formData.append('status', this.news.status);
    formData.append('display', this.news.display);
    formData.append('rating', this.news.rating);

    if(this.fileList.length > 0){
      for (var x = 0;  x < this.fileList.length; x++) {
      let file: File = this.fileList[x];
      formData.append('fileData', file, file.name);
      }
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    } else {
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    }
  }
}
</code>```

ADD.html

```<code><h2>ADD CONFIGS</h2>
  <div class="row">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">NEWS TITLE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newsdescription">NEWS DESCRIPTION:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newstype">NEWS TYPE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="priority">PRIORITY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="place">PLACE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedon">PUBLISHED ON:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedby">PUBLISHED BY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="websiteurl">WEBSITE URL:</label>
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="contactpersonname">CONTACT PERSON NAME:</label>
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile1">MOBILE 1:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile2">MOBILE 2:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="email">EMAIL:</label>
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="status">STATUS:</label>
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="display">DISPLAY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="rating">RATING:</label>
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>
    </div>

    <div class="form-group col-xs-6">
            <label for="usr">City Image:</label>
            <img width="50px" height="50px" id="cimage">
            <input type="file" id="newsimg" name="newsimg" multiple="true" (change)="fileChange($event)">
    </div>

    <button type="submit" class="btn btn-success">Add</button>

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

Body:
I post my data to service in postman it works fine. But when I call the service in HTTP post request, it shows success in console but formData goes as null and nothing is saved on the server.

Any help would be appreciated. My code:

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test',
      'newstype': 'Test',
      'priority': 'Test',
      'place': 'Test',
      'publishedon': 'Test',
      'publishedby': 'Test',
      'websiteurl': 'Test',
      'contactpersonname': 'Test',
      'mobile1': 'Test',
      'mobile2': 'Test',
      'email': 'Test',
      'display': 'Test',
      'rating': 'Test'
    };
  }

  onSubmit() {
    let formData:FormData = new FormData(this.news);
    console.log(this.news);
    let headers = new Headers({'encrypt': 'multipart/form-data'});
    let options = new RequestOptions({ headers: headers });
    this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
  }
  }

Add.html

ADD CONFIGS

  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">

      NEWS TITLE:
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>

      NEWS DESCRIPTION:
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>

      NEWS TYPE:
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>

      PRIORITY:
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>

      PLACE:
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>

      PUBLISHED ON:
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>

      PUBLISHED BY:
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>

      WEBSITE URL:
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>

      CONTACT PERSON NAME:
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>

      MOBILE 1:
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>

      MOBILE 2:
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>

      EMAIL:
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>

      STATUS:
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>

      DISPLAY:
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>

      RATING:
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>

            City Image:

            <input type="file" (change)="fileChange($event)" placeholder="Upload file">

    <button type="submit" class="btn btn-success">Add</button>

  </form>

Body:
APPEND FORM VALUES (WITH FILE) TO FORMDATA IN ANGULAR2.

Actually someone had posted answer to my question, credit actually goes to him, I made some modification in appending the object to form data to get it working.
People can append the form data directly or iterate over the object to add values to formData.
Below is my working code:

Component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
news;
fileList;
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test Title',
      'newstype': 'Test Title',
      'priority': 'Test Title',
      'place': 'Test Title',
      'publishedon': 'Test Title',
      'publishedby': 'Test Title',
      'websiteurl': 'Test Title',
      'contactpersonname': 'Test Title',
      'mobile1': 'Test Title',
      'mobile2': 'Test Title',
      'email': 'Test Title',
      'status': 'Test Title',
      'display': 'Test Title',
      'rating': 'Test Title'
    };
  }

      fileChange(event) {
        this.fileList = event.target.files;
      }

  onSubmit() {
    let formData:FormData = new FormData();

    formData.append('newstitle', this.news.newstitle);
    formData.append('newsdescription', this.news.newsdescription);
    formData.append('newstype', this.news.newstype);
    formData.append('priority', this.news.priority);
    formData.append('place', this.news.place);
    formData.append('publishedon', this.news.newstitlpublishedone);
    formData.append('publishedby', this.news.publishedby);
    formData.append('websiteurl', this.news.websiteurl);
    formData.append('contactpersonname', this.news.contactpersonname);
    formData.append('mobile1', this.news.mobile1);
    formData.append('mobile2', this.news.mobile2);
    formData.append('email', this.news.email);
    formData.append('status', this.news.status);
    formData.append('display', this.news.display);
    formData.append('rating', this.news.rating);

    if(this.fileList.length > 0){
      for (var x = 0;  x < this.fileList.length; x++) {
      let file: File = this.fileList[x];
      formData.append('fileData', file, file.name);
      }
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    } else {
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    }
  }
}

ADD.html

<h2>ADD CONFIGS</h2>
  <div class="row">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">NEWS TITLE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newsdescription">NEWS DESCRIPTION:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newstype">NEWS TYPE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="priority">PRIORITY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="place">PLACE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedon">PUBLISHED ON:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedby">PUBLISHED BY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="websiteurl">WEBSITE URL:</label>
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="contactpersonname">CONTACT PERSON NAME:</label>
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile1">MOBILE 1:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="mobile2">MOBILE 2:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="email">EMAIL:</label>
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="status">STATUS:</label>
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="display">DISPLAY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="rating">RATING:</label>
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>
    </div>

    <div class="form-group col-xs-6">
            <label for="usr">City Image:</label>
            <img width="50px" height="50px" id="cimage">
            <input type="file" id="newsimg" name="newsimg" multiple="true" (change)="fileChange($event)">
    </div>

    <button type="submit" class="btn btn-success">Add</button>

  </form>
</div>