问:
Load CSV to datagrid vb.net, but it will not populate all columns
I am trying to load a CSV to a datatable and currently with the code I am using it will only load the first two columns of data. However some lines have like 7 columns. I do not think this is formatted in the correct CSV syntax, however I believe there is enough info there to extract what I need.
I am looking to get all the info pulled into a datagrid, and view it as if I were opening Excel or some program of the like so then I can access the various cells for the required info.
Sample code to pull in CSV:

```<code>Private Sub ReadCSV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ABInfo = GetCsvData("C:\epds\WIP\", "test2.csv")
    Bind_Grid_ABInfo(ABInfo)
End Sub

Public Sub Bind_Grid_ABInfo(ByVal DT As DataTable)
    Try
        DGABInfo.DataSource = DT
        DGABInfo.Refresh()
    Catch ex As Exception
    End Try
End Sub

Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
    Try

        Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""text;HDR=yes;FMT=Delimited"";"
        Dim conn As New OleDbConnection(strConnString)
        Try
            conn.Open()
            Dim cmd As New OleDbCommand("SELECT *  FROM [" & strFileName & "]", conn) '("SELECT * FROM [" & strFileName & "]", conn)
            Dim da As New OleDbDataAdapter()

            da.SelectCommand = cmd
            Dim ds As New DataSet()

            da.Fill(ds)
            da.Dispose()
            Return ds.Tables(0)
        Catch
            Return Nothing
        Finally
            conn.Close()
        End Try
    Catch ex As Exception
    End Try
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Close()
    Me.Dispose()
End Sub
</code>```

here is the sample csv --- I'm not sure how to keep the formatting

```<code>Process,Quote
File Name,project_10_-_freeform_cover
Project Name,Project 10 - Freeform Cover
Customer Id,1234567

Dealer,dealer
Dealer Name,name
Dealer Telephone,1234567890
Dealer Mobile,
Dealer Email,e@mail.com
Dealer Address,address

Distributor Name,dist
Distributor,dist
Distributor Address,address
Distributor Telephone,1234567890
Distributor Email,e@mail.com

Customer Name,name
Customer Telephone,1234567890
Customer Address,address

Description,L shape pool with slide
Comments,

Measurement Unit,inches

Cover Type,Safety

Pool Shape,Freeform

Cover Color,Blue
Cover Material,Standard Mesh
Grid Size,3 x 3
Replacement,No

Deck Type,Concrete
Deck Width,Full 3' of decking around all sides of the pool.
Coping Type,Concrete
Coping Width,12.0,1' 0"
Perimeter Padding,No

Warnings,None.

A-B Length,401.0,33' 5"

Feature,AB
Type,
Removable,No
Number of points,2
Line Length,401.0,33' 5"
Point,A,B,X,Y,Label,Type
1,,,0.0,0.0,A,Position
2,,,401.0,0.0,B,Position

Feature,Pool
Number of points,25
Calculated Length,467.1,38' 11.1"
Calculated Width,348.4,29' 0.4"
Calculated Perimeter,1386.7,115' 6.7"
Point,A,B,X,Y,Label,Type
1,375.0,61.0,371.2,53.2,,A-B
2,357.0,66.0,354.0,46.3,,A-B
3,190.0,221.0,184.6,44.9,,A-B
4,79.0,341.0,63.3,47.3,,A-B
5,52.0,400.0,4.4,51.8,,A-B
6,73.0,412.0,-4.5,72.9,,A-B
7,146.0,430.0,-3.5,146.0,,A-B
8,165.0,438.0,-4.8,164.9,,A-B
9,191.0,449.0,-5.4,190.9,,A-B
10,210.0,457.0,-4.9,209.9,,A-B
11,341.0,530.0,-4.8,341.0,,A-B
12,356.0,517.0,25.2,355.1,,A-B
13,379.0,531.0,28.0,378.0,,A-B
14,396.0,542.0,29.7,394.9,,A-B
15,401.0,520.0,63.8,395.9,,A-B
16,408.0,497.0,100.1,395.5,,A-B
17,390.0,481.0,101.7,376.5,,A-B
18,371.0,464.0,103.7,356.2,,A-B
19,372.0,442.0,129.5,348.7,,A-B
20,318.0,391.0,136.0,287.5,,A-B
21,278.0,354.0,140.6,239.8,,A-B
22,305.0,314.0,193.6,235.7,,A-B
23,436.0,234.0,369.3,231.8,,A-B
24,408.0,159.0,376.5,157.1,,A-B
25,397.0,130.0,375.9,127.6,,A-B

Feature,Slide
Type,Obstacle
Removable,No
Number of points,4
Line Length,64.0,5' 4.0"
Point,A,B,X,Y,Label,Type
1,146.0,430.0,-3.5,146.0,,A-B
2,165.0,438.0,-4.8,164.9,,A-B
3,191.0,449.0,-5.4,190.9,,A-B
4,210.0,457.0,-4.9,209.9,,A-B

Cross Pool Measurement,Cross Measurement 1
Measured Length,381.0,31' 9"
Calculated Length,381.4,31' 9.4"
Point,A,B,X,Y,Label,Type,Feature,Point
1,165.0,438.0,-4.8,164.9,8,Existing,Pool,8
2,408.0,159.0,376.5,157.1,24,Existing,Pool,24

Cross Pool Measurement,Cross Measurement 2
Measured Length,347.0,28' 11"
Calculated Length,348.6,29' 0.6"
Point,A,B,X,Y,Label,Type,Feature,Point
1,401.0,520.0,63.8,395.9,15,Existing,Pool,15
2,79.0,341.0,63.3,47.3,4,Existing,Pool,4
</code>```

答:
If you know ahead of time about the format you will be importing, which you do, then you could do something like this. According to your current data, 10 columns will be enough to host a data file. Therefore, I simply put each "data column" in a GridviewColumn.

