问:
How to Convert a view into a Pane or Panel in Red
So I have a view that is currently working and looking like I want. What I would like to do take the content it contains wrap it inside a variable and put it inside of a tab-panel. To do this, I believe I need to convert it to a panel or some such. But I am not really sure how.

Here is the view,

```<code>        Red [ Title: "Editor"  needs: 'view]

        s: 110x25
        ts: 50x50

        view [size 800x800 title "Red Edit"

        drop-down s "Debug" data ["Debug" "Release"]
        drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
        button s "Compile" []  across
        button s  "Run" []

         return
            a: area 700x700 black
        ]
</code>```

Here is the tab-panel

```<code>       view [backdrop brown
            title "Red Edit"
            tab-panel 820x820 [
                  "File1" []

                              ]
        ]
</code>```

It would go inside of the first tab named "File1".
My attempts thus far have given me a compiler error telling me that the panel I am trying to create has no value.

Also, tips on syntax and coding style would be appreciated too since I am still learning red.

Update: here is how I would like to combine them :

```<code>    Red [ Title: "Editor"  needs: 'view]
    s: 110x25
    ts: 50x50

    p: [size 800x800 title "Red Edit"

    drop-down s "Debug" data ["Debug" "Release"]
    drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
    button s "Compile" []  across
    button s  "Run" []

     return
        a: area 700x700 black
    ]

    view [backdrop brown
    title "Red Edit"

    tab-panel 820x820 [
        "File1" [text "hello" p]

                                  ]
    ]
</code>```

If I do this, p never gets displayed.

答:
If I was going to make a guess about your intentions, I think your real question is:

How can I compose and glue GUI stuff together?

There are several ways to do this, but the first thing you should ask is:

Do I need to?

As @dockimbel says if it isn't dynamic, you can simply have it after tab-panel word inside the dialect block [], and this is idiomatic:

```<code>tab-panel [<rest of gui here>]
</code>```

Method 1: Compose into the dialect with a block

This is the next simplest way, using your code:

```<code>Red [ Title: "Editor"  needs: 'view]

s: 80x25
ts: 50x50

cnt-object: layout cnt-view-dialect-blk: [
    ;size 80x80 title "Red Edit"
    drop-down s "Debug" data ["Debug" "Release"]
    drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
    button s "Compile" []

    ;across
    button s  "Run" []

    return
    a: area 350x150 black
]

; view cnt-object

pnl-object: layout pnl-view-dialect-blk: compose/deep [
    title "Red Edit"
    tab-panel 400x200 [
        "File1" [(cnt-view-dialect-blk)]
    ]
]

view pnl-object
</code>```

Method 2: Use the view face! object

This requires a steeper learning curve, but makes everything much easier when you learn it, and is probably more efficient too! If you read the documentation for face!:

```<code>button: make face! [type: 'button]
</code>```

Then look back at what I've named as -object in the code above, you realize they are conceptually the same thing. That is, an object! created with make.

If you're doing this way, one of the most useful things is /pane and /parent to move up and down the hierarchy

Further considerations

View is not a "thing" as it appears on the surface. It may refer to the VID dialect (what you have in [blocks]), or view function which is used to display things in the view engine. The actual things are face! objects, created manually with make or by the layout function.

I've labelled -view-dialect-blk, written in the actual view dialect, which is conceptually different from the actual objects. If you inspect all that I've labelled with ??, I think you'd be a few steps closer to understanding how everything works under the hood ;-)

It's also good to read up on rebol2 view concepts and the official documentation until red's catches up with it. Though slightly different, the concepts are the same

Body:
So I have a view that is currently working and looking like I want. What I would like to do take the content it contains wrap it inside a variable and put it inside of a tab-panel. To do this, I believe I need to convert it to a panel or some such. But I am not really sure how.