sorry this is c#, not vb.net

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace CsvToDataGridView_47289838
{

    public partial class Form1 : Form
    {
        DataGridView dgv = new DataGridView();
        BindingList<dgvEntry> dgvdata = new BindingList<dgvEntry>();
        string filePath = @"M:\StackOverflowQuestionsAndAnswers\CsvToDataGridView_47289838\SampleData.txt";
        public Form1()
        {
            InitializeComponent();
            initDGV();
            addData();
        }

        private void addData()
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
            {
                string currentLine = string.Empty;
                while ((currentLine = sr.ReadLine()) != null)
                {
                    dgvEntry entry = new CsvToDataGridView_47289838.dgvEntry();
                    List<string> splitted = currentLine.Split(',').ToList();
                    for (int i = 0; i < splitted.Count; i++)
                    {
                        switch (i)
                        {
                            case 0:
                                entry.col1 = splitted[i];
                                break;
                            case 1:
                                entry.col2 = splitted[i];
                                break;
                            case 2:
                                entry.col3 = splitted[i];
                                break;
                            case 3:
                                entry.col4 = splitted[i];
                                break;
                            case 4:
                                entry.col5 = splitted[i];
                                break;
                            case 5:
                                entry.col6 = splitted[i];
                                break;
                            case 6:
                                entry.col7 = splitted[i];
                                break;
                            case 7:
                                entry.col8 = splitted[i];
                                break;
                            case 8:
                                entry.col9 = splitted[i];
                                break;
                            case 9:
                                entry.col10 = splitted[i];
                                break;
                            default:
                                break;
                        }
                    }
                    dgvdata.Add(entry);
                }
            }
        }

        private void initDGV()
        {
            dgv.Dock = DockStyle.Fill;
            this.Controls.Add(dgv);
            dgv.DataSource = dgvdata;
        }
    }

    public class dgvEntry
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
        public string col4 { get; set; }
        public string col5 { get; set; }
        public string col6 { get; set; }
        public string col7 { get; set; }
        public string col8 { get; set; }
        public string col9 { get; set; }
        public string col10 { get; set; }
    }
}
</code>```

Body:
I am trying to load a CSV to a datatable and currently with the code I am using it will only load the first two columns of data. However some lines have like 7 columns. I do not think this is formatted in the correct CSV syntax, however I believe there is enough info there to extract what I need.
I am looking to get all the info pulled into a datagrid, and view it as if I were opening Excel or some program of the like so then I can access the various cells for the required info.
Sample code to pull in CSV:

Private Sub ReadCSV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ABInfo = GetCsvData("C:\epds\WIP\", "test2.csv")
    Bind_Grid_ABInfo(ABInfo)
End Sub

Public Sub Bind_Grid_ABInfo(ByVal DT As DataTable)
    Try
        DGABInfo.DataSource = DT
        DGABInfo.Refresh()
    Catch ex As Exception
    End Try
End Sub

Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
    Try

        Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=""text;HDR=yes;FMT=Delimited"";"
        Dim conn As New OleDbConnection(strConnString)
        Try
            conn.Open()
            Dim cmd As New OleDbCommand("SELECT *  FROM [" & strFileName & "]", conn) '("SELECT * FROM [" & strFileName & "]", conn)
            Dim da As New OleDbDataAdapter()

            da.SelectCommand = cmd
            Dim ds As New DataSet()

            da.Fill(ds)
            da.Dispose()
            Return ds.Tables(0)
        Catch
            Return Nothing
        Finally
            conn.Close()
        End Try
    Catch ex As Exception
    End Try
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Close()
    Me.Dispose()
End Sub

here is the sample csv --- I'm not sure how to keep the formatting

Process,Quote
File Name,project_10_-_freeform_cover
Project Name,Project 10 - Freeform Cover
Customer Id,1234567

Dealer,dealer
Dealer Name,name
Dealer Telephone,1234567890
Dealer Mobile,
Dealer Email,e@mail.com
Dealer Address,address

Distributor Name,dist
Distributor,dist
Distributor Address,address
Distributor Telephone,1234567890
Distributor Email,e@mail.com

Customer Name,name
Customer Telephone,1234567890
Customer Address,address

Description,L shape pool with slide
Comments,

Measurement Unit,inches

Cover Type,Safety

Pool Shape,Freeform

Cover Color,Blue
Cover Material,Standard Mesh
Grid Size,3 x 3
Replacement,No

Deck Type,Concrete
Deck Width,Full 3' of decking around all sides of the pool.
Coping Type,Concrete
Coping Width,12.0,1' 0"
Perimeter Padding,No

Warnings,None.

A-B Length,401.0,33' 5"

Feature,AB
Type,
Removable,No
Number of points,2
Line Length,401.0,33' 5"
Point,A,B,X,Y,Label,Type
1,,,0.0,0.0,A,Position
2,,,401.0,0.0,B,Position

Feature,Pool
Number of points,25
Calculated Length,467.1,38' 11.1"
Calculated Width,348.4,29' 0.4"
Calculated Perimeter,1386.7,115' 6.7"
Point,A,B,X,Y,Label,Type
1,375.0,61.0,371.2,53.2,,A-B
2,357.0,66.0,354.0,46.3,,A-B
3,190.0,221.0,184.6,44.9,,A-B
4,79.0,341.0,63.3,47.3,,A-B
5,52.0,400.0,4.4,51.8,,A-B
6,73.0,412.0,-4.5,72.9,,A-B
7,146.0,430.0,-3.5,146.0,,A-B
8,165.0,438.0,-4.8,164.9,,A-B
9,191.0,449.0,-5.4,190.9,,A-B
10,210.0,457.0,-4.9,209.9,,A-B
11,341.0,530.0,-4.8,341.0,,A-B
12,356.0,517.0,25.2,355.1,,A-B
13,379.0,531.0,28.0,378.0,,A-B
14,396.0,542.0,29.7,394.9,,A-B
15,401.0,520.0,63.8,395.9,,A-B
16,408.0,497.0,100.1,395.5,,A-B
17,390.0,481.0,101.7,376.5,,A-B
18,371.0,464.0,103.7,356.2,,A-B
19,372.0,442.0,129.5,348.7,,A-B
20,318.0,391.0,136.0,287.5,,A-B
21,278.0,354.0,140.6,239.8,,A-B
22,305.0,314.0,193.6,235.7,,A-B
23,436.0,234.0,369.3,231.8,,A-B
24,408.0,159.0,376.5,157.1,,A-B
25,397.0,130.0,375.9,127.6,,A-B

Feature,Slide
Type,Obstacle
Removable,No
Number of points,4
Line Length,64.0,5' 4.0"
Point,A,B,X,Y,Label,Type
1,146.0,430.0,-3.5,146.0,,A-B
2,165.0,438.0,-4.8,164.9,,A-B
3,191.0,449.0,-5.4,190.9,,A-B
4,210.0,457.0,-4.9,209.9,,A-B

Cross Pool Measurement,Cross Measurement 1
Measured Length,381.0,31' 9"
Calculated Length,381.4,31' 9.4"
Point,A,B,X,Y,Label,Type,Feature,Point
1,165.0,438.0,-4.8,164.9,8,Existing,Pool,8
2,408.0,159.0,376.5,157.1,24,Existing,Pool,24

Cross Pool Measurement,Cross Measurement 2
Measured Length,347.0,28' 11"
Calculated Length,348.6,29' 0.6"
Point,A,B,X,Y,Label,Type,Feature,Point
1,401.0,520.0,63.8,395.9,15,Existing,Pool,15
2,79.0,341.0,63.3,47.3,4,Existing,Pool,4

Body:
If you know ahead of time about the format you will be importing, which you do, then you could do something like this. According to your current data, 10 columns will be enough to host a data file. Therefore, I simply put each "data column" in a GridviewColumn.

sorry this is c#, not vb.net

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace CsvToDataGridView_47289838
{

    public partial class Form1 : Form
    {
        DataGridView dgv = new DataGridView();
        BindingList<dgvEntry> dgvdata = new BindingList<dgvEntry>();
        string filePath = @"M:\StackOverflowQuestionsAndAnswers\CsvToDataGridView_47289838\SampleData.txt";
        public Form1()
        {
            InitializeComponent();
            initDGV();
            addData();
        }

        private void addData()
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
            {
                string currentLine = string.Empty;
                while ((currentLine = sr.ReadLine()) != null)
                {
                    dgvEntry entry = new CsvToDataGridView_47289838.dgvEntry();
                    List<string> splitted = currentLine.Split(',').ToList();
                    for (int i = 0; i < splitted.Count; i++)
                    {
                        switch (i)
                        {
                            case 0:
                                entry.col1 = splitted[i];
                                break;
                            case 1:
                                entry.col2 = splitted[i];
                                break;
                            case 2:
                                entry.col3 = splitted[i];
                                break;
                            case 3:
                                entry.col4 = splitted[i];
                                break;
                            case 4:
                                entry.col5 = splitted[i];
                                break;
                            case 5:
                                entry.col6 = splitted[i];
                                break;
                            case 6:
                                entry.col7 = splitted[i];
                                break;
                            case 7:
                                entry.col8 = splitted[i];
                                break;
                            case 8:
                                entry.col9 = splitted[i];
                                break;
                            case 9:
                                entry.col10 = splitted[i];
                                break;
                            default:
                                break;
                        }
                    }
                    dgvdata.Add(entry);
                }
            }
        }

        private void initDGV()
        {
            dgv.Dock = DockStyle.Fill;
            this.Controls.Add(dgv);
            dgv.DataSource = dgvdata;
        }
    }

    public class dgvEntry
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }
        public string col4 { get; set; }
        public string col5 { get; set; }
        public string col6 { get; set; }
        public string col7 { get; set; }
        public string col8 { get; set; }
        public string col9 { get; set; }
        public string col10 { get; set; }
    }
}


来源: stackexchange

问:
Is Lucene a good choice for Key/Value HashMap?
I am facing a problem. I am doing a mini web crawler. Right now is important to have an efficient HashMap. I just want key/value data structure with only inserts and lookups.

I know Lucene can do the job, just by having two fields: key and value; but is it efficient?
Is there any other solutions more simple?

Ps: It can be in PHP or Java but I would prefer PHP.

Note: I need it to be persisted. And it will be open and closed several times.

答:
If all you want is a fast, persistent key-value store for a non-enormous dataset, Lucene probably isn't the best solution- Berkeley DB would be the obvious choice.  That said, Grant Ingersoll gave a talk at this year's Lucene Revolution conference about exactly this.  He intentionally came at the question with a pro-Lucene bias, and got into a back-and-forth with several audience members about what contemporary document databases (like CouchDB) provide that Lucene doesn't.  For any non-huge dataset that might eventually need secondary indexes, I think this is a great solution. Lucene's performance for key/value lookups won't be quite as fast Berkeley DB, CouchDB, Tokyo Tyrant or the like, but it's still quite speedy, more than adequate for many apps.  I think he measured roughly 50ms for a key/value lookup on a recent laptop.  And if later on you need to add secondary indexes (as it seems like you might on the results of a web crawl), you'll have a much easier time with Lucene than with those products.

Other tools, like BDB, will be simpler to code for than Lucene.  But if that's a concern, just use Solr, which makes it easy to add docs and search via simple HTTP calls (you'll want to modify the fields in the schema.xml config file, but otherwise, Solr should be ready-to-use out of the box).

Now, if your dataset is too big to reasonably fit on one machine, distributed key-value stores, like Project Voldemort or Riak, might be easier to setup and administer.  But Lucene will get you pretty far on one machine, especially if you aren't indexing many fields- at least a TB, I'd guess.

If you do use Lucene, I'd think hard about whether there truly aren't any properties other than the key you'd like to search by- might as well get them stored the first time, since Lucene makes it easy.

ContentLicense: CC BY-SA 2.5


问:
Delete Facebook App with Graph API
I'm developing a Facebook authentication system using the Graph Api v2.8.

The website that makes the request requires the user's email.

Problem: the app is added on the user's Facebook regardless he unchecks or not the email permission option.

Is there any way of preventing the app being added on the user's facebook when he refuses to share his email?

If not, how can I remove the app from the user's facebook?

Thks in advance.

答:
Here is one possible solution that solved the problem, by removing the app from the user's Facebook:

```<code>$response = $fb->get('/me?fields=first_name,last_name,email');
$userNode = $response->getGraphUser();

if (!isset($userNode['email']) || (isset($userNode['email']) && !$userNode['email'])) {
    $fb->delete($userNode['id'] . '/permissions');
}
</code>```

The line:

$fb->delete($userNode['id'] . '/permissions');

deletes the user app.

ContentLicense: CC BY-SA 3.0

Title: Delete Facebook App with Graph API

Body:
Here is one possible solution that solved the problem, by removing the app from the user's Facebook:

$response = $fb->get('/me?fields=first_name,last_name,email');
$userNode = $response->getGraphUser();

if (!isset($userNode['email']) || (isset($userNode['email']) && !$userNode['email'])) {
    $fb->delete($userNode['id'] . '/permissions');
}

The line:

$fb->delete($userNode['id'] . '/permissions');

deletes the user app.


问:
jquery click on div in Chrome Console
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

```<code>$('.entry-method #em2690957').click();
</code>```

答:
You have to select a tag and click

```<code>$('#em2690957').children('a').click();
</code>```

Hope this helps.

Title: jquery click on div in Chrome Console

Body:
Maybe one of you can help me.
How do I click on a div, by using the Chrome Console?

I want to be able to click the div on this site any ideas.

example: https://gleam.io/ZyYPU/100-subscriber-giveaway-100-usd

Tried this without any luck.

$('.entry-method #em2690957').click();

Body:
You have to select a tag and click

$('#em2690957').children('a').click();

Hope this helps.


问:
Exceptions while connecting to the service bus
While connecting to signalr that is configured to use the azure service bus, we are getting 502 and 500 errors since a few hours. The connect and abort fail:

https://mmeet.net/signalr/connect?transport=longPolling&clientProtocol=1.4&MeetingId=b7acc652-8a78-4f64-8ad2-af9484b25865&connectionToken=S%2BQSYyz4tSJTk5200dgUDv1csUNBRO7DT5akRRfkKruqYmbx3DD%2BcIiAr7nakWIl9M3347835prU%2FR5w3Fq4F0y3prhDsiqaG3TgiMhKLu69LcxcOF%2BfOE2dWKiBuU%2FUvpflpXutfZ3krnQ6QH5R6w%3D%3D&connectionData=%5B%7B%22name%22%3A%22meetinghub%22%7D%5D&tid=8&_=1510676508783

gives a standard 502 error and

https://mmeet.net/signalr/abort?transport=longPolling&clientProtocol=1.4&MeetingId=b7acc652-8a78-4f64-8ad2-af9484b25865&connectionToken=8IZTzSjy%2FVpYXq6Q%2FWHz2S6kPApEaD9uEKLiaLuzGUJtNiihXE69%2F8BfY5hWLVepwxB8Y4I6d9PQS%2BZT0VLrgR6kSrFClShBuaunmiJWmuFD6QHGi0yUgugRsOOOsDEYMpk5cJBVSjHNw6HWr48Fxw%3D%3D&connectionData=%5B%7B%22name%22%3A%22meetinghub%22%7D%5D

gives the following exception.

Exception Details: System.ServiceModel.FaultException: 50002: Provider Internal Error, Resource:sb://metaphora.servicebus.windows.net/signalr_topic_metaphorasignalr_4/subscriptions/752b0eb8-5797-4781-b729-59a74afa5a7a. TrackingId:e2eb137f-2cac-45d8-b366-fa8585c6c2d2_G39, SystemTracker:metaphora.servicebus.windows.net:SIGNALR_TOPIC_MetaphoraSignalR_4/Subscriptions/752b0eb8-5797-4781-b729-59a74afa5a7a, Timestamp:11/14/2017 4:22:01 PM

Also our topics are gone in the azure service bus admin. Is there a problem with the service bus?

答:
@jan-willem-spuij this is a support question, not a question for StackOverflow. If you experience an abnormal behaviour that is not expected at all, then you should direct your question at Azure support.

In this case, if this is a production issue, I'd not even think twice before opening a support case. If it's lower environment, check with your team as entities, just like energy, don't show up or disappear. You can also try ServiceBus Explorer tool to inspect your namespace.

For exceptions and troubleshooting with Azure support, you've got TrackingId. Add that to your support case to get to the bottom of the issue.


问:
Substitute multiple spaces with character during SELECT
I have some field values that contain 5 spaces as a separator e.g.

AWERDC     123

I do a weekly extract that ends up being submitted to an outside party, but any of these particular values need to have a '#' substituted (AWERDC#123).  I am looking for the best way to do the transform during the SELECT.

What can I do?

答:
If you are using SQL Server, and if there are always 5 spaces, you can use replace(), like this example:

```<code>declare @s varchar(100) = 'AWERDC     123'

select replace(@s, '     ', '#')
</code>```

Which returns:

```<code>AWERDC#123
</code>```

If there are a variable number of spaces, then you can handle that using stuff(), charindex() and patindex().  This example depends on the characters before the variable number of spaces to be letters, and the characters after the spaces to be numbers.  If your data is otherwise, you will have to modify the patindex() accordingly.

```<code>declare @s varchar(100) = 'AWERDC       123'

select stuff(@s, charindex(' ', @s, 1), patindex('%[0-9]%', @s) - charindex(' ', @s, 1), '#')
</code>```

Which always returns AWERDC#123, regardless of how many spaces there are.

Here is an improved approach that doesn't care what type of characters are in the leading and trailing characters.  It simply works with a variable number of spaces, because it searches for the first space forward, then the first space backwards (in the string), does the math, then inserts a single # in place of all the spaces using stuff():

```<code>declare @s varchar(100) = 'AWERDC             123'

select stuff(@s, charindex(' ', @s, 1), len(@s) - charindex(' ', reverse(@s), 1) - charindex(' ', @s, 1) + 2, '#')
</code>```

Body:
If you are using SQL Server, and if there are always 5 spaces, you can use replace(), like this example:

declare @s varchar(100) = 'AWERDC     123'

select replace(@s, '     ', '#')

Which returns:

AWERDC#123

If there are a variable number of spaces, then you can handle that using stuff(), charindex() and patindex().  This example depends on the characters before the variable number of spaces to be letters, and the characters after the spaces to be numbers.  If your data is otherwise, you will have to modify the patindex() accordingly.

declare @s varchar(100) = 'AWERDC       123'

select stuff(@s, charindex(' ', @s, 1), patindex('%[0-9]%', @s) - charindex(' ', @s, 1), '#')

Which always returns AWERDC#123, regardless of how many spaces there are.

Here is an improved approach that doesn't care what type of characters are in the leading and trailing characters.  It simply works with a variable number of spaces, because it searches for the first space forward, then the first space backwards (in the string), does the math, then inserts a single # in place of all the spaces using stuff():

declare @s varchar(100) = 'AWERDC             123'

select stuff(@s, charindex(' ', @s, 1), len(@s) - charindex(' ', reverse(@s), 1) - charindex(' ', @s, 1) + 2, '#')


问:
extending the c programming language with gcc
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

```<code>namespace TcpConnection {
    void* connect(char *addr)
}
</code>```

would translate to:

```<code>void* TcpConnection_connect(char *addr)
</code>```

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?

答: You could write a preprocessor that parses your language and compiles it to C, which is then passed on to gcc. This is how early implementations of C++ worked. However, you may prefer to hack on LLVM's clang, which is designed to support several C-family languages and, as part of LLVM, is also designed to be more modular and easier to extend.</p>

Body:
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

namespace TcpConnection {
    void* connect(char *addr)
}

would translate to:

void* TcpConnection_connect(char *addr)

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?


问:
R - ggplot2 plotting lognormal curve on histogram
So i have a set of data which follows the lognormal distribution, i have found the values for mu and sigma and am now trying to plot a histogram of the data alongside the PDF of the lognormal. However plotting the line seems to put it below 0 which doesnt seem to make sense, what am i doing wrong here, it seems like the line should be 5 y values higher.

Thanks
M

```<code>h <- read.table("data.csv", header=TRUE, sep=",", row.names="id")
library("ggplot2")
d <- ggplot(data=h, aes(h$time)) +
geom_histogram(binwidth = 0.8) +
stat_function(fun = dlnorm, args = list(meanlog = 2.2, sdlog = 0.44, log = TRUE), colour = "red")
d
</code>```

Graph Produced

答:
To be able to make the comparision:

```<code>h <- data.frame(time = rlnorm(100, 2.2, .44))
library("ggplot2")
d <- ggplot(data=h) +
  geom_histogram(binwidth = 0.8, aes(x = time, ..density..)) +
  stat_function(fun = dlnorm, args = list(meanlog = 2.2, sdlog = 0.44),
                colour = "red")
d
</code>```

As suggested, turn log = TRUE off and then use ..density.. to get a frequency instead of a count.

Body:
So i have a set of data which follows the lognormal distribution, i have found the values for mu and sigma and am now trying to plot a histogram of the data alongside the PDF of the lognormal. However plotting the line seems to put it below 0 which doesnt seem to make sense, what am i doing wrong here, it seems like the line should be 5 y values higher.

Thanks
M

h <- read.table("data.csv", header=TRUE, sep=",", row.names="id")
library("ggplot2")
d <- ggplot(data=h, aes(h$time)) +
geom_histogram(binwidth = 0.8) +
stat_function(fun = dlnorm, args = list(meanlog = 2.2, sdlog = 0.44, log = TRUE), colour = "red")
d

Graph Produced

Body:
To be able to make the comparision:

h <- data.frame(time = rlnorm(100, 2.2, .44))
library("ggplot2")
d <- ggplot(data=h) +
  geom_histogram(binwidth = 0.8, aes(x = time, ..density..)) +
  stat_function(fun = dlnorm, args = list(meanlog = 2.2, sdlog = 0.44),
                colour = "red")
d

As suggested, turn log = TRUE off and then use ..density.. to get a frequency instead of a count.


问:
About region / zone of Google Compute Engine's VM
I have an instance which was created in Australia region, the zone is australia-southeast1-a. However, I find that the External IP is still in US:

Had tried creating another instance in another region (asia), and logined using ssh, haven't noticed any significant difference in latency, the responses are both not very fast.

My question is, have I correctly setup the region to Australia? Or is there any configuration that I have missed?

答:
Your setup on the VM and its configuration are perfectly fine. You have your hardware physically located in the Australian region. Your concern over IP’s location is just a mere confusion. This had happened to most of the customers.

Most of the external Geo IP services are depending upon the SWIP database. And for this reason, most of the Google’s IPs are SWIP’ed to the  Mountain View, CA. Because of this, even for a VM which is created outside (in your case Australian Region) the US shows its IP location as in the US.

Furthermore, you can also go through this Google discussion thread which will give you more comments on this matter.


问:
React native - cross platform with windows phone
Is React Native made for windows phone too?
If no what is best language or tool that is worth learning in mobile app cross-platform development?</p>

答:
React Native doesn't come with support for Windows Phone (7/8/8.1).

Microsoft has created a really good React Native plugin for Windows Phone's successor: Windows 10 Mobile, but they also announced that the company no longer focuses on the platform so choose wisely.

React Native Windows plugin repository:
https://github.com/Microsoft/react-native-windows


问:
hashes, flash and assert_not - how do I assert_not a hash
I'm trying to finish the exercises in the Mhartl RoR tutorial.

The question asks you to complete the following integration test

```<code>assert_not 'flash.FILLIN'