Here is the view,

        Red [ Title: "Editor"  needs: 'view]

        s: 110x25
        ts: 50x50

        view [size 800x800 title "Red Edit"

        drop-down s "Debug" data ["Debug" "Release"]
        drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
        button s "Compile" []  across
        button s  "Run" []

         return
            a: area 700x700 black
        ]

Here is the tab-panel

       view [backdrop brown
            title "Red Edit"
            tab-panel 820x820 [
                  "File1" []

                              ]
        ]

It would go inside of the first tab named "File1".
My attempts thus far have given me a compiler error telling me that the panel I am trying to create has no value.

Also, tips on syntax and coding style would be appreciated too since I am still learning red.

Update: here is how I would like to combine them :

    Red [ Title: "Editor"  needs: 'view]
    s: 110x25
    ts: 50x50

    p: [size 800x800 title "Red Edit"

    drop-down s "Debug" data ["Debug" "Release"]
    drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
    button s "Compile" []  across
    button s  "Run" []

     return
        a: area 700x700 black
    ]

    view [backdrop brown
    title "Red Edit"

    tab-panel 820x820 [
        "File1" [text "hello" p]

                                  ]
    ]

If I do this, p never gets displayed.

Body:
If I was going to make a guess about your intentions, I think your real question is:

How can I compose and glue GUI stuff together?

There are several ways to do this, but the first thing you should ask is:

Do I need to?

As @dockimbel says if it isn't dynamic, you can simply have it after tab-panel word inside the dialect block [], and this is idiomatic:

tab-panel [<rest of gui here>]

Method 1: Compose into the dialect with a block

This is the next simplest way, using your code:

Red [ Title: "Editor"  needs: 'view]

s: 80x25
ts: 50x50

cnt-object: layout cnt-view-dialect-blk: [
    ;size 80x80 title "Red Edit"
    drop-down s "Debug" data ["Debug" "Release"]
    drop-down s "Windows" data ["Windows" "MacOSX" "Linux" "BSD" ]
    button s "Compile" []

    ;across
    button s  "Run" []

    return
    a: area 350x150 black
]

; view cnt-object

pnl-object: layout pnl-view-dialect-blk: compose/deep [
    title "Red Edit"
    tab-panel 400x200 [
        "File1" [(cnt-view-dialect-blk)]
    ]
]

view pnl-object

Method 2: Use the view face! object

This requires a steeper learning curve, but makes everything much easier when you learn it, and is probably more efficient too! If you read the documentation for face!:

button: make face! [type: 'button]

Then look back at what I've named as -object in the code above, you realize they are conceptually the same thing. That is, an object! created with make.

If you're doing this way, one of the most useful things is /pane and /parent to move up and down the hierarchy

Further considerations

View is not a "thing" as it appears on the surface. It may refer to the VID dialect (what you have in [blocks]), or view function which is used to display things in the view engine. The actual things are face! objects, created manually with make or by the layout function.

I've labelled -view-dialect-blk, written in the actual view dialect, which is conceptually different from the actual objects. If you inspect all that I've labelled with ??, I think you'd be a few steps closer to understanding how everything works under the hood ;-)

It's also good to read up on rebol2 view concepts and the official documentation until red's catches up with it. Though slightly different, the concepts are the same


来源: stackexchange

问:
How to get data from Google Sheet to use in deployed web app
I am using Google App scripts and am having trouble finding an answer to this fairly simple task: how can I get the data from a Google Sheet in my code.gs and then use it in a published web app (for some visualization w/ D3)?

I would like to get all columns and rows from the spreadsheet, then use those in the data. Preferably they would be in JSON for ease of use, but I can't find the specifics on how to grab all (or any) of the data from a Sheet in my code.gs and then use it in the index.html.

So far I have something like this:

code.gs

```<code>function getData(){
 var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k");

 //get desired range

 return sheet;
}
</code>```

index.html

In the

答:
Getting the data is fairly easy. However this has to be properly done on both server side and client side.

For code.gs you will need to return actual data, but currently return sheet just returns the sheet object. What you need to do instead is

```<code>var vals = sheet.getDataRange().getValues()
</code>```

which now gets you a 2D array of your sheet values. Now keep in mind that sheet has to be a sheet object not a spreadhseet object. So if your spreadsheet has many sheets, make sure you get the correct one with something like

```<code>var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheets()[0];
</code>```

or

```<code>var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheetByName('Sheet1');
</code>```

Now, since you want to grab the data as a JSON, all you really have to do is

```<code>vals = JSON.stringify(vals)
</code>```

and now you have a JSON string of values. However that is just half of it, because your index.html that you wrote will not make use of the data as it calls the server side function, but does not listen for a response. In order to do that, you will need to use a success handler as written here. Essentially you will have to call a function in index.html that will make use of the returned vals variable. So something like

```<code>google.script.run.withSuccessHandler(useData).getData();

function useData(data) {
   data = JSON.parse(data)
   //now you have a 2D array in your index.html and you can use it as you wish within these client side scripts
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Google App scripts and am having trouble finding an answer to this fairly simple task: how can I get the data from a Google Sheet in my code.gs and then use it in a published web app (for some visualization w/ D3)?

I would like to get all columns and rows from the spreadsheet, then use those in the data. Preferably they would be in JSON for ease of use, but I can't find the specifics on how to grab all (or any) of the data from a Sheet in my code.gs and then use it in the index.html.

So far I have something like this:

code.gs

function getData(){
 var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k");

 //get desired range

 return sheet;
}

index.html

In the

Body:
Getting the data is fairly easy. However this has to be properly done on both server side and client side.

For code.gs you will need to return actual data, but currently return sheet just returns the sheet object. What you need to do instead is

var vals = sheet.getDataRange().getValues()

which now gets you a 2D array of your sheet values. Now keep in mind that sheet has to be a sheet object not a spreadhseet object. So if your spreadsheet has many sheets, make sure you get the correct one with something like

var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheets()[0];

or

var sheet = SpreadsheetApp.openById("1NCNsdEGAHXWhZMEHnOflsIqElKdQSQxy83iM5vUIa9k").getSheetByName('Sheet1');

Now, since you want to grab the data as a JSON, all you really have to do is

vals = JSON.stringify(vals)

and now you have a JSON string of values. However that is just half of it, because your index.html that you wrote will not make use of the data as it calls the server side function, but does not listen for a response. In order to do that, you will need to use a success handler as written here. Essentially you will have to call a function in index.html that will make use of the returned vals variable. So something like

google.script.run.withSuccessHandler(useData).getData();

function useData(data) {
   data = JSON.parse(data)
   //now you have a 2D array in your index.html and you can use it as you wish within these client side scripts
}


问:
Rails - Show form only
I have a rails application that handles tool loan requests. I've scaffolded the model to handle all of the requests. I was wondering how I could make it so that when they access the request, to show only the form and not the index, and if possible, to have the index show on a different page.</p>

答:
In index action have something like this:

```<code>@object = Object.new
</code>```

and in index.html.erb:

```<code><%= render "form" %>
</code>```

Title: Rails - Show form only

Body:
In index action have something like this:

@object = Object.new

and in index.html.erb:

<%= render "form" %>


问:
Add extra column in sql to show ratio with previous row
I have a SQL table with a format like this:

```<code>SELECT period_id, amount FROM table;
+--------------------+
| period_id | amount |
+-----------+--------+
| 1         |    12  |
| 2         |    11  |
| 3         |    15  |
| 4         |    20  |
| ..        |    ..  |
+-----------+--------+
</code>```

I'd like to add an extra column (just in my select statement) that calculates the growth ratio with the previous amount, like so:

```<code>SELECT period_id, amount, [insert formula here] AS growth FROM table;
+-----------------------------+
| period_id | amount | growth |
+-----------+-----------------+
| 1         |    12  |        |
| 2         |    11  |   0.91 |  <-- 11/12
| 3         |    15  |   1.36 |  <-- 15/11
| 4         |    20  |   1.33 |  <-- 20/15
| ..        |    ..  |     .. |
+-----------+-----------------+
</code>```

Just need to work out how to perform the operation with the line before. Not interested in adding to the table. Any help appreciated :)

** also want to point out that period_id is in order but not necessarily increasing incrementally

答:
If you are using SQL Server 2012+ then go for John Cappelletti answer.

And If you are also less blessed like me then this below code work for you in the 2008 version too.

```<code>Declare @YourTable table (period_id int,amount int)
Insert Into @YourTable values
( 1,12),
( 2,11),
( 3,15),
( 4,20)

;WITH CTE AS (
    SELECT ROW_NUMBER() OVER (
            ORDER BY period_id
            ) SNO
        ,period_id
        ,amount
    FROM @YourTable
    )
SELECT C1.period_id
    ,C1.amount
    ,CASE
        WHEN C2.amount IS NOT NULL AND C2.amount<>0
            THEN CAST(C1.amount / CAST(C2.amount AS FLOAT) AS DECIMAL(18, 2))
        END AS growth
FROM CTE C1
LEFT JOIN CTE C2 ON C1.SNO = C2.SNO + 1
</code>```

Which works same as LAG.

```<code>+-----------+--------+--------+
| period_id | amount | growth |
+-----------+--------+--------+
|         1 |     12 | NULL   |
|         2 |     11 | 0.92   |
|         3 |     15 | 1.36   |
|         4 |     20 | 1.33   |
+-----------+--------+--------+
</code>```

Body:
I have a SQL table with a format like this:

SELECT period_id, amount FROM table;
+--------------------+
| period_id | amount |
+-----------+--------+
| 1         |    12  |
| 2         |    11  |
| 3         |    15  |
| 4         |    20  |
| ..        |    ..  |
+-----------+--------+

I'd like to add an extra column (just in my select statement) that calculates the growth ratio with the previous amount, like so:

SELECT period_id, amount, [insert formula here] AS growth FROM table;
+-----------------------------+
| period_id | amount | growth |
+-----------+-----------------+
| 1         |    12  |        |
| 2         |    11  |   0.91 |  <-- 11/12
| 3         |    15  |   1.36 |  <-- 15/11
| 4         |    20  |   1.33 |  <-- 20/15
| ..        |    ..  |     .. |
+-----------+-----------------+

Just need to work out how to perform the operation with the line before. Not interested in adding to the table. Any help appreciated :)

** also want to point out that period_id is in order but not necessarily increasing incrementally

Body:
If you are using SQL Server 2012+ then go for John Cappelletti answer.

And If you are also less blessed like me then this below code work for you in the 2008 version too.

Declare @YourTable table (period_id int,amount int)
Insert Into @YourTable values
( 1,12),
( 2,11),
( 3,15),
( 4,20)

;WITH CTE AS (
    SELECT ROW_NUMBER() OVER (
            ORDER BY period_id
            ) SNO
        ,period_id
        ,amount
    FROM @YourTable
    )
SELECT C1.period_id
    ,C1.amount
    ,CASE
        WHEN C2.amount IS NOT NULL AND C2.amount<>0
            THEN CAST(C1.amount / CAST(C2.amount AS FLOAT) AS DECIMAL(18, 2))
        END AS growth
FROM CTE C1
LEFT JOIN CTE C2 ON C1.SNO = C2.SNO + 1

Which works same as LAG.

+-----------+--------+--------+
| period_id | amount | growth |
+-----------+--------+--------+
|         1 |     12 | NULL   |
|         2 |     11 | 0.92   |
|         3 |     15 | 1.36   |
|         4 |     20 | 1.33   |
+-----------+--------+--------+


问:
Xcode debugger sometimes won't step into a method
Sometimes when I press the "step into" button in the Xcode debugger, it instead steps over the method call.

This happens even though the method is a method I wrote, and the source code is in the same project.

Can anyone explain how to prevent this?

答: You may need to Clean your targets in XCode.  Under the Build menu try Cleaning All and see if that resolves your issue.

ContentLicense: CC BY-SA 2.5


问:
How do I remove whitespace in HTML Source with Html Agility Pack and C#
Before posting I tried the solution from this thread:

C# - Remove spaces in HTML source in between markups?

Here is a snippet of the HTML I'm working with:

```<code><p>This is my text</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>This is next text</p>
</code>```

I'm using HTML Agility Pack to clean up the HTML:

```<code>HtmlDocument doc = new HtmlDocument();
doc.Load(htmlLocation);
foreach (var item in doc.DocumentNode.Descendants("p").ToList())
{
    if (item.InnerHtml == " ")
    {
        item.Remove();
    }
}
</code>```

The output of the code above is

```<code><p>This is my text</p>

<p>This is next text</p>
</code>```

So my problem is how do I remove the extra whitespace between the two paragraphs in the HTML source.

答:
Remove the text nodes between the first and last paragraphs:

HTML:

```<code>var html = @"
<p>This is my text</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>This is next text</p>";
</code>```

Parse it:

```<code>HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var paragraphs = doc.DocumentNode.Descendants("p").ToList();
foreach (var item in paragraphs)
{
    if (item.InnerHtml == " ") item.Remove();
}
var followingText = paragraphs[0]
    .SelectNodes(".//following-sibling::text()")
    .ToList();
foreach (var text in followingText)
{
    text.Remove();
}
</code>```

Result:

This is my text

This is next text

If you want to keep the line break between the paragraphs, use a for loop and call Remove() on all except the last text node.

```<code>for (int i = 0; i < followingText.Count - 1; ++i)
{
    followingText[i].Remove();
}
</code>```

Result:

```<code><p>This is my text</p>
<p>This is next text</p>
</code>```

Body:
Before posting I tried the solution from this thread:

C# - Remove spaces in HTML source in between markups?

Here is a snippet of the HTML I'm working with:

This is my text

This is next text

I'm using HTML Agility Pack to clean up the HTML:

HtmlDocument doc = new HtmlDocument();
doc.Load(htmlLocation);
foreach (var item in doc.DocumentNode.Descendants("p").ToList())
{
    if (item.InnerHtml == " ")
    {
        item.Remove();
    }
}

The output of the code above is

This is my text

This is next text

So my problem is how do I remove the extra whitespace between the two paragraphs in the HTML source.

Body:
Remove the text nodes between the first and last paragraphs:

HTML:

var html = @"
<p>This is my text</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>This is next text</p>";

Parse it:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var paragraphs = doc.DocumentNode.Descendants("p").ToList();
foreach (var item in paragraphs)
{
    if (item.InnerHtml == "&nbsp;") item.Remove();
}
var followingText = paragraphs[0]
    .SelectNodes(".//following-sibling::text()")
    .ToList();
foreach (var text in followingText)
{
    text.Remove();
}

Result:

<p>This is my text</p><p>This is next text</p>

If you want to keep the line break between the paragraphs, use a for loop and call Remove() on all except the last text node.

for (int i = 0; i < followingText.Count - 1; ++i)
{
    followingText[i].Remove();
}

Result:

<p>This is my text</p>
<p>This is next text</p>


问:
Regarding Current date comparision in Mysql
I am writing the below specified query which has no error but doesn't fetch me the correct record which matches current date of server, on other part it shows me old records

My Mysql Query:

```<code>select news_title,
    full_url,
    source_site,
    date_added,
    `category`
from tbl_urlLog
where category like '%enter%'
    or category like '%hollywood%'
    or category like '%bollywood%'
    or category like '%movies%'
    or category like '%film%'
    and date (`date_added`) = date (CURDATE())
group by `source_site`
order by `date_added` desc LIMIT 3
</code>```

答:
I am guessing you want to group together all the ORs using parentheses. Also, curdate() already is date no need to call date() on it.

```<code>select news_title,
    full_url,
    source_site,
    date_added,
    `category`
from tbl_urlLog
where (
        category like '%enter%'
        or category like '%hollywood%'
        or category like '%bollywood%'
        or category like '%movies%'
        or category like '%film%'
        )
    and date (`date_added`) = CURDATE()
group by `source_site`
order by `date_added` desc LIMIT 3
</code>```

Body:
I am writing the below specified query which has no error but doesn't fetch me the correct record which matches current date of server, on other part it shows me old records

My Mysql Query:

select news_title,
    full_url,
    source_site,
    date_added,
    `category`
from tbl_urlLog
where category like '%enter%'
    or category like '%hollywood%'
    or category like '%bollywood%'
    or category like '%movies%'
    or category like '%film%'
    and date (`date_added`) = date (CURDATE())
group by `source_site`
order by `date_added` desc LIMIT 3

Body:
I am guessing you want to group together all the ORs using parentheses. Also, curdate() already is date no need to call date() on it.

select news_title,
    full_url,
    source_site,
    date_added,
    `category`
from tbl_urlLog
where (
        category like '%enter%'
        or category like '%hollywood%'
        or category like '%bollywood%'
        or category like '%movies%'
        or category like '%film%'
        )
    and date (`date_added`) = CURDATE()
group by `source_site`
order by `date_added` desc LIMIT 3


答:
To get a cumulative count grouped by a given variable, you would generally use the ave() function with the cumsum() function:

```<code>#first arg is input to cumsum (set to 1 here), second arg is grouping variable
ave(rep(1, nrow(ds)), ds$visitIp, FUN = cumsum)
</code>```

To get a reverse counter by group, you would just reverse the grouping vector (second argument), to get the counter reversed, then reverse the result to match it back up to your data:

```<code>rev(ave(rep(1, nrow(ds)), rev(ds$visitIp), FUN = cumsum))
</code>```

Title: Update column values on some condition in R

Body:
    > ds[1:20,1:5]
   idSite idVisit         visitIp        visitorId   type
1       1    4103     8.37.230.12 0b146529434a43e3 action
2       1    4103     8.37.230.12 0b146529434a43e3 action
4       1    4100 117.212.128.163 2fda542e2cac67d4 action
5       1    4100 117.212.128.163 2fda542e2cac67d4 action
6       1    4100 117.212.128.163 2fda542e2cac67d4 action
8       1    4102  187.134.160.17 ab2413b2ed5bccc4 action
11      1    4099  168.235.201.23 5e8b3f87bd30cc1b action
12      1    4099  168.235.201.23 5e8b3f87bd30cc1b action
13      1    4099  168.235.201.23 5e8b3f87bd30cc1b action
14      1    4099  168.235.201.23 5e8b3f87bd30cc1b action
16      1    4101   5.107.224.242 fc77e4a99d153c16 action
19      1    4098  119.156.96.132 d083c7814aefc5e4 action
21      1    4097  95.221.204.238 87b98db4b05df2b0 action
23      1    4096  122.173.30.126 4386834b62126a2b action
25      1    4092   42.109.204.55 4744bd421d7f06b8 action
26      1    4092   42.109.204.55 4744bd421d7f06b8 action
27      1    4092   42.109.204.55 4744bd421d7f06b8 action
28      1    4092   42.109.204.55 4744bd421d7f06b8 action
29      1    4092   42.109.204.55 4744bd421d7f06b8 action
32      1    4041   49.35.130.191 eb8795f74c372b41 action

In the above dataframe I want to go from last row to first and rename the column type as "action1"/"action2/.."and so on but only for a specific visitIp as shown below

    > dactions[1:20,1:5]
   idSite idVisit         visitIp        visitorId    type
1       1    4103     8.37.230.12 0b146529434a43e3 action2
2       1    4103     8.37.230.12 0b146529434a43e3 action1
4       1    4100 117.212.128.163 2fda542e2cac67d4 action3
5       1    4100 117.212.128.163 2fda542e2cac67d4 action2
6       1    4100 117.212.128.163 2fda542e2cac67d4 action1
8       1    4102  187.134.160.17 ab2413b2ed5bccc4 action1
11      1    4099  168.235.201.23 5e8b3f87bd30cc1b action4
12      1    4099  168.235.201.23 5e8b3f87bd30cc1b action3
13      1    4099  168.235.201.23 5e8b3f87bd30cc1b action2
14      1    4099  168.235.201.23 5e8b3f87bd30cc1b action1
16      1    4101   5.107.224.242 fc77e4a99d153c16 action1
19      1    4098  119.156.96.132 d083c7814aefc5e4 action1
21      1    4097  95.221.204.238 87b98db4b05df2b0 action1
23      1    4096  122.173.30.126 4386834b62126a2b action1
25      1    4092   42.109.204.55 4744bd421d7f06b8 action5
26      1    4092   42.109.204.55 4744bd421d7f06b8 action4
27      1    4092   42.109.204.55 4744bd421d7f06b8 action3
28      1    4092   42.109.204.55 4744bd421d7f06b8 action2
29      1    4092   42.109.204.55 4744bd421d7f06b8 action1
32      1    4041   49.35.130.191 eb8795f74c372b41 action4

I have a code using for loop for this but it's taking considerably too much time in case of large dataframe (more than 30k rows) I want to avoid the for loop so that this can be done faster. My code is as follows

    #rename actions
ds$type<-as.characterds$type)
count<-0
visitedIp<-""
for(i in nrow(ds):1){
  if(ds[i,]$visitIp!=visitedIp){
    count<-1
    visitedIp<-ds[i,]$visitIp
    ds[i,]$type<-paste0(ds[i,]$type,as.character(count))
    next
  }else{
    count<-count+1
    ds[i,]$type<-paste0(ds[i,]$type,as.character(count))
  }
}
dactions<-ds

Thanks in advance.

Body:
To get a cumulative count grouped by a given variable, you would generally use the ave() function with the cumsum() function:

#first arg is input to cumsum (set to 1 here), second arg is grouping variable
ave(rep(1, nrow(ds)), ds$visitIp, FUN = cumsum)

To get a reverse counter by group, you would just reverse the grouping vector (second argument), to get the counter reversed, then reverse the result to match it back up to your data:

rev(ave(rep(1, nrow(ds)), rev(ds$visitIp), FUN = cumsum))


问:
How to use dynamic table in SQL query "Select * From $var; " $var is fetching from another file
In below code i want to use $var as tablename, and the vale for $var is coming from another file. $var value is the name of table. So i want the dynamic tablenaame in sql query. but when i am executing following code then sql query is not taking $var value. But when i am declaring $var value in this file as static value then it is executing correctly. so please help me ...how to use variable as tablename in sql query.</p>

```<code>include_once("set_team.php");
// Create connection
$conn = mysqli_connect($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

ob_start();
echo $table;
$var = ob_get_clean();

$sql = "SELECT * FROM $var";
$res = mysqli_query($conn,$sql);
$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[1]
));
}
        echo json_encode(array("result"=>$result));

$conn->close();
</code>```

答:
Yes you can dynamically select tables in sql. You would have to pass the variable and then use it. Php provides Variable interpolation, which I find easier to both write and read, hence you can directly insert the $var_value within the string.

you can try Methods such as sessions, cookies, GET, POST variables.

Session:

```<code>//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];
$sql_query = "select * from $var_value";
</code>```

Run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

```<code>//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];
$sql_query = "select * from $var_value";
</code>```

The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies.

GET and POST

You can add the variable in the link to the next page:

```<code>$var_value = $_POST['varname'];
$sql_query = "select * from $var_value";

        or

$var_value = $_GET['varname'];
$sql_query = "select * from $var_value";
</code>```

This will create a POST/ GET variable.

Body:
In below code i want to use $var as tablename, and the vale for $var is coming from another file. $var value is the name of table. So i want the dynamic tablenaame in sql query. but when i am executing following code then sql query is not taking $var value. But when i am declaring $var value in this file as static value then it is executing correctly. so please help me ...how to use variable as tablename in sql query.

include_once("set_team.php");
// Create connection
$conn = mysqli_connect($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

ob_start();
echo $table;
$var = ob_get_clean();

$sql = "SELECT * FROM $var";
$res = mysqli_query($conn,$sql);
$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[1]
));
}
        echo json_encode(array("result"=>$result));

$conn->close();

Body:
Yes you can dynamically select tables in sql. You would have to pass the variable and then use it. Php provides Variable interpolation, which I find easier to both write and read, hence you can directly insert the $var_value within the string.

you can try Methods such as sessions, cookies, GET, POST variables.

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];
$sql_query = "select * from $var_value";

Run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];
$sql_query = "select * from $var_value";

The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies.

GET and POST

You can add the variable in the link to the next page:

$var_value = $_POST['varname'];
$sql_query = "select * from $var_value";

        or

$var_value = $_GET['varname'];
$sql_query = "select * from $var_value";

This will create a POST/ GET variable.


问:
Do statically linked libraries require linking with their dependencies?
I'm building an executable that depends on a static library A which in turn depends on a static library B. When I build my application, do I need to also link against B in my build script?

To be more specific, do I need to do -la -lb, or, just linking with A via -la is enough?

答:
You might or might not have to link with both libraries, depending on how A was built.

If A contains a linker comment record instructing the linker to also look in library B for symbols (typically included in one of the object files contained within A), you don't need to include B when you link.  If A does not contain that comment record, you must include it yourself.


问:
C++ How to make a variable true if another variable WAS true
I was wonder how could I make a bool true if another bool was true for example with this program :

for(int i=1;i<5;i++){
  if (i == 3){
    x = false;
  } else{
    x = true;
  }

  if(x){
    cout << "true";
  }else{
    cout << "false";
  }
}

output :
true
true
false
true
true
```

<p>how would I make it so that the output is this: </p>

```output:
true
true
false
false
false
```

sorry if this is hard to understand I'm not the best at explaining

答:
Try this code</p>

```<code>x = true;

for(int i=1;i<5;i++){
  if (i == 3){
    x = false;
  }

  if(x){
    cout << "true";
  }else{
    cout << "false";
  }
}
</code>```

Body:
I was wonder how could I make a bool true if another bool was true for example with this program :

for(int i=1;i<5;i++){
  if (i == 3){
    x = false;
  } else{
    x = true;
  }

  if(x){
    cout << "true";
  }else{
    cout << "false";
  }
}

output :
true
true
false
true
true

how would I make it so that the output is this:

output:
true
true
false
false
false

sorry if this is hard to understand I'm not the best at explaining

Body:
Try this code

x = true;

for(int i=1;i<5;i++){
  if (i == 3){
    x = false;
  }

  if(x){
    cout << "true";
  }else{
    cout << "false";
  }
}


问:
Which dialect of C is Objective-C a "strict superset" of?
I frequently hear that Objective-C is a "strict superset" of the C programming language. There are several dialects/standards of C (ie. K&R, ANSI C, C90, C99, GNU extensions...); Objective-C was first developed in the early 1980s, so it has to predate these standards. However, Objective-C 2.0 is from around 2006 or 2007, so it could be based on a more modern C dialect. So, which "C" is Objective-C a superset of?</p>

答: There's a corresponding "dialect" of Objective-C for all the standard dialects of C.</p>


问:
Pandas: Multiplying two columns of same dataframe thats dependent on third column
How can I multiply two columns of within a same dataframe? My dataframe looks like below image and I want to output like this. However, I cannot find how to multiply two columns that are dependent on first row of same dataframe. I would really appreciate some help on this.

```<code>request                            totalbytes
/login                              8520
/shuttle/countdown/                 7970
/shuttle/countdown/liftoff.html     0
</code>```

So far my output is below, but how can I get unique rows.

答:
It seems need simply multiple columns:

```<code>df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
</code>```

Or use mul:

```<code>df['totalbytes'] = df['bytesbytes'].mul(df['bytesfrequency'])
</code>```

Sample:

```<code>df = pd.DataFrame({'bytesbytes':[3985,1420,0,0],
                   'bytesfrequency':[2,6,2,2]})

df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
print (df)
   bytesbytes  bytesfrequency  totalbytes
0        3985               2        7970
1        1420               6        8520
2           0               2           0
3           0               2           0
</code>```

But maybe need groupby by first column request and use transform for create new Series which is multiple (both columns are converted by transform, maybe need only one):

```<code>df = pd.DataFrame({ 'request':['a','a','b','b'],
                   'bytesbytes':[3985,1420,1420,0],
                   'bytesfrequency':[2,6,6,2]})

g = df.groupby('request')

print (g['bytesbytes'].transform('first'))
0    3985
1    3985
2    1420
3    1420
Name: bytesbytes, dtype: int64

print (g['bytesfrequency'].transform('first'))
0    2
1    2
2    6
3    6
Name: bytesfrequency, dtype: int64

df['totalbytes'] = g['bytesbytes'].transform('first')*g['bytesfrequency'].transform('first')
print (df)
   bytesbytes  bytesfrequency request  totalbytes
0        3985               2       a        7970
1        1420               6       a        7970
2        1420               6       b        8520
3           0               2       b        8520
</code>```

EDIT:

If need remove duplicates by request column:

```<code>df = pd.DataFrame({ 'request':['a','a','b','b'],
                   'bytesbytes':[3985,1420,1420,0],
                   'bytesfrequency':[2,6,6,2]})

print (df)
   bytesbytes  bytesfrequency request
0        3985               2       a
1        1420               6       a
2        1420               6       b
3           0               2       b
</code>```

One line solution - drop_duplicates, multiple and last drop columns:

```<code>df = df.drop_duplicates('request')
       .assign(totalbytes=df['bytesbytes']*df['bytesfrequency'])
       .drop(['bytesbytes','bytesfrequency'], axis=1)
print (df)
  request  totalbytes
0       a        7970
2       b        8520
</code>```

```<code>df = df.drop_duplicates('request')
df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
df = df.drop(['bytesbytes','bytesfrequency'], axis=1)
print (df)
  request  totalbytes
0       a        7970
2       b        8520
</code>```

Body:
How can I multiply two columns of within a same dataframe? My dataframe looks like below image and I want to output like this. However, I cannot find how to multiply two columns that are dependent on first row of same dataframe. I would really appreciate some help on this.

request                            totalbytes
/login                              8520
/shuttle/countdown/                 7970
/shuttle/countdown/liftoff.html     0

So far my output is below, but how can I get unique rows.

Body:
It seems need simply multiple columns:

df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']

Or use mul:

df['totalbytes'] = df['bytesbytes'].mul(df['bytesfrequency'])

Sample:

df = pd.DataFrame({'bytesbytes':[3985,1420,0,0],
                   'bytesfrequency':[2,6,2,2]})

df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
print (df)
   bytesbytes  bytesfrequency  totalbytes
0        3985               2        7970
1        1420               6        8520
2           0               2           0
3           0               2           0

But maybe need groupby by first column request and use transform for create new Series which is multiple (both columns are converted by transform, maybe need only one):

df = pd.DataFrame({ 'request':['a','a','b','b'],
                   'bytesbytes':[3985,1420,1420,0],
                   'bytesfrequency':[2,6,6,2]})

g = df.groupby('request')

print (g['bytesbytes'].transform('first'))
0    3985
1    3985
2    1420
3    1420
Name: bytesbytes, dtype: int64

print (g['bytesfrequency'].transform('first'))
0    2
1    2
2    6
3    6
Name: bytesfrequency, dtype: int64

df['totalbytes'] = g['bytesbytes'].transform('first')*g['bytesfrequency'].transform('first')
print (df)
   bytesbytes  bytesfrequency request  totalbytes
0        3985               2       a        7970
1        1420               6       a        7970
2        1420               6       b        8520
3           0               2       b        8520

EDIT:

If need remove duplicates by request column:

df = pd.DataFrame({ 'request':['a','a','b','b'],
                   'bytesbytes':[3985,1420,1420,0],
                   'bytesfrequency':[2,6,6,2]})

print (df)
   bytesbytes  bytesfrequency request
0        3985               2       a
1        1420               6       a
2        1420               6       b
3           0               2       b

One line solution - drop_duplicates, multiple and last drop columns:

df = df.drop_duplicates('request')
       .assign(totalbytes=df['bytesbytes']*df['bytesfrequency'])
       .drop(['bytesbytes','bytesfrequency'], axis=1)
print (df)
  request  totalbytes
0       a        7970
2       b        8520

df = df.drop_duplicates('request')
df['totalbytes'] = df['bytesbytes']*df['bytesfrequency']
df = df.drop(['bytesbytes','bytesfrequency'], axis=1)
print (df)
  request  totalbytes
0       a        7970
2       b        8520


问:
Writing a "simple calculator for 32-bit integers" in MASM using the Irvine32 library. How can I fix this "write access violation" error?
Here is the assignment:

Here is the link to the documentation for the Irvine32 library (which I must use): http://programming.msjc.edu/asm/help/

Right now I'm just experimenting with how to make a successful template prompt/output, and i'm starting with the addition operation. My issue is that I get a "write access violation" when trying to use WriteString (an Irvine32 procedure) to print the first line of response output. It does print the text on the console, but the error comes up immediately after. What confuses me is that earlier in the program I successfully use WriteString for other strings; it's weird that it doesn't work here.

Here is a screenshot of the error displayed during debugging:

Here is my code:

```<code>.386
.MODEL flat,stdcall
.STACK 4096
ExitProcess PROTO,dwExitCode:DWORD
WriteString PROTO
ReadDec PROTO

.DATA

promptLineOne DB "1.  X + Y                    6.  X and Y",13,10,0
promptLineTwo DB "2.  X - Y                    7.  X or Y",13,10,0
promptLineThree DB "3.  X * Y                    8.  not X",13,10,0
promptLineFour DB "4.  X / Y                    9.  X xor Y",13,10,0
promptLineFive DB "5.  X mod Y                    10.  Exit Program",13,10,0
adding DB "Adding X and Y; enter X, then enter Y",0
added DB "The sum of X and Y is: ",0
tryAgain DB "Try again",0

.CODE

prompt PROC
  MOV ECX,5
  MOV EAX,0
  MOV EDI,OFFSET promptLineOne
  L1:
    MOV EDX,EDI
    INVOKE WriteString
    L2:
        INC EDI
        MOV AL,[EDI]
        CMP EAX,0
        JNZ L2
        INC EDI
    LOOP L1

RET
prompt ENDP

calculate PROC
  MOV EDX,OFFSET adding
  INVOKE WriteString
  op1 DD ?
  op2 DD ?
  result DD ?
  L1:
    INVOKE ReadDec
    JNC chastise
    JC FirstPass
    JNC L1
  FirstPass:
    MOV op1,EAX
  L2:
    INVOKE ReadDec
    JNC chastise
    JC SecondPass
    JNC L2
  SecondPass:
    MOV op2,EAX
    ADD EAX,op1
    ADD EAX,op2
    MOV result,EAX

    MOV EDX,OFFSET added
    INVOKE WriteString
    MOV EDX,OFFSET result
    INVOKE WriteString
RET
calculate ENDP

chastise PROC
  MOV EDX,OFFSET tryAgain
  INVOKE WriteString
RET
chastise ENDP

main PROC
  INVOKE prompt
  INVOKE ReadDec
  INVOKE calculate

  INVOKE ExitProcess,0
main ENDP

END main
</code>```

Thanks for taking a look! :)

答:
Unlike c++, asm doesn't allow you to define variables at any point in your code.  Like this:

```<code>calculate PROC
  MOV EDX,OFFSET adding
  INVOKE WriteString
  op1 DD ?
  op2 DD ?
  result DD ?
  L1:
    INVOKE ReadDec
    JNC chastise
</code>```

This will do the mov, do the invoke, then attempt to execute whatever instruction lives at op1.  Since the ? means the contents of this location are undefined, who knows what it contains?  For sure it isn't going to do what you intend.

It's easy to get used to high level languages where the compiler knows the difference between data and code.  But in asm, if you put it in your .code section, it's code.

Body:
Here is the assignment:

Here is the link to the documentation for the Irvine32 library (which I must use): http://programming.msjc.edu/asm/help/

Right now I'm just experimenting with how to make a successful template prompt/output, and i'm starting with the addition operation. My issue is that I get a "write access violation" when trying to use WriteString (an Irvine32 procedure) to print the first line of response output. It does print the text on the console, but the error comes up immediately after. What confuses me is that earlier in the program I successfully use WriteString for other strings; it's weird that it doesn't work here.

Here is a screenshot of the error displayed during debugging:

Here is my code:

.386
.MODEL flat,stdcall
.STACK 4096
ExitProcess PROTO,dwExitCode:DWORD
WriteString PROTO
ReadDec PROTO

.DATA

promptLineOne DB "1.  X + Y                    6.  X and Y",13,10,0
promptLineTwo DB "2.  X - Y                    7.  X or Y",13,10,0
promptLineThree DB "3.  X * Y                    8.  not X",13,10,0
promptLineFour DB "4.  X / Y                    9.  X xor Y",13,10,0
promptLineFive DB "5.  X mod Y                    10.  Exit Program",13,10,0
adding DB "Adding X and Y; enter X, then enter Y",0
added DB "The sum of X and Y is: ",0
tryAgain DB "Try again",0

.CODE

prompt PROC
  MOV ECX,5
  MOV EAX,0
  MOV EDI,OFFSET promptLineOne
  L1:
    MOV EDX,EDI
    INVOKE WriteString
    L2:
        INC EDI
        MOV AL,[EDI]
        CMP EAX,0
        JNZ L2
        INC EDI
    LOOP L1

RET
prompt ENDP

calculate PROC
  MOV EDX,OFFSET adding
  INVOKE WriteString
  op1 DD ?
  op2 DD ?
  result DD ?
  L1:
    INVOKE ReadDec
    JNC chastise
    JC FirstPass
    JNC L1
  FirstPass:
    MOV op1,EAX
  L2:
    INVOKE ReadDec
    JNC chastise
    JC SecondPass
    JNC L2
  SecondPass:
    MOV op2,EAX
    ADD EAX,op1
    ADD EAX,op2
    MOV result,EAX

    MOV EDX,OFFSET added
    INVOKE WriteString
    MOV EDX,OFFSET result
    INVOKE WriteString
RET
calculate ENDP

chastise PROC
  MOV EDX,OFFSET tryAgain
  INVOKE WriteString
RET
chastise ENDP

main PROC
  INVOKE prompt
  INVOKE ReadDec
  INVOKE calculate

  INVOKE ExitProcess,0
main ENDP

END main

Thanks for taking a look! :)

Body:
Unlike c++, asm doesn't allow you to define variables at any point in your code.  Like this:

calculate PROC
  MOV EDX,OFFSET adding
  INVOKE WriteString
  op1 DD ?
  op2 DD ?
  result DD ?
  L1:
    INVOKE ReadDec
    JNC chastise

This will do the mov, do the invoke, then attempt to execute whatever instruction lives at op1.  Since the ? means the contents of this location are undefined, who knows what it contains?  For sure it isn't going to do what you intend.

It's easy to get used to high level languages where the compiler knows the difference between data and code.  But in asm, if you put it in your .code section, it's code.


问:
Items Don't Stay Where Placed With Drag Drop Feature in Android Studio
So Android Studio has the drag/drop feature in the design tab. I am able to place the elements where I want them, and the layout looks great on the screen.

However, when I go to run the app emulator, it looks completely different. Everything gets shoved up to the top-left hand corner of the screen, nowhere near where I placed it in design mode.

Is there a way to have your elements show the same way in the emulator, as the way you place them in design mode? Right now I'm having to go back and edit all the code each time.

I have my code below, as well as a image link below to further clarify my point.Comparison of Design mode vs App Emulator

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.luke.currencyconverter.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter The Amount in Dollars"
        tools:layout_editor_absoluteX="-159dp"
        tools:layout_editor_absoluteY="126dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="403dp"
        android:layout_height="0dp"
        android:text="Enter The Amount in Dollars:"
        android:textColor="@android:color/black"
        android:textSize="22sp"
        tools:layout_editor_absoluteX="33dp"
        tools:layout_editor_absoluteY="365dp" />

    <ImageView
        android:id="@+id/currency"
        android:layout_width="361dp"
        android:layout_height="450dp"
        app:srcCompat="@drawable/currency"
        tools:layout_editor_absoluteX="12dp"
        tools:layout_editor_absoluteY="-117dp" />

    <Button
        android:id="@+id/convert"
        android:layout_width="361dp"
        android:layout_height="wrap_content"
        android:onClick="convert"
        android:text="Convert"
        tools:layout_editor_absoluteX="12dp"
        tools:layout_editor_absoluteY="462dp" />

    <EditText
        android:id="@+id/dollarField"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="408dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答: I figured it out. I was using "constraint layout", and I needed to use "relative layout".</p>