assert_select 'div#FILLIN'
assert_select 'div.FILLIN'
</code>```

And I have a flash that shows either

```<code>{:success => "success message here"}
</code>```

or upon error,

```<code><% flash.each do |message_type, message| %>
</code>```

taking the standard @user.errors.fullmessages.

My questions are:

How would I go about finding the list of @users.errors.fullmessages, and how do assert_not error?

```<code>assert_not 'flash.errors'
</code>```

yields no exit:success... :(

any help appreciated, the link to the exercise is here: https://draft.railstutorial.org/book/sign_up#sec-signup_exercises

答:
To assert that there is no flash message of a particular type set (:error in this example), you can do:

```<code>assert_predicate flash[:error], :nil?
</code>```

Body:
I'm trying to finish the exercises in the Mhartl RoR tutorial.

The question asks you to complete the following integration test

assert_not 'flash.FILLIN'

assert_select 'div#FILLIN'
assert_select 'div.FILLIN'

And I have a flash that shows either

{:success => "success message here"}

or upon error,

<% flash.each do |message_type, message| %>

taking the standard @user.errors.fullmessages.

My questions are:

How would I go about finding the list of @users.errors.fullmessages, and how do assert_not error?

assert_not 'flash.errors'

yields no exit:success... :(

any help appreciated, the link to the exercise is here: https://draft.railstutorial.org/book/sign_up#sec-signup_exercises

Body:
To assert that there is no flash message of a particular type set (:error in this example), you can do:

assert_predicate flash[:error], :nil?


问:
ReactJS - Components - Best Practices
I'm relative new to react and I need to create a character counter component (CharacterCounter) for a input field.

This question is not specific to this component (character counter) - but is a generic question about components best practices in general.

I can implement in two ways (as far I know - if there are better ways I'm happy to hear about it):

1) Wrapping the component and have the input field as a child - The component will insert the span (for showing the counter) after the input field

```<code><CharacterCounter maxLength={50}>
    <input type="text">
  </CharacterCounter>
</code>```

and

```<code>const input = this.container.firstChild
input.addEventListener('keyup', function() { ... });
</code>```

advantage: I can have multiple components for the same input - if I need extra functionality (components) for this input.

disadvantage: If the input for some reason stop being the first child of this component - stop working/ fragile

2) To create a generic component which will render the input and the counter on the render() function

like:

```<code><CharacterCounter />

render() {
    return (
        <input type="text">
        <span>{this.state.count}</span>
    )
</code>```

advantage: Not fragile - not relying on the first child

disadvantage: Not sure is possible to have other component for the same input - let's say I need another component for tracking every time the user type/ or focus/ or blur the field

What is the best practices?

答:
You could use second approach with components with state and then use composition to extend that component or create more  “special cases” of that component.

let {Component} = React;

class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {count: 0}
  }

  render() {
    return

      <input
      {...this.props}
      onChange={() => {
        let count = this.refs.inputCount.value.length;
        this.setState({count})
      }}
      type="text"
      maxLength="50"
      ref="inputCount" />
       {this.state.count} / 50

  }
}

class FocusInput extends Component {
  render() {
    return <Input
    onFocus={() => {
      console.log('Focus')
    }} />
  }
}

class App extends Component {
  render() {
    return

      <Input />
      <FocusInput />

  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Title: ReactJS - Components - Best Practices

Body:
I'm relative new to react and I need to create a character counter component (CharacterCounter) for a input field.

This question is not specific to this component (character counter) - but is a generic question about components best practices in general.

I can implement in two ways (as far I know - if there are better ways I'm happy to hear about it):

1) Wrapping the component and have the input field as a child - The component will insert the span (for showing the counter) after the input field

<CharacterCounter maxLength={50}>
    <input type="text">
  </CharacterCounter>

and

const input = this.container.firstChild
input.addEventListener('keyup', function() { ... });

advantage: I can have multiple components for the same input - if I need extra functionality (components) for this input.

disadvantage: If the input for some reason stop being the first child of this component - stop working/ fragile

2) To create a generic component which will render the input and the counter on the render() function

like:

<CharacterCounter />

render() {
    return (
        <input type="text">
        {this.state.count}
    )

advantage: Not fragile - not relying on the first child

disadvantage: Not sure is possible to have other component for the same input - let's say I need another component for tracking every time the user type/ or focus/ or blur the field

What is the best practices?

Body:
You could use second approach with components with state and then use composition to extend that component or create more  “special cases” of that component.

let {Component} = React;

class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {count: 0}
  }

  render() {
    return <div>
      <input
      {...this.props}
      onChange={() => {
        let count = this.refs.inputCount.value.length;
        this.setState({count})
      }}
      type="text"
      maxLength="50"
      ref="inputCount" />
      <span> {this.state.count} / 50</span>
    </div>
  }
}

class FocusInput extends Component {
  render() {
    return <Input
    onFocus={() => {
      console.log('Focus')
    }} />
  }
}

class App extends Component {
  render() {
    return <div>
      <Input />
      <FocusInput />
    </div>
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>


问:
Android ADT error, dx.jar was not loaded from the SDK folder
I just downloaded Eclipse Galileo and installed ADT10 and tried to a phonegap app using this guide: http://www.phonegap.com/start
But each time i try to build im getting this error:
Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder!

I know that there are already some questions/answers about it in this forum but they didnt work for me.

答:
I had this problem in Eclipse since I upgraded from build-tools 25.0.0 to 26.0.0

I just add "sdk.buildtools=25.0.0" in my project.properties and it works again

my project.properties:

```<code>target=android-23
sdk.buildtools=25.0.0
android.library.reference.1=../design
</code>```

Body:
I had this problem in Eclipse since I upgraded from build-tools 25.0.0 to 26.0.0

I just add "sdk.buildtools=25.0.0" in my project.properties and it works again

my project.properties:

target=android-23
sdk.buildtools=25.0.0
android.library.reference.1=../design


问:
Push data in array, ngx-line-chart, angular4
I want to push some live-data in an array, to show the data in the ngx-line-chart.

This is my Linechart-Component:

```<code>export class LinechartComponent implements OnInit {

  data = [
    {
      "name": "Test",
      "series": [
        {
          'nam': 'Point1',
          'value': '5'
        },
        {
          "nam": "Point2",
          "value": '15'
        }
      ]
    },
  ];

  constructor( private GEtDataService: DataService) { }

  ngOnInit() {
    this.GEtDataService.onMessage = (msg: string) => {
      this.data = [{name: 'test',  series: {  'nam': 'testing', 'value': msg}}];
    };
  };

  }
</code>```

But this doesn't work.

Furthermore, did anyone know, if there is a solution to implement an own structure of the array with ngx-line-chart?

答:
You should specify the index and push the value to the array as follows,</p>

```<code> this.GEtDataService.onMessage = (msg: string) => {
      this.data[0].series.push({ 'nam': 'testing', 'value': msg});
 };
</code>```

Body:
I want to push some live-data in an array, to show the data in the ngx-line-chart.

This is my Linechart-Component:

export class LinechartComponent implements OnInit {

  data = [
    {
      "name": "Test",
      "series": [
        {
          'nam': 'Point1',
          'value': '5'
        },
        {
          "nam": "Point2",
          "value": '15'
        }
      ]
    },
  ];

  constructor( private GEtDataService: DataService) { }

  ngOnInit() {
    this.GEtDataService.onMessage = (msg: string) => {
      this.data = [{name: 'test',  series: {  'nam': 'testing', 'value': msg}}];
    };
  };

  }

But this doesn't work.

Furthermore, did anyone know, if there is a solution to implement an own structure of the array with ngx-line-chart?

Body:
You should specify the index and push the value to the array as follows,

 this.GEtDataService.onMessage = (msg: string) => {
      this.data[0].series.push({ 'nam': 'testing', 'value': msg});
 };


问:
How to 'queue' piece of code in javascript
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

```<code>  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }
</code>```

答:
I agree that a callback function is the proper way. If this is code you cannot modify, you can do something like this, but seriously, use a callback!

```<code>function wait_for_load(expr, func)
{
    var interval = window.setInterval(function()
    {
        if(eval(expr))
        {
            window.clearInterval(interval);
            func();
        }
    }, 20);
}

var d;
$(document).ready(function() {
    d = new Duk('element');
    d.getBlueprint('hud.json');
    wait_for_load('d.blueprint', start);
});
</code>```

Body:
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }

Body:
I agree that a callback function is the proper way. If this is code you cannot modify, you can do something like this, but seriously, use a callback!

function wait_for_load(expr, func)
{
    var interval = window.setInterval(function()
    {
        if(eval(expr))
        {
            window.clearInterval(interval);
            func();
        }
    }, 20);
}

var d;
$(document).ready(function() {
    d = new Duk('element');
    d.getBlueprint('hud.json');
    wait_for_load('d.blueprint', start);
});


问:
How can I encode text data as features for ML algorithms in Python?
I have a csv file which have columns filled with text data. How can I replace them with constant data so I can apply machine learning algorithm on that dataset.
Dataset Example: Date, Name, Color Name, User Name and Product Name.</p>

答:
Actually the upper answers and comments just explain half of the work.
1, 2, 3, ... imply spacial dependencies within the encoded words, e.g. "red" is closer to "yellow" than to "blue", since 1 is closer to 2 than to 3.
After applying a transformation to integer values you should go for something like a one-hot-encoding.

If you use pandas check out get_dummies

If you use sklearn go for LabelBinarizer

(Here you can find a very good tutorial on how to deal with categorical data)

Since a one-hot-encoding blows up your actual data you feed into the network you might consider using dimensionalty reduction techniques upfront or maybe the best way is to use so called word embeddings. Today it's very advisable to use word embeddings in real text data, since they were a game changer for modern NLP applications. If you're only dealing with single words there is no need for word embeddings.

Cheers


问:
Python loop through text and set numpy array index
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

```<code>temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]
</code>```

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

答:
```<code>matrixText = '1,2,3;4,5,6;7,8,9'
temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.empty((rows, columns),dtype=np.int)
for n, line in enumerate(temp1):
    rA[n,:]=line.split(',')