Body:
So Android Studio has the drag/drop feature in the design tab. I am able to place the elements where I want them, and the layout looks great on the screen.

However, when I go to run the app emulator, it looks completely different. Everything gets shoved up to the top-left hand corner of the screen, nowhere near where I placed it in design mode.

Is there a way to have your elements show the same way in the emulator, as the way you place them in design mode? Right now I'm having to go back and edit all the code each time.

I have my code below, as well as a image link below to further clarify my point.Comparison of Design mode vs App Emulator

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.luke.currencyconverter.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter The Amount in Dollars"
        tools:layout_editor_absoluteX="-159dp"
        tools:layout_editor_absoluteY="126dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="403dp"
        android:layout_height="0dp"
        android:text="Enter The Amount in Dollars:"
        android:textColor="@android:color/black"
        android:textSize="22sp"
        tools:layout_editor_absoluteX="33dp"
        tools:layout_editor_absoluteY="365dp" />

    <ImageView
        android:id="@+id/currency"
        android:layout_width="361dp"
        android:layout_height="450dp"
        app:srcCompat="@drawable/currency"
        tools:layout_editor_absoluteX="12dp"
        tools:layout_editor_absoluteY="-117dp" />

    <Button
        android:id="@+id/convert"
        android:layout_width="361dp"
        android:layout_height="wrap_content"
        android:onClick="convert"
        android:text="Convert"
        tools:layout_editor_absoluteX="12dp"
        tools:layout_editor_absoluteY="462dp" />

    <EditText
        android:id="@+id/dollarField"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="408dp" />

</android.support.constraint.ConstraintLayout>


问:
Automatic YouTube transcript alignment. How to do?
We have many videos on YouTube and we would like to offer automatic YouTube transcript alignment for site visitors. What we want is pretty much like this example.

But instead of word by word automatic alignment, we would like sentence by sentence alignment, such as this example (please click the "Show Transcript" button)

We have captions for our YouTube videos already. We want to put transcript and video side by side, exactly like the example on 3playmedia.com.

Could anyone kindly suggest me how to do that?

Thank you!

答:
There is a paid solution at voicebase.com which even does PCI - Compliance and redaction (http://voicebase.readthedocs.io/en/v2-beta/how-to-guides/pci-ssn-pii-detection.html)

I have not tried it yet but looks very promising.


问:
How to store a binary object in redis using node?
I am trying to save a binary object in redis and then serve it back as an image.

Here is the code I am using to save the data:

```<code>var buff=new Buffer(data.data,'base64');
client.set(key,new Buffer(data.data,'base64'));
</code>```

Here is the code to dump the data out:

```<code>client.get(key,function(err,reply){
        var data = reply;
        response.writeHead(200, {"Content-Type": "image/png"});
        response.end(data,'binary');

});
</code>```

The first few byte of the data seem to be corrupted. The magic number is incorrect.

Did some experimenting:

when I do the following:

```<code>var buff=new Buffer(data.data,'base64');
console.log(buff.toString('binary'));
</code>```

I get this:

0000000: c289 504e 470d 0a1a 0a00 0000 0d49 4844

when I do this

```<code> var buff=new Buffer(data.data,'base64');
 console.log(buff);
</code>```

I get the following:

Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00

I am not sure where the c2 is coming from

答: What worked for me is to use data.toString('binary') if it is a Buffer. Also make sure not to reinterpret it as utf-8, but also as binary.

Body:
I am trying to save a binary object in redis and then serve it back as an image.

Here is the code I am using to save the data:

var buff=new Buffer(data.data,'base64');
client.set(key,new Buffer(data.data,'base64'));

Here is the code to dump the data out:

client.get(key,function(err,reply){
        var data = reply;
        response.writeHead(200, {"Content-Type": "image/png"});
        response.end(data,'binary');

});

The first few byte of the data seem to be corrupted. The magic number is incorrect.

Did some experimenting:

when I do the following:

var buff=new Buffer(data.data,'base64');
console.log(buff.toString('binary'));

I get this:

0000000: c289 504e 470d 0a1a 0a00 0000 0d49 4844

when I do this

 var buff=new Buffer(data.data,'base64');
 console.log(buff);

I get the following:

Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00

I am not sure where the c2 is coming from


问:
how to disconnect from mqtt server using eclipse paho javascript client
I have an application in which am connecting to a mqtt server i followed this link  and made some more modifications and made a connection with a username and password,how to disconnect from that server

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Paho} from 'ng2-mqtt/mqttws31';