</code>```

Body:
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?


问:
Close, prev, next icons not showing properly in Lightgallery Jquery
I successfully configured lightgallery in my project. However, when i click on thumbnail and big image comes up , prev, next, close icons not showing properly. Infact strange characters are showing. This can be viewed on page : http://agentpet.com/lightgallery/lg.html . Please help me out whats wrong in it ?</p>

答:
My prev button disapeared too.

I was looking at 'lightgallery.css' and changed like here My Fork to solve this issue.

Was ...

```<code>.lg-actions .lg-prev:after {
</code>```

changed to:

```<code>.lg-actions .lg-prev:before {
</code>```

... like lg.next is.

Hope it helps anybody.

Body:
My prev button disapeared too.

I was looking at 'lightgallery.css' and changed like here My Fork to solve this issue.

Was ...

.lg-actions .lg-prev:after {

changed to:

.lg-actions .lg-prev:before {

... like lg.next is.

Hope it helps anybody.


问:
Should I avoid Alternative Control Syntax?
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

```<code>x = (y == true) ? "foo" : "bar";
</code>```

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

答:
The conditional operator (sometimes referred to as the ternary operator, but that's not technically correct, see Marc's comments) isn't really an "alternative control structure", there's a few important differences:

The conditional operator is an operator and provides a value, it's used in an expression.

If/else is a control structure, it (of course) returns no value on its own.

The alternatives in a conditional operator must also be expressions.

The alternatives in an if-else structure can be an arbitrary number of statements.

Of course there are similarities as well:

Each evaluates a conditional expression.

Only the appropriate alternative (expression or block) is evaluated based on the boolean value of the conditional.

Both can be chained together with others of its kind to form longer "switch-like" statements.

In general, if you are evaluating alternative expressions for the side-effects (that is to do work instead of to return a value), then using a conditional operator can be more confusing to maintainers than using an if-else structure.

If all of the following are true, use a conditional:

Your conditional and alternative statements are easy to understand.

None of the expressions has any side-effects.

You won't need additional behavior (i.e. side-effects or additional statements) on the alternatives in the future.

Your example as given is a good use of a ternary conditional.

When in doubt, use an if-else.  Beware of thinking of the conditional as another kind of if-else and trying to cram things that don't belong into it.  That's the kind of thing that (especially when found in legacy code) turns people off to the conditional operator altogether.

OwnerDisplayName: Chris

Body:
As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:

x = (y == true) ? "foo" : "bar";

I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional if ... else structure?

Thanks in advance.

OwnerDisplayName: Adam Bellaire

LastEditorDisplayName: Adam Bellaire


问:
Python request.session JIRA "You do not have the permission to see the specified issue"
Firstly, I am aware of the solution presented here: JIRA REST API to get work log - "You do not have the permission to see the specified issue" ... As well the linked blog post (penned by @Nick Josevski), which whilst useful, doesn't address my specifc problem, which could be something trivial...

With following Python 2.7.3 code...

```<code>import requests
import getpass
import json

jira_user = raw_input("Username: ")
jira_pass = getpass.getpass()

session = requests.Session()
session.verify = jira_ca_certs # Our internal certs
auth_info = {"username": jira_user, "password":  jira_pass}
login_url = 'http://JIRA_SERVER.com/login.jsp'
session.post(login_url, data=auth_info)
</code>```

I generate the cookies post basic authenticatation to jira (note: I am using "http" without specifying the PORT to authenticate with the login page).. As session automatically holds the returned cookies, I can use session.cookies to set the header:

```<code>cookies = requests.utils.dict_from_cookiejar(session.cookies)
headers = {'Content-type': 'application/json', 'cookie': cookies}
</code>```

Following which, I test the captured cookies with a basic get to the secure JIRA url, using https + PORT:

```<code>base = session.get('https://JIRA_SERVER.com:1234', headers=headers)
print 'base: ', base
</code>```

The above, as expected, returns (though this might not be a valid test?) ...

```<code>base:  <Response [200]>
</code>```

Now to test the code for it's intended purpose. I extend the url for a specific JIRA issue, using the same approach:

```<code>jira = session.get('https://JIRA_SERVER.com:1234/rest/api/latest/issue/KRYP-6207', headers=headers)
print 'issue: ', jira
print jira.json()
</code>```

With JSON output, I get a response stating I do not have the permission:

```<code>issue:  <Response [401]>
{u'errorMessages': [u'You do not have the permission to see the specified issue.', u'Login Required'], u'errors': {}}
</code>```

The cookies returned, that I use in the header, are:

```<code>headers:  {'cookie': 'atlassian.xsrf.token=XXXXXXXXXXXXXXXX|lout; Path=/, JSESSIONID=XXXXXXXXXXXXXXXX; Path=/'}
</code>```

I don't know why this works for the base url, but not the issue url.. I have used Chrome POSTMAN to check the cookies being returned, and they are the same as those listed above i.e. atlassian.xsrf.token, and JSESSIONID.

Hoping someone here can tell me what I am doing wrong! Thanks in advance ...

答:
Maybe you are not correctly logged in? based on the requests I saw in webbrowser developer tools, I created following requests and it worked with our JIRA:</p>

```<code>import requests
import getpass
import json

jira_user = raw_input("Username: ")
jira_pass = getpass.getpass()

session = requests.Session()

headers = {
    'Host': 'our.jira.com',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Referer': 'https://our.jira.com/login.jsp',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
}

data = [
  ('os_username', jira_user),
  ('os_password', jira_pass),
  ('os_destination', ''),
  ('user_role', ''),
  ('atl_token', ''),
  ('login', 'Anmelden'),
]

loginPost = session.post('https://our.jira.com/login.jsp', headers=headers, data=data)

xsrf_token = session.cookies.get_dict()['atlassian.xsrf.token']
jsessionid = session.cookies.get_dict()['JSESSIONID']

cookies = {
    'atlassian.xsrf.token': xsrf_token,
    'JSESSIONID': jsessionid,
}

headers = {
    'Host': 'our.jira.com',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
}

r = session.get('https://our.jira.com/rest/api/latest/issue/SDN-206', headers=headers, cookies=cookies)
print r.json()
</code>```

Body:
Firstly, I am aware of the solution presented here: JIRA REST API to get work log - "You do not have the permission to see the specified issue" ... As well the linked blog post (penned by @Nick Josevski), which whilst useful, doesn't address my specifc problem, which could be something trivial...

With following Python 2.7.3 code...

import requests
import getpass
import json

jira_user = raw_input("Username: ")
jira_pass = getpass.getpass()

session = requests.Session()
session.verify = jira_ca_certs # Our internal certs
auth_info = {"username": jira_user, "password":  jira_pass}
login_url = 'http://JIRA_SERVER.com/login.jsp'
session.post(login_url, data=auth_info)

I generate the cookies post basic authenticatation to jira (note: I am using "http" without specifying the PORT to authenticate with the login page).. As session automatically holds the returned cookies, I can use session.cookies to set the header:

cookies = requests.utils.dict_from_cookiejar(session.cookies)
headers = {'Content-type': 'application/json', 'cookie': cookies}

Following which, I test the captured cookies with a basic get to the secure JIRA url, using https + PORT:

base = session.get('https://JIRA_SERVER.com:1234', headers=headers)
print 'base: ', base

The above, as expected, returns (though this might not be a valid test?) ...

base:  <Response [200]>

Now to test the code for it's intended purpose. I extend the url for a specific JIRA issue, using the same approach:

jira = session.get('https://JIRA_SERVER.com:1234/rest/api/latest/issue/KRYP-6207', headers=headers)
print 'issue: ', jira
print jira.json()

With JSON output, I get a response stating I do not have the permission:

issue:  <Response [401]>
{u'errorMessages': [u'You do not have the permission to see the specified issue.', u'Login Required'], u'errors': {}}

The cookies returned, that I use in the header, are:

headers:  {'cookie': 'atlassian.xsrf.token=XXXXXXXXXXXXXXXX|lout; Path=/, JSESSIONID=XXXXXXXXXXXXXXXX; Path=/'}

I don't know why this works for the base url, but not the issue url.. I have used Chrome POSTMAN to check the cookies being returned, and they are the same as those listed above i.e. atlassian.xsrf.token, and JSESSIONID.

Hoping someone here can tell me what I am doing wrong! Thanks in advance ...

Body:
Maybe you are not correctly logged in? based on the requests I saw in webbrowser developer tools, I created following requests and it worked with our JIRA:

import requests
import getpass
import json

jira_user = raw_input("Username: ")
jira_pass = getpass.getpass()

session = requests.Session()

headers = {
    'Host': 'our.jira.com',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Referer': 'https://our.jira.com/login.jsp',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
}

data = [
  ('os_username', jira_user),
  ('os_password', jira_pass),
  ('os_destination', ''),
  ('user_role', ''),
  ('atl_token', ''),
  ('login', 'Anmelden'),
]

loginPost = session.post('https://our.jira.com/login.jsp', headers=headers, data=data)

xsrf_token = session.cookies.get_dict()['atlassian.xsrf.token']
jsessionid = session.cookies.get_dict()['JSESSIONID']

cookies = {
    'atlassian.xsrf.token': xsrf_token,
    'JSESSIONID': jsessionid,
}

headers = {
    'Host': 'our.jira.com',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
}

r = session.get('https://our.jira.com/rest/api/latest/issue/SDN-206', headers=headers, cookies=cookies)
print r.json()


问:
Looping a component in another component Vue.js
The question here is how can I get this Task.vue file to loop in my tasklist.vue file knowing I'm willing to pass a json file so I can get the list of all the task to do.

Task.vue

```<code><template>
    <table :id="id" class="task_box">
        <tr>
            <td class="task_user">{{name}}</td>
            <td class="task_date">{{date}}</td>
            <td class="task_time">{{time}}</td>
        </tr>
        <tr>
            <td colspan="3" class="task_description">
                <div class="toto">{{description}}</div>
            </td>
        </tr>
    </table>
</template>

<script>
export default {
  name: "task",
  data() {
    return {
      id: 1,
      name: "Test",
      date: new Date(),
      time: "9:30 ",
      description: "whatever"
    };
  }
};
</script>
</code>```

So this task.vue is meant to be a container that I can use in the tasklist.vue.

tasklist.vue

```<code><template>
    <div>
        <task v-for="task in tasks" :key="task.id"></task>
    </div>
</template>

<script>
import Task from "./Task.vue";

export default {
  name: "tasklist",
  data() {
    return {
      tasks: []
    };
  },
  components: {
    Task
  }
};
</script>
</code>```

答:
If task-component is reapeating, you should insert it's tag inside table tag.

Use props to pass data to task-component from tasklist-component

When tasklist-component is creating, you can load tasks via Ajax from json.

Full working example of code you can find here

TaskList.vue

```<code><script>
  import Task from "./Task.vue";

  export default {
    components: { Task },
    data() {
      return {
        tasks: [],
        isLoading: false,
        doShowNewTaskAddingDialog: false,
      };
    },
    created(){
//      this.isLoading = true;

//      $.ajax({
//        url: '/some/tasks/url',
//        method: 'GET',
//        dataType: 'json',
//        success: (tasks) => {
//          this.isLoading = false;
//          this.tasks = tasks;
//        }
//      });

       this.tasks = [
         {id: 1, name: "task 1", date: new Date(), time: "9:31", description: "descr 1" },
         {id: 1, name: "task 2", date: new Date(), time: "9:32", description: "descr 2" },
         {id: 1, name: "task 3", date: new Date(), time: "9:33", description: "descr 3" },
         {id: 1, name: "task 4", date: new Date(), time: "9:34", description: "descr 4" },
       ]
    },
    methods:{
      addButtonHandler(){
        this.doShowNewTaskAddingDialog = true;
      }
    }
  };
</script>

<template>
  <div>
    <div v-if="isLoading">Please wait, loading tasks...</div>
    <table v-if="!isLoading">
      <task
        v-for="task in tasks"
        :key="task.id"
        :task="task"
        :isNew="false"
      />

      <task
        v-if="doShowNewTaskAddingDialog"
        :isNew="true"
      />
    </table>
    <a href="javascript:" @click="addButtonHandler">Add new?</a>
  </div>
</template>

<style>
  table, td{
    border-collapse: collapse;
    border: 1px solid black;
  }
</style>
</code>```

Task.vue

```<code><template>
  <!--
    I'd prefer use bootstrap row and col- divs here instead
    of table and tbody-hack. See discussion here: https://github.com/vuejs/Discussion/issues/295
  -->
  <tbody>
    <!-- display only -->
    <tr v-if="!isNew">
      <td class="task_user">{{name}}</td>
      <td class="task_date">{{date}}</td>
      <td class="task_time">{{time}}</td>
    </tr>
    <tr v-if="!isNew">
      <td colspan="3" class="task_description">
        <div class="toto">{{description}}</div>
      </td>
    </tr>

    <!-- edit -->
    <tr v-if="isNew">
      <td class="task_user"><input type="text" v-model="name"></td>
      <td class="task_date"><input type="text" v-model="date"></td>
      <td class="task_time"><input type="text" v-model="time"></td>
    </tr>
    <tr v-if="isNew">
      <td colspan="3" class="task_description">
        <div class="toto"><input type="text" v-model="description"></div>
      </td>
    </tr>
  </tbody>
</template>

<script>
  export default {
    props:{
      task: { type: Object, required: false },
      isNew: { type: Boolean, required: true },
    },

    created(){
      if(!this.isNew){
        this.id = this.task.id;
        this.name = this.task.name;
        this.date = this.task.date;
        this.time = this.task.time;
        this.description = this.task.description;
      }
    },

    data() {
      return {
        id: 1,
        name: "",
        date: new Date(),
        time: "0:00 ",
        description: ""
      };
    }
  };
</script>
</code>```

Body:
The question here is how can I get this Task.vue file to loop in my tasklist.vue file knowing I'm willing to pass a json file so I can get the list of all the task to do.

Task.vue

<template>

            {{name}}
            {{date}}
            {{time}}

{{description}}

</template>

So this task.vue is meant to be a container that I can use in the tasklist.vue.

tasklist.vue

<template>

        <task v-for="task in tasks" :key="task.id"></task>

</template>

Body:
If task-component is reapeating, you should insert it's tag inside table tag.

Use props to pass data to task-component from tasklist-component

When tasklist-component is creating, you can load tasks via Ajax from json.

Full working example of code you can find here

TaskList.vue

<script>
  import Task from "./Task.vue";

  export default {
    components: { Task },
    data() {
      return {
        tasks: [],
        isLoading: false,
        doShowNewTaskAddingDialog: false,
      };
    },
    created(){
//      this.isLoading = true;

//      $.ajax({
//        url: '/some/tasks/url',
//        method: 'GET',
//        dataType: 'json',
//        success: (tasks) => {
//          this.isLoading = false;
//          this.tasks = tasks;
//        }
//      });

       this.tasks = [
         {id: 1, name: "task 1", date: new Date(), time: "9:31", description: "descr 1" },
         {id: 1, name: "task 2", date: new Date(), time: "9:32", description: "descr 2" },
         {id: 1, name: "task 3", date: new Date(), time: "9:33", description: "descr 3" },
         {id: 1, name: "task 4", date: new Date(), time: "9:34", description: "descr 4" },
       ]
    },
    methods:{
      addButtonHandler(){
        this.doShowNewTaskAddingDialog = true;
      }
    }
  };
</script>

<template>
  <div>
    <div v-if="isLoading">Please wait, loading tasks...</div>
    <table v-if="!isLoading">
      <task
        v-for="task in tasks"
        :key="task.id"
        :task="task"
        :isNew="false"
      />

      <task
        v-if="doShowNewTaskAddingDialog"
        :isNew="true"
      />
    </table>
    <a href="javascript:" @click="addButtonHandler">Add new?</a>
  </div>
</template>

<style>
  table, td{
    border-collapse: collapse;
    border: 1px solid black;
  }
</style>

Task.vue

<template>
  <!--
    I'd prefer use bootstrap row and col- divs here instead
    of table and tbody-hack. See discussion here: https://github.com/vuejs/Discussion/issues/295
  -->
  <tbody>
    <!-- display only -->
    <tr v-if="!isNew">
      <td class="task_user">{{name}}</td>
      <td class="task_date">{{date}}</td>
      <td class="task_time">{{time}}</td>
    </tr>
    <tr v-if="!isNew">
      <td colspan="3" class="task_description">
        <div class="toto">{{description}}</div>
      </td>
    </tr>

    <!-- edit -->
    <tr v-if="isNew">
      <td class="task_user"><input type="text" v-model="name"></td>
      <td class="task_date"><input type="text" v-model="date"></td>
      <td class="task_time"><input type="text" v-model="time"></td>
    </tr>
    <tr v-if="isNew">
      <td colspan="3" class="task_description">
        <div class="toto"><input type="text" v-model="description"></div>
      </td>
    </tr>
  </tbody>
</template>

<script>
  export default {
    props:{
      task: { type: Object, required: false },
      isNew: { type: Boolean, required: true },
    },

    created(){
      if(!this.isNew){
        this.id = this.task.id;
        this.name = this.task.name;
        this.date = this.task.date;
        this.time = this.task.time;
        this.description = this.task.description;
      }
    },

    data() {
      return {
        id: 1,
        name: "",
        date: new Date(),
        time: "0:00 ",
        description: ""
      };
    }
  };
</script>


问:
Problems with generics and static methods - Java
I'm trying my hand at Generics and implementing a generic list in a simple text based UI, however I keep getting messages saying that I can't get to different methods etc from my methods that are and aren't static.

Can somebody please point out what I am doing wrong?

```<code>public class GenericList<T> {

    List<T> genericList = new ArrayList<T>();

    public void addGeneric(T t) {
        this.genericList.add(t);
    }

    public static void initial() {
        // USER INPUT AREA
        switch(ans.toLowerCase()) {
            case "add" : addToList(); break;
            case "delete" : deleteFromList(); break;
            case "print" : printList(); break;
        }
    }

    public void deleteFromList() {}

    public void printList() {
        for (int i = 0; i<this.genericList.size(); i++) {
            System.out.println(this.genericList.get(i));
        }
    }

    public void addToList() {
        // USER INPUT AREA
        switch(type.toLowerCase()) {
            case "x":
                System.out.println("Exitiing...");
                initial();
                break;
            case "string": type="String"; break;
            case "int": type="Integer"; break;
            case "integer": type="Integer"; break;
        }

        System.out.println("Enter data...");
        String data = s.next();
        if (data.equals("x")){
            System.out.println("Exiting...");
            initial();
        }
        initial();

    }

    public static void main(String[] args) {
        GenericList g = new GenericList();
        initial();

    }
}
</code>```

答: I believe the issue has to do with the fact that you are using non-static methods (i.e. addToList() etc) within you static method (i.e. initial()). @danben's answer in the following post explains it pretty well: calling non-static method in static method in Java. To account for this you could make the other methods static or make initial() non-static.

Body:
I'm trying my hand at Generics and implementing a generic list in a simple text based UI, however I keep getting messages saying that I can't get to different methods etc from my methods that are and aren't static.

Can somebody please point out what I am doing wrong?

public class GenericList<T> {

    List<T> genericList = new ArrayList<T>();

    public void addGeneric(T t) {
        this.genericList.add(t);
    }

    public static void initial() {
        // USER INPUT AREA
        switch(ans.toLowerCase()) {
            case "add" : addToList(); break;
            case "delete" : deleteFromList(); break;
            case "print" : printList(); break;
        }
    }

    public void deleteFromList() {}

    public void printList() {
        for (int i = 0; i<this.genericList.size(); i++) {
            System.out.println(this.genericList.get(i));
        }
    }

    public void addToList() {
        // USER INPUT AREA
        switch(type.toLowerCase()) {
            case "x":
                System.out.println("Exitiing...");
                initial();
                break;
            case "string": type="String"; break;
            case "int": type="Integer"; break;
            case "integer": type="Integer"; break;
        }

        System.out.println("Enter data...");
        String data = s.next();
        if (data.equals("x")){
            System.out.println("Exiting...");
            initial();
        }
        initial();

    }

    public static void main(String[] args) {
        GenericList g = new GenericList();
        initial();

    }
}


问:
R Question: ifelse producing unexpected results
I am new to R and am getting unexpected results while using the ifelse() function. Here is an example. Below is a subset of the data frame I am working with. After the last command, why does the example$Points column contain 12 instead of 2? I have tried this for many different values of example$Value and the result is always 10 more than what I expect.

Example:

```<code>example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co      0
2927       18    100878    84386     2     2     Co      0
2928       18    100895    84386     1     5     Co      0
2929       18    100913    84386     2     2     Co      0
2930       18    100884    84386     2     2     Co      0
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co     12
2927       18    100878    84386     2     2     Co     12
2928       18    100895    84386     1     5     Co     11
2929       18    100913    84386     2     2     Co     12
2930       18    100884    84386     2     2     Co     12
</code>```

I've been using the work-around of just then subtracting 10 from the column, but I would like to avoid this and get to the bottom of what is going on here.

Any help would be greatly appreciated. Thank you!

答:
I have no idea, because when I run this on my machine I get the right answer:

```<code>> print(example)
  Question StudentID SchoolID Value Worth Answer Points
1       18    101290    84386     2     2     Co      0
2       18    100878    84386     2     2     Co      0
3       18    100895    84386     1     5     Co      0
4       18    100913    84386     2     2     Co      0
5       18    100884    84386     2     2     Co      0
>
> example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
>
> print(example)
  Question StudentID SchoolID Value Worth Answer Points
1       18    101290    84386     2     2     Co      2
2       18    100878    84386     2     2     Co      2
3       18    100895    84386     1     5     Co      1
4       18    100913    84386     2     2     Co      2
5       18    100884    84386     2     2     Co      2
</code>```

Here's the code that I'm using:

```<code>example = read.table('data.txt', header = T)
print(example)
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
print(example)
</code>```

Here's data.txt:

```<code>Question StudentID SchoolID Value Worth Answer Points
18    101290    84386     2     2     Co      0
18    100878    84386     2     2     Co      0
18    100895    84386     1     5     Co      0
18    100913    84386     2     2     Co      0
18    100884    84386     2     2     Co      0
</code>```

Hopefully this helps. What happens when you print out the type of example$Value? Try this:

```<code>print( typeof(example$Value) )
[1] "integer"
</code>```

If that comes out as a factor, then that might explain your odd results.

Body:
I am new to R and am getting unexpected results while using the ifelse() function. Here is an example. Below is a subset of the data frame I am working with. After the last command, why does the example$Points column contain 12 instead of 2? I have tried this for many different values of example$Value and the result is always 10 more than what I expect.

Example:

example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co      0
2927       18    100878    84386     2     2     Co      0
2928       18    100895    84386     1     5     Co      0
2929       18    100913    84386     2     2     Co      0
2930       18    100884    84386     2     2     Co      0
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co     12
2927       18    100878    84386     2     2     Co     12
2928       18    100895    84386     1     5     Co     11
2929       18    100913    84386     2     2     Co     12
2930       18    100884    84386     2     2     Co     12

I've been using the work-around of just then subtracting 10 from the column, but I would like to avoid this and get to the bottom of what is going on here.

Any help would be greatly appreciated. Thank you!

Body:
I have no idea, because when I run this on my machine I get the right answer:

> print(example)
  Question StudentID SchoolID Value Worth Answer Points
1       18    101290    84386     2     2     Co      0
2       18    100878    84386     2     2     Co      0
3       18    100895    84386     1     5     Co      0
4       18    100913    84386     2     2     Co      0
5       18    100884    84386     2     2     Co      0
>
> example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
>
> print(example)
  Question StudentID SchoolID Value Worth Answer Points
1       18    101290    84386     2     2     Co      2
2       18    100878    84386     2     2     Co      2
3       18    100895    84386     1     5     Co      1
4       18    100913    84386     2     2     Co      2
5       18    100884    84386     2     2     Co      2

Here's the code that I'm using:

example = read.table('data.txt', header = T)
print(example)
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
print(example)

Here's data.txt:

Question StudentID SchoolID Value Worth Answer Points
18    101290    84386     2     2     Co      0
18    100878    84386     2     2     Co      0
18    100895    84386     1     5     Co      0
18    100913    84386     2     2     Co      0
18    100884    84386     2     2     Co      0

Hopefully this helps. What happens when you print out the type of example$Value? Try this:

print( typeof(example$Value) )
[1] "integer"

If that comes out as a factor, then that might explain your odd results.


问:
Microservice of Commercetools cart API
As per documentations of commercetools, all the microservices(carts, order, shipping method etc) are independent of each other.

Calling the below API in POSTMAN :
https://api.sphere.io/{{myproject-key}}/carts/{{cartId}}

Body part:

    {
      "version": 5,
      "actions": [{
        "action": "addLineItem",
        "productId": "6d22957d-7c42-4663-95c3-099c11016999",
        "variantId": 1
      }]
    }
```

The above yields me the correct response whenever I provide the productID from the commercetools platform catalog.
But if I try to give my own product ID (from DB hosted at Localhost) I can't add items to the cart.

Instead it gives me the following error:
Error Log: "The referenced object of type 'product' with identifier '6d22957d-7c42-4663-95c3-099c11016999' not found."

This means both the services i.e product catalog and cart are tightly coupled.
Does this mean that the microservices cannot be used individually?

Question :
Can I use commercetools individual services such as Cart, Shipping method, Order alone in my existing e-commerce site?

答:
Commercetools platform's services can be utilized in different scenarios such as

architectures which core e-commerce services are provided by commercetools.

microservice architectures which consist of several different services provided by different service providers - only one of them being commercetools.

Therefore commercetools services provide different concepts and actions that suit different levels of integration. For scenarios that are more like 1 it is just convenient that commercetools platform optionally performs validations or calculations in a highly integrated fashion. For scenarios that are more like 2 commercetools provides optional concepts that allow you to use all the services in a loosly coupled fashion.

Some examples:

Add a line item to cart

Cart's addLineItem action is meant to be used in combination with commercetools Products endpoint. If you use both, commercetools can automatically validate the product that you are adding to cart.

Cart's addCustomLineItem action is meant to be used with your products that are stored outside of commercetools or with dynamically generated lineItems, not necessarily being conventional products. Therefore it allows you to add you own products that commercetools does not need to know.

Calculate shippingCosts

If you use commercetools' cart and shippingMethods services commercetools setShippingMethod action can automatically calculate shipping costs based on zones, countries and shippingMethods and even on more complex rules.

If you want to use commercetools cart service but you want to use your own shippingRate service you can use commercetools Carts setCustomShippingMethod to provide your externally calculated shippingRates.

Create an Order

If you use commercetools' cart and order services commercetools automatically validates your carts before converting it to orders if you perform the createOrderFromCart action.

If you want to use commercetools orders but want to use your own cart services you can use commercetools orderImport service.

These are just three examples of different ways to use commercetools services in different scenarios. Usually whenever it makes sense you will find a way of loosely integrating commercetools services into your overall architecture.

There is an unofficial postman collection for the commercetools API that covers most of their endpoints and update actions (currently more then 400 actions).

ContentLicense: CC BY-SA 4.0

Title: Microservice of Commercetools cart API

Body:
As per documentations of commercetools, all the microservices(carts, order, shipping method etc) are independent of each other.

Calling the below API in POSTMAN :
https://api.sphere.io/{{myproject-key}}/carts/{{cartId}}

Body part:

    {
      "version": 5,
      "actions": [{
        "action": "addLineItem",
        "productId": "6d22957d-7c42-4663-95c3-099c11016999",
        "variantId": 1
      }]
    }

The above yields me the correct response whenever I provide the productID from the commercetools platform catalog.
But if I try to give my own product ID (from DB hosted at Localhost) I can't add items to the cart.

Instead it gives me the following error:
Error Log: "The referenced object of type 'product' with identifier '6d22957d-7c42-4663-95c3-099c11016999' not found."

This means both the services i.e product catalog and cart are tightly coupled.
Does this mean that the microservices cannot be used individually?

Question :
Can I use commercetools individual services such as Cart, Shipping method, Order alone in my existing e-commerce site?


问:
Calling api inside map
I have two APIs which are written in action and reducer using redux.The first api fetches a list of user and the second api based on user id which comes from the first api.

The APIs are as follows
action.js

```<code>export const GET_EXPERT_LIST='GET_EXPERT_LIST';
export const GET_PROFILE_PHOTO='GET_PROFILE_PHOTO';
export const getExpertList=()=>{
    return(dispatch)=>{
        axios({
            method:'POST',
            url:Constants.URLConst+"/xyz",
            headers:Constants.headers,
            data:{
                "PageNum" : 1,
            }
        }).then((response)=>{
            return dispatch({
                type:GET_EXPERT_LIST,
                response
            })

        }).catch((error)=>{
            console.log(error);
        })
    }
}

export const getProfile=(userid)=>{
    return(dispatch)=>{
        axios({
             method:'GET',
             url:Constants.URLConst+"/UserProfileImage?enterpriseId="+userid,
             headers:Constants.headers
        }).then((response)=>{
             dispatch({
                type:GET_PROFILE_PHOTO,
                response
             })
        }).catch((error)=>{
            console.log(error);
        })
    }
}
</code>```

And in reducer.js, I have-

```<code>import {combineReducers} from 'redux';
import {ASK_EXPERT_DATA,GET_EXPERT_LIST,GET_PROFILE_PHOTO} from '../actions/ProfilePageActions.js';

export function getExpertList(state={},action){
    switch(action.type){
        case GET_EXPERT_LIST:
            return {...state, ...action.response}
            default:
                return state
    }
}

export function getProfile(state={},action){
    switch(action.type){
        case GET_PROFILE_PHOTO:
            return {...state, ...action.response}
            default:
                return state
    }
}

const data=combineReducers({
    getExpertList,
    getProfile
})

export default data;
</code>```

In the main javascript file, I am calling the first api in componentDidMount,
since the first api return an array which I am using map() for display.

```<code>import React,{Component} from 'react';
import ReactDom from 'react-dom';
import {getExpert,getExpertList} from './actions/ProfilePageActions.js';
import {connect} from 'react-redux';
import theme from './assets/react-toolbox/theme';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider';
import Card from 'react-toolbox/lib/card/Card.js';
import CardTitle from 'react-toolbox/lib/card/CardTitle';
import CardMedia from 'react-toolbox/lib/card/CardMedia';
import Chip from 'react-toolbox/lib/chip/Chip.js';
import CardText from 'react-toolbox/lib/card/CardText';

class FindExpert extends Component{

    state={
        countries: ['ES-es', 'TH-th'],
        source:[],
        valueSelected:[],
        experts:[]
    }

    componentDidMount(){
        this.props.getExpertList();
    }

    componentWillReceiveProps(nextProps){

        if(nextProps.get_Expert_List && nextProps.get_Expert_List.data){
            this.setState({
                experts:[...nextProps.get_Expert_List.data.Experts]
            })
        }
    }

    getExpertInfo(){
        var i=1;
        if (this.state.experts && this.state.experts.length) {
            this.test = this.state.experts.map((expertUSer)=> {
                this.props.getProfile(expertUSer.UserId);
                console.log(this.props.get_profile);
                return(
                    <ThemeProvider theme={theme} key={i++}>
                        <Card className='experts'>

                            <CardTitle title={expertUSer.Name}
                                subtitle={expertUSer.Designation}/>
                            <CardText>{expertUSer.Country}</CardText>
                        </Card>
                    </ThemeProvider>
                    )
            });

            return this.test;
        }
        return null;
    }

    render(){
        if(this.props.ask_expert.data){
            return(
                <div className='expert-div' id='expert-div'>{this.getExpertInfo()}</div>
                    )
        }else{
            return null;
        }
    }
}

const mapStateToProps=(state)=>{
    console.log({getExpert: state.getProfile});
    return{
        get_Expert_List:state.getExpertList,
        get_profile:state.getProfile
    }
}

export default connect(mapStateToProps,{
    getExpertList,
    getProfile
})(FindExpert);
</code>```

So,in getExpertList's data, I am calling the getProfile by passing the user id of the individual user.But in this.props.getProfile(expertUSer.UserId);, I get the error that

getProfile is not a function

What should be done here?

答:
I see that you pass getProfile in connect but... it is not imported. xD

try:

```<code>import {getExpert,getExpertList, getProfile} from './actions/ProfilePageActions.js';
</code>```

Title: Calling api inside map

Body:
I have two APIs which are written in action and reducer using redux.The first api fetches a list of user and the second api based on user id which comes from the first api.

The APIs are as follows
action.js

export const GET_EXPERT_LIST='GET_EXPERT_LIST';
export const GET_PROFILE_PHOTO='GET_PROFILE_PHOTO';
export const getExpertList=()=>{
    return(dispatch)=>{
        axios({
            method:'POST',
            url:Constants.URLConst+"/xyz",
            headers:Constants.headers,
            data:{
                "PageNum" : 1,
            }
        }).then((response)=>{
            return dispatch({
                type:GET_EXPERT_LIST,
                response
            })

        }).catch((error)=>{
            console.log(error);
        })
    }
}

export const getProfile=(userid)=>{
    return(dispatch)=>{
        axios({
             method:'GET',
             url:Constants.URLConst+"/UserProfileImage?enterpriseId="+userid,
             headers:Constants.headers
        }).then((response)=>{
             dispatch({
                type:GET_PROFILE_PHOTO,
                response
             })
        }).catch((error)=>{
            console.log(error);
        })
    }
}

And in reducer.js, I have-

import {combineReducers} from 'redux';
import {ASK_EXPERT_DATA,GET_EXPERT_LIST,GET_PROFILE_PHOTO} from '../actions/ProfilePageActions.js';

export function getExpertList(state={},action){
    switch(action.type){
        case GET_EXPERT_LIST:
            return {...state, ...action.response}
            default:
                return state
    }
}

export function getProfile(state={},action){
    switch(action.type){
        case GET_PROFILE_PHOTO:
            return {...state, ...action.response}
            default:
                return state
    }
}

const data=combineReducers({
    getExpertList,
    getProfile
})

export default data;

In the main javascript file, I am calling the first api in componentDidMount,
since the first api return an array which I am using map() for display.

import React,{Component} from 'react';
import ReactDom from 'react-dom';
import {getExpert,getExpertList} from './actions/ProfilePageActions.js';
import {connect} from 'react-redux';
import theme from './assets/react-toolbox/theme';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider';
import Card from 'react-toolbox/lib/card/Card.js';
import CardTitle from 'react-toolbox/lib/card/CardTitle';
import CardMedia from 'react-toolbox/lib/card/CardMedia';
import Chip from 'react-toolbox/lib/chip/Chip.js';
import CardText from 'react-toolbox/lib/card/CardText';

class FindExpert extends Component{

    state={
        countries: ['ES-es', 'TH-th'],
        source:[],
        valueSelected:[],
        experts:[]
    }

    componentDidMount(){
        this.props.getExpertList();
    }

    componentWillReceiveProps(nextProps){

        if(nextProps.get_Expert_List && nextProps.get_Expert_List.data){
            this.setState({
                experts:[...nextProps.get_Expert_List.data.Experts]
            })
        }
    }

    getExpertInfo(){
        var i=1;
        if (this.state.experts && this.state.experts.length) {
            this.test = this.state.experts.map((expertUSer)=> {
                this.props.getProfile(expertUSer.UserId);
                console.log(this.props.get_profile);
                return(
                    <ThemeProvider theme={theme} key={i++}>
                        <Card className='experts'>

                            <CardTitle title={expertUSer.Name}
                                subtitle={expertUSer.Designation}/>
                            <CardText>{expertUSer.Country}</CardText>
                        </Card>
                    </ThemeProvider>
                    )
            });

            return this.test;
        }
        return null;
    }

    render(){
        if(this.props.ask_expert.data){
            return(

{this.getExpertInfo()}

                    )
        }else{
            return null;
        }
    }
}

const mapStateToProps=(state)=>{
    console.log({getExpert: state.getProfile});
    return{
        get_Expert_List:state.getExpertList,
        get_profile:state.getProfile
    }
}

export default connect(mapStateToProps,{
    getExpertList,
    getProfile
})(FindExpert);

So,in getExpertList's data, I am calling the getProfile by passing the user id of the individual user.But in this.props.getProfile(expertUSer.UserId);, I get the error that

getProfile is not a function

What should be done here?

Body:
I see that you pass getProfile in connect but... it is not imported. xD

try:

import {getExpert,getExpertList, getProfile} from './actions/ProfilePageActions.js';


问:
dplyr() grouping and getting counts - error message Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical"
I've got a data frame (df) with two variables, location and weather.

I'd like a  wide data frame (dfgoal), in which the data is grouped by location and in which there are three new variables (weather_1 to weather_3) with counts for the observations in the original weather variable.

The problem's that when I try to use dplyr()::mutate() I only get TRUE/FALSE output rather than counts, alternatively an error message: Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical".

Any help would be much appreciated.

Starting point (df):

```<code>df <- data.frame(location=c("az","az","az","az","bi","bi","bi","ca","ca","ca","ca","ca"),weather=c(1,1,2,3,2,3,2,1,2,3,1,2))
</code>```

Desired outcome (df):

```<code>dfgoal <- data.frame(location=c("az","bi","ca"),weather_1=c(2,0,2),weather_2=c(1,2,2),weather_3=c(1,1,1))
</code>```

Current code:

```<code>library(dplyr)
df %>% group_by(location)  %>% mutate(weather_1 = (weather == 1)) %>% mutate(weather_2 = (weather == 2)) %>% mutate(weather_3 = (weather == 3))
df %>% group_by(location)  %>% mutate(weather_1 = summarise(weather == 1)) %>% mutate(weather_2 = summarise(weather == 2)) %>% mutate(weather_3 = summarise(weather == 3))
</code>```

答:
Krzysztof's answer wins for simplicity, but if you want a tidyverse-only solution (dplyr and tidyr):

```<code>df %>%
    group_by(location, weather) %>%
    summarize(bin = sum(weather==weather)) %>%
    spread(weather, bin, fill = 0, sep='_')
</code>```

This results in:

```<code>location    weather_1   weather_2   weather_3
az  2   1   1
bi  0   2   1
ca  2   2   1
</code>```

Body:
I've got a data frame (df) with two variables, location and weather.

I'd like a  wide data frame (dfgoal), in which the data is grouped by location and in which there are three new variables (weather_1 to weather_3) with counts for the observations in the original weather variable.

The problem's that when I try to use dplyr()::mutate() I only get TRUE/FALSE output rather than counts, alternatively an error message: Evaluation error: no applicable method for 'summarise_' applied to an object of class "logical".

Any help would be much appreciated.

Starting point (df):

df <- data.frame(location=c("az","az","az","az","bi","bi","bi","ca","ca","ca","ca","ca"),weather=c(1,1,2,3,2,3,2,1,2,3,1,2))

Desired outcome (df):

dfgoal <- data.frame(location=c("az","bi","ca"),weather_1=c(2,0,2),weather_2=c(1,2,2),weather_3=c(1,1,1))

Current code:

library(dplyr)
df %>% group_by(location)  %>% mutate(weather_1 = (weather == 1)) %>% mutate(weather_2 = (weather == 2)) %>% mutate(weather_3 = (weather == 3))
df %>% group_by(location)  %>% mutate(weather_1 = summarise(weather == 1)) %>% mutate(weather_2 = summarise(weather == 2)) %>% mutate(weather_3 = summarise(weather == 3))

Body:
Krzysztof's answer wins for simplicity, but if you want a tidyverse-only solution (dplyr and tidyr):

df %>%
    group_by(location, weather) %>%
    summarize(bin = sum(weather==weather)) %>%
    spread(weather, bin, fill = 0, sep='_')

This results in:

location    weather_1   weather_2   weather_3
az  2   1   1
bi  0   2   1
ca  2   2   1


问:
SQL - Select *, but add in another column as the nth column?
This is probably a stupid question, but if I select tableA.*, but in the results I want a column from tableB as say the third column slotted in the middle of tableA's columns, is there a way to do this without manually selecting every single column from tableA and rearranging as required? This is in SSMS2016.

答:
There's no way to do that.

Just in case you didn't know, you can drag and drop table and column names within SSMS.  This feature comes in handy quite often.

See this for details:
http://www.sqlservercentral.com/blogs/the-dba-who-came-in-from-the-cold/2016/11/09/drag-drop-table-column-names-in-ssms/