/*
  Generated class for the MqttService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Mqttservice {

  client :any;
  message :any;
  topic : any ;
  user:any;

   constructor(public http: Http) {}

 connectToMqtt(user,pwd){
  this.client = new Paho.MQTT.Client("iot.eclipse.org",9001,user);
    this.client.onConnectionLost = this.onConnectionLost;
  this.client.onMessageArrived = this.onMessageArrived.bind(this);
    // connect the client
    this.client.connect({onSuccess:this.onConnect.bind(this),userName:user,password:Pwd});
 }

 // called when the client connects
  onConnect() {
     console.log("onConnect");
   }

   //subscribe to a topic
   subscribe(topic){
    this.topic = topic ;
    this.client.subscribe(this.topic);
        console.log("subscribed to a topic");
   }
   //send a message
   publish(topic,msg){
    this.topic = topic ;
    this.message = new Paho.MQTT.Message(msg);
    this.message.destinationName = this.topic;
    this.client.send(this.message);

   }

 // called when the client loses its connection
  onConnectionLost(responseObject) {
    console.log("connection is lost");
    if (responseObject.errorCode !== 0) {
       console.log("onConnectionLost:"+responseObject.errorMessage);
      }
   }

 // called when a message arrives
  onMessageArrived(message) {
     console.log("message is from topic: "+message.destinationName);

 }

}```

how to disconnect from server using disconnect() just like publish() or subscribe() that I used in code sample

答:
disconnect() {
      console.log("client is disconnecting..");
      this.client.disconnect();
 }```

just call the disconnect() as per the Paho documentation

Body:
I have an application in which am connecting to a mqtt server i followed this link  and made some more modifications and made a connection with a username and password,how to disconnect from that server

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Paho} from 'ng2-mqtt/mqttws31';

/*
  Generated class for the MqttService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class Mqttservice {

  client :any;
  message :any;
  topic : any ;
  user:any;

   constructor(public http: Http) {}

 connectToMqtt(user,pwd){
  this.client = new Paho.MQTT.Client("iot.eclipse.org",9001,user);
    this.client.onConnectionLost = this.onConnectionLost;
  this.client.onMessageArrived = this.onMessageArrived.bind(this);
    // connect the client
    this.client.connect({onSuccess:this.onConnect.bind(this),userName:user,password:Pwd});
 }

 // called when the client connects
  onConnect() {
     console.log("onConnect");
   }

   //subscribe to a topic
   subscribe(topic){
    this.topic = topic ;
    this.client.subscribe(this.topic);
        console.log("subscribed to a topic");
   }
   //send a message
   publish(topic,msg){
    this.topic = topic ;
    this.message = new Paho.MQTT.Message(msg);
    this.message.destinationName = this.topic;
    this.client.send(this.message);

   }

 // called when the client loses its connection
  onConnectionLost(responseObject) {
    console.log("connection is lost");
    if (responseObject.errorCode !== 0) {
       console.log("onConnectionLost:"+responseObject.errorMessage);
      }
   }

 // called when a message arrives
  onMessageArrived(message) {
     console.log("message is from topic: "+message.destinationName);

 }

}

how to disconnect from server using disconnect() just like publish() or subscribe() that I used in code sample

Body:
disconnect() {
      console.log("client is disconnecting..");
      this.client.disconnect();
 }

just call the disconnect() as per the Paho documentation


问:
DR1 is a 'variable' but is used like a 'method' .. this
this is my code.. and it showes that DR1 is a variable and is being used as a method please can some one explain this for me and how can i fix it i need to get the data from the database and post it on a label </p>

```<code>    SqlConnection sqlConnection1 = new SqlConnection("sql connection");
    SqlCommand cmd = new SqlCommand();

    cmd.CommandText = "Select * from request where reqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
    //cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    SqlDataReader DR1;
    DR1 = cmd.ExecuteReader();
    DR1.Read();

         if (DR1.HasRows)
        {
            lbl_reqNoV.Text = DR1("ReqNo");
   }
</code>```

答:
This line is your problem:

```<code> lbl_reqNoV.Text = DR1("ReqNo");
</code>```

DR1 is a variable.  But DR1() uses the syntax of a method call.

You probably meant this:

```<code>lbl_reqNoV.Text = DR1["ReqNo"];
</code>```

Or possibly

```<code>lbl_reqNoV.Text = DR1.GetString("ReqNo");
</code>```

Body:
this is my code.. and it showes that DR1 is a variable and is being used as a method please can some one explain this for me and how can i fix it i need to get the data from the database and post it on a label

    SqlConnection sqlConnection1 = new SqlConnection("sql connection");
    SqlCommand cmd = new SqlCommand();

    cmd.CommandText = "Select * from request where reqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
    //cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    SqlDataReader DR1;
    DR1 = cmd.ExecuteReader();
    DR1.Read();

         if (DR1.HasRows)
        {
            lbl_reqNoV.Text = DR1("ReqNo");
   }

Body:
This line is your problem:

 lbl_reqNoV.Text = DR1("ReqNo");

DR1 is a variable.  But DR1() uses the syntax of a method call.

You probably meant this:

lbl_reqNoV.Text = DR1["ReqNo"];

Or possibly

lbl_reqNoV.Text = DR1.GetString("ReqNo");


问:
ClassLoader.loadClass() surprisingly throws NoClassDefFoundError instead of a ClassNotFoundException
I have a class named as MyClass, so when i called
classloader.loadClass("myclass") throws a NoClassDefFoundError instead of a ClassNotFoundException.

Note - I have changed the upper case letter to small case letter

When i used completely different string "ABC" i get  ClassNotFoundException as expected .

Please find the code snippet below.

```<code>    public class Test {

    public static void main(String[] args) {
        // normal conditions
        try {
            Test.class.getClassLoader().loadClass("MyClass");
            System.out.println(" Successfully loaded an existing class ");
        } catch (ClassNotFoundException notExpected) {

        }

        // expected
        try {
            Test.class.getClassLoader().loadClass("ABC");
        } catch (ClassNotFoundException expected) {
            System.out.println("Expected");
        }

        try {
            Test.class.getClassLoader().loadClass("myclass");
        } catch (ClassNotFoundException expected) {
            System.out.println("Expected but not coming");
        }
    }
}
</code>```

//

```<code>// sample class used for the above in separate file
//
public class MyClass
{

}
</code>```

OutPut:

```<code>Successfully loaded an existing class
Expected
Exception in thread "main" java.lang.NoClassDefFoundError: myclass (wrong name: MyClass)
</code>```

[![Output on Java 8 Machine][1]][1]

It is not duplicate as I am looking for different exceptions on name change scenario please check again

答:
I've copied your program as is and run on my machine (Java jdk1.8.0_121 on Windows 10). The output it has produced is:

```<code>Expected
Expected but not coming
</code>```

So probably you have some previous parts of your tests that have not been deleted or alternatively you're running on a jvm that has a bug that has been fixed in more recent version (unlikely to be so but the possibility still exists).

There is a pretty nice article on those exceptions: available here

So NoClassDefFoundError (its an Error, not just an exception, btw!) is thrown when the class was available during compile time, but later on has been removed from the classpath in runtime. JVM really counts on this class, but it doesn't exist so JVM is forced to throw an error like this.

Could you please recompile your project and make sure that you don't really have "myclass.java" as a file on disk during the compilation?

Another option I would check is upgrading your JVM to the most recent version and trying again.

Body:
I have a class named as MyClass, so when i called
classloader.loadClass("myclass") throws a NoClassDefFoundError instead of a ClassNotFoundException.

Note - I have changed the upper case letter to small case letter

When i used completely different string "ABC" i get  ClassNotFoundException as expected .

Please find the code snippet below.

    public class Test {

    public static void main(String[] args) {
        // normal conditions
        try {
            Test.class.getClassLoader().loadClass("MyClass");
            System.out.println(" Successfully loaded an existing class ");
        } catch (ClassNotFoundException notExpected) {

        }

        // expected
        try {
            Test.class.getClassLoader().loadClass("ABC");
        } catch (ClassNotFoundException expected) {
            System.out.println("Expected");
        }

        try {
            Test.class.getClassLoader().loadClass("myclass");
        } catch (ClassNotFoundException expected) {
            System.out.println("Expected but not coming");
        }
    }
}

//

// sample class used for the above in separate file
//
public class MyClass
{

}

OutPut:

Successfully loaded an existing class
Expected
Exception in thread "main" java.lang.NoClassDefFoundError: myclass (wrong name: MyClass)

[![Output on Java 8 Machine][1]][1]

It is not duplicate as I am looking for different exceptions on name change scenario please check again

Body:
I've copied your program as is and run on my machine (Java jdk1.8.0_121 on Windows 10). The output it has produced is:

Expected
Expected but not coming

So probably you have some previous parts of your tests that have not been deleted or alternatively you're running on a jvm that has a bug that has been fixed in more recent version (unlikely to be so but the possibility still exists).

There is a pretty nice article on those exceptions: available here

So NoClassDefFoundError (its an Error, not just an exception, btw!) is thrown when the class was available during compile time, but later on has been removed from the classpath in runtime. JVM really counts on this class, but it doesn't exist so JVM is forced to throw an error like this.

Could you please recompile your project and make sure that you don't really have "myclass.java" as a file on disk during the compilation?

Another option I would check is upgrading your JVM to the most recent version and trying again.


问:
Populate select only if option tag doesn't exist
I want to populate the select #current_location only if it hasn't been done yet.

```<code>$(document).ready(function(){
            $('#current_location').on('change', function (){
                   /*
                    * Populate the select
                    * I want to populate the select only if it hasn't been done yet
                    */
                   $.getJSON('fetch.php', {action: 'homepage' , key: 'current_location' }, function(data){
                       var options = '';
                       for (var x = 0; x < data.length; x++) {
                           options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                       }
                       $('#current_location').html(options);
                   });

                $.getJSON('fetch.php', {action: 'homepage' , key: $('#current_location').val() }, function(data){
                    var options = '';
                    for (var x = 0; x < data.length; x++) {
                        options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                    }
                    $('#destination').html(options);
                });

            });
        });
</code>```

答:
Check if there is no options present and add options accordingly.

```<code>if($('#current_location').find('option').length < 1) {
    .... // add options
}
</code>```

Body:
I want to populate the select #current_location only if it hasn't been done yet.

$(document).ready(function(){
            $('#current_location').on('change', function (){
                   /*
                    * Populate the select
                    * I want to populate the select only if it hasn't been done yet
                    */
                   $.getJSON('fetch.php', {action: 'homepage' , key: 'current_location' }, function(data){
                       var options = '';
                       for (var x = 0; x < data.length; x++) {
                           options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                       }
                       $('#current_location').html(options);
                   });

                $.getJSON('fetch.php', {action: 'homepage' , key: $('#current_location').val() }, function(data){
                    var options = '';
                    for (var x = 0; x < data.length; x++) {
                        options += '<option value="' + data[x] + '">' + data[x] + '</option>';
                    }
                    $('#destination').html(options);
                });

            });
        });

Body:
Check if there is no options present and add options accordingly.

if($('#current_location').find('option').length < 1) {
    .... // add options
}


问:
My android application suddenly stopped working
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

I made some minor changes to MainActivity.java

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>
</code>```

答:
First add ChessHistoryActivity.java, LearnChessActivity.java and GrandmastersActivity.java classes into your java source Folder(If not added yet).

Folder:  ./app/src/main/java/birada1.tulungatung.ph.myapplication2/

Declare ChessHistoryActivity, LearnChessActivity and GrandmastersActivity in the AndroidManifest.xml file.

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/chess_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ChessHistoryActivity" />
        <activity android:name=".LearnChessActivity" />
        <activity android:name=".GrandmastersActivity" />

    </application>
</manifest>
</code>```

Hope this will help~

Body:
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

I made some minor changes to MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>

Body:
First add ChessHistoryActivity.java, LearnChessActivity.java and GrandmastersActivity.java classes into your java source Folder(If not added yet).

Folder:  ./app/src/main/java/birada1.tulungatung.ph.myapplication2/

Declare ChessHistoryActivity, LearnChessActivity and GrandmastersActivity in the AndroidManifest.xml file.

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/chess_icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ChessHistoryActivity" />
        <activity android:name=".LearnChessActivity" />
        <activity android:name=".GrandmastersActivity" />

    </application>
</manifest>

Hope this will help~


问:
How to call a Action Name on dropdown change in MVC?
How to bind data to second dropdownlist on selecting first dropdownlist ?

I have bind first dropdownlist using strongly typed view.

Now how to call action name and bind second dropdownlist on selection first dropdownlist?

```<code> <tr>
            <td>Select Make:</td>
            <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList, new { @class = "form-control", @onchange = "FillModel()" })</td>
        </tr>
        <tr>
            <td>Select Model</td>
            <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList)</td>
        </tr>
</code>```

Action Name

```<code>public ActionResult FillModel(int MakeId)
        {
            var makedata = objVehicleContext.VehicleMakes.Where(m=>m.MakeId==MakeId);

            ViewBag.makelist = makedata.ToList();
            return View();
        }
</code>```

答:
You can Put Jquery function on change of dropdown list. For Example

```<code> <tr>

        <td>Select Make:</td>
                <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList, new { @class = "form-control", @onchange = "FillModel()", id="ddlMake"

    })</td>
        </tr>
        <tr>
            <td>Select Model</td>
            <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList,new {@id="ddlModel"})</td>
        </tr>
</code>```

This Is a simple solution to call the action method on dropdown change.

```<code>$(document).ready(function(){
    $("#ddlMake").change(function(){url.action('Controller Name','Action Method Name')})
})
</code>```

But for further Effects You have to call the Ajax call method and fetch the data. After that on success of the method You have to append the rest of Data On ddlModel. Just Like It.

```<code>    $(document).ready(function(){

   $("#ddlMake").change(function(){
   $.ajax({
        type:'POST',
        url:'url.action('Controller Name','Action Method Name')'
        data:{id:$('#ddlMake').val()},
        sucess:{
             $("#ddlModel").append('<option value="' + ModelId.Value + '">' + Model.Text + '</option>');
        }
        });)})
        })
</code>```

And You need to do this with Controller

```<code>public JsonResult GetModel()
    {
        //your dropdown datasource
        return json(ddlModeldatasurce,JsonRequestBehavior.AllowGet);
    }
</code>```

Body:
How to bind data to second dropdownlist on selecting first dropdownlist ?

I have bind first dropdownlist using strongly typed view.

Now how to call action name and bind second dropdownlist on selection first dropdownlist?

            Select Make:
            @Html.DropDownListFor(m => m.SelectedMake, Model.MakesList, new { @class = "form-control", @onchange = "FillModel()" })

            Select Model
            @Html.DropDownListFor(m => m.SelectedMake, Model.MakesList)

Action Name

public ActionResult FillModel(int MakeId)
        {
            var makedata = objVehicleContext.VehicleMakes.Where(m=>m.MakeId==MakeId);

            ViewBag.makelist = makedata.ToList();
            return View();
        }

Body:
You can Put Jquery function on change of dropdown list. For Example

 <tr>

        <td>Select Make:</td>
                <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList, new { @class = "form-control", @onchange = "FillModel()", id="ddlMake"

    })</td>
        </tr>
        <tr>
            <td>Select Model</td>
            <td>@Html.DropDownListFor(m => m.SelectedMake, Model.MakesList,new {@id="ddlModel"})</td>
        </tr>

This Is a simple solution to call the action method on dropdown change.

$(document).ready(function(){
    $("#ddlMake").change(function(){url.action('Controller Name','Action Method Name')})
})

But for further Effects You have to call the Ajax call method and fetch the data. After that on success of the method You have to append the rest of Data On ddlModel. Just Like It.

    $(document).ready(function(){

   $("#ddlMake").change(function(){
   $.ajax({
        type:'POST',
        url:'url.action('Controller Name','Action Method Name')'
        data:{id:$('#ddlMake').val()},
        sucess:{
             $("#ddlModel").append('<option value="' + ModelId.Value + '">' + Model.Text + '</option>');
        }
        });)})
        })

And You need to do this with Controller

public JsonResult GetModel()
    {
        //your dropdown datasource
        return json(ddlModeldatasurce,JsonRequestBehavior.AllowGet);
    }


问:
Adding a form field that is not in the schema to Doctrine form Symfony 1.4
I have an image upload form and at the bottom, I'd like to have a checkbox that the user must check before submitting the form, certifying that they have the right to distribute the photo. I've tried adding it as a Widget in the Form class, but it is not displaying. What is the best way to accomplish this?</p>

答:
Adding a new widget to your form should be the right way.

```<code>class ImageForm extends BaseImageForm
{
  public function configure()
  {

    $this->widgetSchema['copyright'] = new sfWidgetFormInputCheckbox();
  }
}
</code>```

For conditional validation, check this cookbook page should still be valid.

Body:
Adding a new widget to your form should be the right way.

class ImageForm extends BaseImageForm
{
  public function configure()
  {

    $this->widgetSchema['copyright'] = new sfWidgetFormInputCheckbox();
  }
}

For conditional validation, check this cookbook page should still be valid.


问:
Openpyxl dataframe_to_rows generating unreadable content error
I created a fairly simple utility function that just put a dataframe into an excel worksheet, using the newer dataframe_to_rows option in openpyxl:

```<code>insertRows = dataframe_to_rows(df)
worksheet = workbook.create_sheet(title=sheetName)

for r_idx, row in enumerate(insertRows, 1):
    for c_idx, cell_value in enumerate(row, 1):
        worksheet.cell(row=r_idx, column=c_idx, value=value)
</code>```

When I open the workbook, I received excel's unreadable content error which is usually related to formatting. After some googling, I found that the answer isn't posted anywhere. So posting my fix below

答:
The problem ended up being related to the formatting of the numpy NAN values in the dataframe which the cell class couldn't convert properly.

A simple fix was to change the insertion code into something like the following:

```<code>try:
    if numpy.isnan(cell_value):
        cell_value = "NAN"
    elif numpy.isinf(cell_value):
        cell_value = "INF"
    else:
        cell_value = float(cell_value)
except:
    pass

worksheet.cell(row=r_idx, column=c_idx, value=cell_value)
</code>```

Body:
I created a fairly simple utility function that just put a dataframe into an excel worksheet, using the newer dataframe_to_rows option in openpyxl:

insertRows = dataframe_to_rows(df)
worksheet = workbook.create_sheet(title=sheetName)

for r_idx, row in enumerate(insertRows, 1):
    for c_idx, cell_value in enumerate(row, 1):
        worksheet.cell(row=r_idx, column=c_idx, value=value)

When I open the workbook, I received excel's unreadable content error which is usually related to formatting. After some googling, I found that the answer isn't posted anywhere. So posting my fix below

Body:
The problem ended up being related to the formatting of the numpy NAN values in the dataframe which the cell class couldn't convert properly.

A simple fix was to change the insertion code into something like the following:

try:
    if numpy.isnan(cell_value):
        cell_value = "NAN"
    elif numpy.isinf(cell_value):
        cell_value = "INF"
    else:
        cell_value = float(cell_value)
except:
    pass

worksheet.cell(row=r_idx, column=c_idx, value=cell_value)


问:
How to get json array from json file?
im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?

Code Pasted here;

```<code>var points;

        var l_nOldX;
        var l_nOldY;
        function createHotspots(){
        var points = new Array(
            /*Tamilnadu*/
        [38.7, 85.6, "0168"],
        [36.1, 85.3, "1843"],
        [38.5, 88.3, "39647"],
        [34.8, 29.2, "12320"]
    );
    var divHotspot = document.getElementById("loadImages");
    for(pi = 0; pi < points.length; pi++){
        var hs = document.createElement("div");
        hs.className = "hotspot";
        hs.style.position = "absolute";
        hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
        hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
        hs.style.width = "15px";
        hs.style.height = "15px";
        var html;
        if (points[pi][0] < 31) {
            html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
            // alert('a');
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipright").show();
            });
        }

        else {
            html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipnormal").show();
            });

        }

        $('.divclose').on('click touchstart', function () {
            //debugger;

            $('.tbltooltipnormal').hide();
            $('.tbltooltipleft').hide();
            $('.tbltooltipright').hide();
            return false;
        });

        divHotspot.appendChild(hs);
    }

}
</code>```

In above code i've  get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.

thanks in Advance.

答:
```<code>var yourJsonDataFromFile=undefined;
var getJsonData=function () {

        console.log("fetching data from JSON file");
        var url = "path_to_your_json _file";
        var ajaxHttp = new XMLHttpRequest();
        ajaxHttp.overrideMimeType("application/json");
        ajaxHttp.open("GET",url,true);
        ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
        ajaxHttp.send(null);
        ajaxHttp.onreadystatechange = function () {
            if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
            {
                yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
            }
        };

    }
</code>```

modify this code add file path in path_to_your_json _fileand call this function  getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue

Title: How to get json array from json file?

Body:
im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?

Code Pasted here;

var points;

        var l_nOldX;
        var l_nOldY;
        function createHotspots(){
        var points = new Array(
            /*Tamilnadu*/
        [38.7, 85.6, "0168"],
        [36.1, 85.3, "1843"],
        [38.5, 88.3, "39647"],
        [34.8, 29.2, "12320"]
    );
    var divHotspot = document.getElementById("loadImages");
    for(pi = 0; pi < points.length; pi++){
        var hs = document.createElement("div");
        hs.className = "hotspot";
        hs.style.position = "absolute";
        hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
        hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
        hs.style.width = "15px";
        hs.style.height = "15px";
        var html;
        if (points[pi][0] < 31) {
            html = "

" + points[pi][2] + "

";
            // alert('a');
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipright").show();
            });
        }

        else {
            html = "

" + points[pi][2] + "

";
            hs.innerHTML = html;
            $(hs).bind("mouseenter", function () {
                $(".tbltooltipnormal").hide();
                $(".tbltooltipleft").hide();
                $(".tbltooltipright").hide();
                $(this).find(".tbltooltipnormal").show();
            });

        }

        $('.divclose').on('click touchstart', function () {
            //debugger;

            $('.tbltooltipnormal').hide();
            $('.tbltooltipleft').hide();
            $('.tbltooltipright').hide();
            return false;
        });

        divHotspot.appendChild(hs);
    }

}

In above code i've  get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.

thanks in Advance.

Body:
var yourJsonDataFromFile=undefined;
var getJsonData=function () {

        console.log("fetching data from JSON file");
        var url = "path_to_your_json _file";
        var ajaxHttp = new XMLHttpRequest();
        ajaxHttp.overrideMimeType("application/json");
        ajaxHttp.open("GET",url,true);
        ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
        ajaxHttp.send(null);
        ajaxHttp.onreadystatechange = function () {
            if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
            {
                yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
            }
        };

    }

modify this code add file path in path_to_your_json _fileand call this function  getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue