问:
How can I camelCase a phrase with Dragon NaturallySpeaking's advanced scripting?
From time to time, typically when coding, I would like to dictate a phrase so that it is camelCased a phrase. For example, when I dictate sentence generator I would like Dragon NaturallySpeaking to write sentenceGenerator.

How can I camelCase a phrase with Dragon NaturallySpeaking's advanced scripting?

Same question for Dragon Dictate: How can I convert a series of words into camel case in AppleScript?

答:
You can use this function:

```<code>' CamelCases the previous <1to10> words:
' Voice command name: CamelCase <1to10>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate

Sub Main
   Dim camelVariable, dictate, firstCharacter As String
   Dim wasSpace, isLower, trailingSpace As Boolean
   Dim dictationLength As Integer

   For increment = 1 To Val (ListVar1)
      SendKeys "+^{Left}", 1
   Next increment
   Wait 0.2
   SendKeys "^c", 1
   Wait 0.3
   dictate = Clipboard
   Wait 0.3
   dictationLength = Len (dictate)

   If Mid (dictate, dictationLength, 1) = " " Then trailingSpace = True
'Dim testing As String
'testing = "#" + Mid (dictate, 1, dictationLength) + "#"
'MsgBox testing
   dictate = Trim (dictate)
   firstCharacter = Mid (dictate, 1, 1)
   firstCharacter = LCase (firstCharacter)
   camelVariable = firstCharacter

   dictationLength = Len (dictate)
   If dictationLength > 1 Then
      For increment = 2 To dictationLength
         firstCharacter = Mid (dictate, increment, 1)
         If firstCharacter = " " Then
            wasSpace = True
         Else
            If wasSpace = True Then firstCharacter = UCase (firstCharacter)
            camelVariable = camelVariable + firstCharacter
            wasSpace = False
         End If
      Next increment
   End If
   If leadingSpace = True Then camelVariable = " " + camelVariable
   If trailingSpace = True Then camelVariable = camelVariable + " "
   SendKeys camelVariable
End Sub
</code>```

or

```<code>' CamelCases the previous dictated words:
' Voice command name: CamelCase that
' Author: Heather
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate

Option Explicit

Sub Main
Dim engCtrl As New DgnEngineControl
Dim Text As String
Dim VarText As String

HeardWord "cut","that"
Text = Clipboard

SendDragonKeys "" & CamelCase(Text)
End Sub

Public Function CamelCase(strInput As String) As String
Dim i As Integer
Dim sMid As String
Dim foundSpace As Boolean

For i = 1 To Len(strInput)
sMid = Mid(strInput, i, 1)
Select Case Asc(sMid)
Case 32:
foundSpace = True

Case 65 To 90:

If i = 1 Then
CamelCase = CamelCase + LCase(sMid)
Else
CamelCase = CamelCase + sMid
End If

foundSpace = False

Case 97 To 122:
If foundSpace Then
CamelCase = CamelCase + UCase(sMid)
Else
CamelCase = CamelCase + sMid
End If

foundSpace = False

Case Else:
CamelCase = CamelCase + sMid
foundSpace = False

End Select
Next i
End Function
</code>```

or

```<code>' CamelCases the next dictated words:
' Voice command name: CamelCase <dictation>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Requires Dragon NaturallySpeaking 13 Professional or higher, because the variable <dictation> was introduced in Dragon NaturallySpeaking 13 Professional.

Sub Main
   Dim camelVariable, dictate, firstCharacter As String
   Dim wasSpace, isLower As Boolean
   Dim dictationLength As Integer

   dictate = ListVar1

   dictate = Trim (dictate)' probably unnecessary
   firstCharacter = Mid (dictate, 1, 1)
   firstCharacter = LCase (firstCharacter)
   camelVariable = firstCharacter

   dictationLength = Len (dictate)
   If dictationLength > 1 Then
      For increment = 2 To dictationLength
         firstCharacter = Mid (dictate, increment, 1)
         If firstCharacter = " " Then
            wasSpace = True
         Else
            If wasSpace = True Then firstCharacter = UCase (firstCharacter)
            camelVariable = camelVariable + firstCharacter
            wasSpace = False
         End If
      Next increment
   End If

   SendKeys " " + camelVariable + " "
End Sub
</code>```

(source) (mirror)

Body:
You can use this function:

' CamelCases the previous <1to10> words:
' Voice command name: CamelCase <1to10>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate

Sub Main
   Dim camelVariable, dictate, firstCharacter As String
   Dim wasSpace, isLower, trailingSpace As Boolean
   Dim dictationLength As Integer

   For increment = 1 To Val (ListVar1)
      SendKeys "+^{Left}", 1
   Next increment
   Wait 0.2
   SendKeys "^c", 1
   Wait 0.3
   dictate = Clipboard
   Wait 0.3
   dictationLength = Len (dictate)

   If Mid (dictate, dictationLength, 1) = " " Then trailingSpace = True
'Dim testing As String
'testing = "#" + Mid (dictate, 1, dictationLength) + "#"
'MsgBox testing
   dictate = Trim (dictate)
   firstCharacter = Mid (dictate, 1, 1)
   firstCharacter = LCase (firstCharacter)
   camelVariable = firstCharacter

   dictationLength = Len (dictate)
   If dictationLength > 1 Then
      For increment = 2 To dictationLength
         firstCharacter = Mid (dictate, increment, 1)
         If firstCharacter = " " Then
            wasSpace = True
         Else
            If wasSpace = True Then firstCharacter = UCase (firstCharacter)
            camelVariable = camelVariable + firstCharacter
            wasSpace = False
         End If
      Next increment
   End If
   If leadingSpace = True Then camelVariable = " " + camelVariable
   If trailingSpace = True Then camelVariable = camelVariable + " "
   SendKeys camelVariable
End Sub

or

' CamelCases the previous dictated words:
' Voice command name: CamelCase that
' Author: Heather
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate

Option Explicit

Sub Main
Dim engCtrl As New DgnEngineControl
Dim Text As String
Dim VarText As String

HeardWord "cut","that"
Text = Clipboard

SendDragonKeys "" & CamelCase(Text)
End Sub

Public Function CamelCase(strInput As String) As String
Dim i As Integer
Dim sMid As String
Dim foundSpace As Boolean

For i = 1 To Len(strInput)
sMid = Mid(strInput, i, 1)
Select Case Asc(sMid)
Case 32:
foundSpace = True

Case 65 To 90:

If i = 1 Then
CamelCase = CamelCase + LCase(sMid)
Else
CamelCase = CamelCase + sMid
End If

foundSpace = False

Case 97 To 122:
If foundSpace Then
CamelCase = CamelCase + UCase(sMid)
Else
CamelCase = CamelCase + sMid
End If

foundSpace = False

Case Else:
CamelCase = CamelCase + sMid
foundSpace = False

End Select
Next i
End Function

or

' CamelCases the next dictated words:
' Voice command name: CamelCase <dictation>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Requires Dragon NaturallySpeaking 13 Professional or higher, because the variable <dictation> was introduced in Dragon NaturallySpeaking 13 Professional.

Sub Main
   Dim camelVariable, dictate, firstCharacter As String
   Dim wasSpace, isLower As Boolean
   Dim dictationLength As Integer

   dictate = ListVar1

   dictate = Trim (dictate)' probably unnecessary
   firstCharacter = Mid (dictate, 1, 1)
   firstCharacter = LCase (firstCharacter)
   camelVariable = firstCharacter

   dictationLength = Len (dictate)
   If dictationLength > 1 Then
      For increment = 2 To dictationLength
         firstCharacter = Mid (dictate, increment, 1)
         If firstCharacter = " " Then
            wasSpace = True
         Else
            If wasSpace = True Then firstCharacter = UCase (firstCharacter)
            camelVariable = camelVariable + firstCharacter
            wasSpace = False
         End If
      Next increment
   End If

   SendKeys " " + camelVariable + " "
End Sub

(source) (mirror)


来源: stackexchange

问:
Compare files names regardless of extension in node
So I have a node script that currently spits out two arrays:

```<code>$ yarn run header:test
yarn run v0.22.0
$ ./bin/create_header.js
[ 'LucidEventIcon.md', 'LucidStates.md' ] [ 'LucidEventIcon.js', 'LucidStates.js' ]
</code>```

What I would like to do is use some kind of find method to say:

"LucideEventIcon.md should match the LucidEventIcon.js", what I care about is matching on name. I need to keep the file extension so I can, later, prepend the contends of the .md to the .js

How can I match on name, regardless of extension? while looping over the first and checking the second array?

Expected result should be true for both elements in the first array, they should match to the two JS files in the second array.

答:
Updated isArraysEqual function to not modify Array.prototype.</p>

```<code>   function isArraysEqual(arr1, arr2, strict) {
    if (!arr1 || !arr2)
        return false;

    if (arr1.length != arr2.length)
        return false;

    for (var i = 0; i < arr1.length; i++) {
        if (arr1[i] instanceof Array && arr2[i] instanceof Array) {
            if (!isArraysEqual(arr1[i], arr2[i], strict))
                return false;
        }
        else if (strict && arr1[i] != arr2[i]) {
            return false;
        }
        else if (!strict) {
            return isArraysEqual(arr1.sort(), arr2.sort(), true);
        }
    }
    return true;
}

const mdFiles = [ 'LucidEventIcon.md', 'LucidStates.md' ].map((file)=>file.split('.')[0]);
const jsFiles = [ 'LucidEventIcon.js', 'LucidStates.js' ].map((file)=>file.split('.')[0]);

const isEqual = isArraysEqual(mdFiles, jsFiles, false);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a node script that currently spits out two arrays:

$ yarn run header:test
yarn run v0.22.0
$ ./bin/create_header.js
[ 'LucidEventIcon.md', 'LucidStates.md' ] [ 'LucidEventIcon.js', 'LucidStates.js' ]

What I would like to do is use some kind of find method to say:

"LucideEventIcon.md should match the LucidEventIcon.js", what I care about is matching on name. I need to keep the file extension so I can, later, prepend the contends of the .md to the .js

How can I match on name, regardless of extension? while looping over the first and checking the second array?

Expected result should be true for both elements in the first array, they should match to the two JS files in the second array.

Body:
Updated isArraysEqual function to not modify Array.prototype.

   function isArraysEqual(arr1, arr2, strict) {
    if (!arr1 || !arr2)
        return false;

    if (arr1.length != arr2.length)
        return false;

    for (var i = 0; i < arr1.length; i++) {
        if (arr1[i] instanceof Array && arr2[i] instanceof Array) {
            if (!isArraysEqual(arr1[i], arr2[i], strict))
                return false;
        }
        else if (strict && arr1[i] != arr2[i]) {
            return false;
        }
        else if (!strict) {
            return isArraysEqual(arr1.sort(), arr2.sort(), true);
        }
    }
    return true;
}

const mdFiles = [ 'LucidEventIcon.md', 'LucidStates.md' ].map((file)=>file.split('.')[0]);
const jsFiles = [ 'LucidEventIcon.js', 'LucidStates.js' ].map((file)=>file.split('.')[0]);

const isEqual = isArraysEqual(mdFiles, jsFiles, false);


问:
Update with percentage calculation on the same table
I have a table like this:

```<code>ItemID      PersonID  Score      Percentage
==========================================
1             1       10         [ = 10 / 10+30 = 25%]
1             2       30         [ = 30 / 10+30 = 75%]
2             1       20         [ = 20 / 20+40 = 33%]
2             2       40         [ = 40 / 20+40 = 67%]
</code>```

The data on "Percentage" is not entered but is auto-calculated at certain time interval.
The calculation is Percentage = Score / Total Score of the ItemID

Instead of using "SELECT-do the maths-UPDATE" method, I'm trying to write a single SQL to update the "Percentage".

What I tried is like this:

```<code>UPDATE tb_temp AS t1
    SET t1.Percentage =
        CEIL( t1.Score /
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID)
        );
</code>```

But it doesn't work.(Error Code : 1093 You can't specify target table 't1' for update in FROM clause).

Any idea?

答:
try:</p>

```<code>  UPDATE tb_temp t1
     JOIN (SELECT ItemId, SUM(t2.Score) TotalScore
           FROM tb_temp
           group by ItemId) t2 ON t2.ItemID = t1.ItemID
  SET t1.Percentage = CEIL( t1.Score / t2.TotalScore)
</code>```

Body:
I have a table like this:

ItemID      PersonID  Score      Percentage
==========================================
1             1       10         [ = 10 / 10+30 = 25%]
1             2       30         [ = 30 / 10+30 = 75%]
2             1       20         [ = 20 / 20+40 = 33%]
2             2       40         [ = 40 / 20+40 = 67%]

The data on "Percentage" is not entered but is auto-calculated at certain time interval.
The calculation is Percentage = Score / Total Score of the ItemID

Instead of using "SELECT-do the maths-UPDATE" method, I'm trying to write a single SQL to update the "Percentage".

What I tried is like this:

UPDATE tb_temp AS t1
    SET t1.Percentage =
        CEIL( t1.Score /
            (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID)
        );

But it doesn't work.(Error Code : 1093 You can't specify target table 't1' for update in FROM clause).

Any idea?

Body:
try:

  UPDATE tb_temp t1
     JOIN (SELECT ItemId, SUM(t2.Score) TotalScore
           FROM tb_temp
           group by ItemId) t2 ON t2.ItemID = t1.ItemID
  SET t1.Percentage = CEIL( t1.Score / t2.TotalScore)

ContentLicense: CC BY-SA 2.5


问:
Imagemagick get detailed error with PHP
I'm running the following Imagemagick command on many images. Some images fail, but I'm not sure why... how can I get a detailed error message or error number from ImageMagick with PHP to help with troubleshooting the failures?</p>

```<code>$myexec = 'convert -trim -density 200 /path/filename.tif -resize 70% /path/filename.png';
exec($myexec, $output, $return);

if (!$return) {
//success
}else{
//failed
}
</code>```

答:
In ImageMagick, you should read the input first (assuming it is a raster image and not a vector image), then settings, then operators that use those setting, then other settings. Also you should specify -units. PNG only supports density and units of pixelspercentimeter. But if you specify units of pixelsperinch, ImageMagick will automatically convert the density to a value in pixelspercentimeter that corresponds to the corresponding pixelsperinch. To see any textual error messages, try the following:

```<code>$myexec = "convert /path/filename.tif -trim -resize 70% -units pixelsperinch -density 200 /path/filename.png 2>&1";
exec($myexec, $output, $return);
foreach($output as $text) {echo "$text<br>";}
</code>```

You might also want to specify a -fuzz XX% before -trim if the background is not perfectly uniform.  XX is a value between 0.0 and 100.0

Title: Imagemagick get detailed error with PHP

Body:
I'm running the following Imagemagick command on many images. Some images fail, but I'm not sure why... how can I get a detailed error message or error number from ImageMagick with PHP to help with troubleshooting the failures?

$myexec = 'convert -trim -density 200 /path/filename.tif -resize 70% /path/filename.png';
exec($myexec, $output, $return);

if (!$return) {
//success
}else{
//failed
}

Body:
In ImageMagick, you should read the input first (assuming it is a raster image and not a vector image), then settings, then operators that use those setting, then other settings. Also you should specify -units. PNG only supports density and units of pixelspercentimeter. But if you specify units of pixelsperinch, ImageMagick will automatically convert the density to a value in pixelspercentimeter that corresponds to the corresponding pixelsperinch. To see any textual error messages, try the following:

$myexec = "convert /path/filename.tif -trim -resize 70% -units pixelsperinch -density 200 /path/filename.png 2>&1";
exec($myexec, $output, $return);
foreach($output as $text) {echo "$text<br>";}

You might also want to specify a -fuzz XX% before -trim if the background is not perfectly uniform.  XX is a value between 0.0 and 100.0


问:
MySQL update if value is greater than current value
Here is my insertion scripts:

```<code>INSERT INTO CONTENT (content_id, version, description)
VALUES ('123', '1', 'This is an example')
ON DUPLICATE KEY UPDATE version=VALUES(version),description=VALUES(description)
</code>```

content_id is pk.
If there is a duplicate key, I want to check the value under version. If it is greater than that I want to insert, then ignore the new insertion. Otherwise, update the one with content_id in db. I tried to search my question first on stack overflow and found this:MySQL update if value is greater than that current value. But it doesn't solve my case.
Any suggestions?

答:
INSERT INTO CONTENT (content_id, version, description)
VALUES ('123', '1', 'This is an example')
ON DUPLICATE KEY
UPDATE version=
    CASE WHEN VALUES(version) > version THEN VALUES(version) ELSE version END,
description=
    CASE WHEN VALUES(version) > version THEN VALUES(description) ELSE description END

Body:
Here is my insertion scripts:

INSERT INTO CONTENT (content_id, version, description)
VALUES ('123', '1', 'This is an example')
ON DUPLICATE KEY UPDATE version=VALUES(version),description=VALUES(description)

content_id is pk.
If there is a duplicate key, I want to check the value under version. If it is greater than that I want to insert, then ignore the new insertion. Otherwise, update the one with content_id in db. I tried to search my question first on stack overflow and found this:MySQL update if value is greater than that current value. But it doesn't solve my case.
Any suggestions?


问:
ng-table work with user inputted filter
I have a scenario where i will be doing a page refresh of a ng-table but i don't want to lose any user inputted filters when the page refreshes.

The idea is to store the user inputted data in the controller, then push that data back into the filter input box after the page refresh.

```<code><table ng-table="tableParams" class="table" show-filter="true">
<tr ng-repeat="user in $data">
  <td title="'Name'" filter="{ name: 'text'}" sortable="'name'">
    {{user.name}}</td>
  <td title="'Age'" filter="{ age: 'number'}" sortable="'age'">
    {{user.age}}</td>
</tr>
</code>```

```<code><p>name = {{ params.filter()[name] }}</p> //i thought this might be the way to get the filter data
</code>```

example here: https://plnkr.co/edit/z98RLOX9AUOoX9c7x00d?p=preview

If I type "mor" into the "name" filter box, I want to be able to use "mor" in my controller to push it back into the filter after a page refresh, so the user doesnt lose any search filters they have used.

Is this possible?

答:
To get filter data, it can use tableParams.filter().

```<code><p>name = {{ tableParams.filter()['name'] }}</p>
</code>```

And you can use 'sessionStorage' to keep the search filters. Then the data will not lost after page refresh.

Title: ng-table work with user inputted filter

Body:
I have a scenario where i will be doing a page refresh of a ng-table but i don't want to lose any user inputted filters when the page refreshes.

The idea is to store the user inputted data in the controller, then push that data back into the filter input box after the page refresh.

    {{user.name}}

    {{user.age}}

name = {{ params.filter()[name] }}
 //i thought this might be the way to get the filter data

example here: https://plnkr.co/edit/z98RLOX9AUOoX9c7x00d?p=preview

If I type "mor" into the "name" filter box, I want to be able to use "mor" in my controller to push it back into the filter after a page refresh, so the user doesnt lose any search filters they have used.

Is this possible?

Body:
To get filter data, it can use tableParams.filter().

<p>name = {{ tableParams.filter()['name'] }}</p>

And you can use 'sessionStorage' to keep the search filters. Then the data will not lost after page refresh.


问:
Vue.js, Axios, JSon and no refresh
Sorry to post it, but I tried all solutions I found on the web. This seems to be a common problem but I just can't make it work. After a full day on it I give up. It must be a silly point, any vue.js guru will find the point in seconds. Any help will be appreciated.

The point : I receive some JSON and try to update my page with the received values, but the fields are null. jsonSettings.length is always 0.

I think I understand why: it's surely because the 'pointer' on the arrays doesn't change so vue.js doesn't detect the change of the content, or something similar, but I just can't make it work and it's driving me CRAZY.

My HTML :

```<code><!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        Typeof : {{ jsonSettings.typeof }} <BR>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>
</code>```

My JavaScript:

```<code>var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        // jsonSettings: [],
    },
    methods: {
        jsonSettings : function() {
            return (
                [
                    { id: 0, resume: 'test 0'},
                    { id: 1, resume: 'test 1'},
                    { id: 2, resume: 'test 2'}
                ]
            )
        },

        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(function (response) {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                    this.message = "getData - OK";

                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + jsonSettings.length + "]";

            jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})
</code>```

Sorry again, but I just can't make it work and I'm stuck in the middle of the river because of this silly point :-(

答:
Incorrect this strikes again. Essentially, the this inside your axios callbacks is not a reference to the Vue. In order to make it point to the Vue you need to use an arrow function, or use bind or capture the correct this in a closure. Here, I'm using an arrow function.

```<code>getData : function () {
  axios.get('/axios/LoadAxiosData')
    .then(response => {
      this.jsonSettings = response.data;
      this.message = "getData - I get objects : " + jsonSettings.length + " lines ";

    })
    .catch(error =>  {
        this.message = "getData - I get null";
    });
},
</code>```

See How to access the correct this inside a callback?

Also delete your jsonSettings method and add the data property back in.

```<code>data: {
    message: 'Hello Vue!',
    jsonSettings: [],
},
</code>```

Working example. You'll see in the example that I cleaned up a couple other things.

Title: Vue.js, Axios, JSon and no refresh

Body:
Sorry to post it, but I tried all solutions I found on the web. This seems to be a common problem but I just can't make it work. After a full day on it I give up. It must be a silly point, any vue.js guru will find the point in seconds. Any help will be appreciated.

The point : I receive some JSON and try to update my page with the received values, but the fields are null. jsonSettings.length is always 0.

I think I understand why: it's surely because the 'pointer' on the arrays doesn't change so vue.js doesn't detect the change of the content, or something similar, but I just can't make it work and it's driving me CRAZY.

My HTML :

<!DOCTYPE html>

    <title>List</title>

        Message : {{ message }}

        Length : {{ jsonSettings.length }}

        Typeof : {{ jsonSettings.typeof }}

        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>

My JavaScript:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        // jsonSettings: [],
    },
    methods: {
        jsonSettings : function() {
            return (
                [
                    { id: 0, resume: 'test 0'},
                    { id: 1, resume: 'test 1'},
                    { id: 2, resume: 'test 2'}
                ]
            )
        },

        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(function (response) {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                    this.message = "getData - OK";

                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + jsonSettings.length + "]";

            jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})

Sorry again, but I just can't make it work and I'm stuck in the middle of the river because of this silly point :-(

Body:
Incorrect this strikes again. Essentially, the this inside your axios callbacks is not a reference to the Vue. In order to make it point to the Vue you need to use an arrow function, or use bind or capture the correct this in a closure. Here, I'm using an arrow function.

getData : function () {
  axios.get('/axios/LoadAxiosData')
    .then(response => {
      this.jsonSettings = response.data;
      this.message = "getData - I get objects : " + jsonSettings.length + " lines ";

    })
    .catch(error =>  {
        this.message = "getData - I get null";
    });
},

See How to access the correct this inside a callback?

Also delete your jsonSettings method and add the data property back in.

data: {
    message: 'Hello Vue!',
    jsonSettings: [],
},

Working example. You'll see in the example that I cleaned up a couple other things.


问:
Deleting part of a string in nested list python
I am trying to keep only a particular part of a string within my nested list.  My code is as follows:

```<code>answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "', ...]
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "', ...]]
</code>```

I want to delete parts of the string so that the only piece that remains are:

```<code>answers = [
    ['person1', 'answer 1', 'answer 0', ...]
    ['person 2', 'answer 3', 'answer 1', ...]]
</code>```

答:
This code works:

```<code>answers = [
           ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "'],
           ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "']]

result = []
for person_ans in answers:
    list = []
    for val in person_ans:
        if "[" in val:
            temp = val.split("[")
            output = temp[1].split("]")[0]
            list.append(output)
        else:
            list.append(val)
    result.append(list)
print result
</code>```

Output:

```<code>[['person1', '"answer 1"', '"answer 0"'], ['person2', '"answer 3"', '"answer 1"']]
</code>```

Body:
I am trying to keep only a particular part of a string within my nested list.  My code is as follows:

answers = [
    ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "', ...]
    ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "', ...]]

I want to delete parts of the string so that the only piece that remains are:

answers = [
    ['person1', 'answer 1', 'answer 0', ...]
    ['person 2', 'answer 3', 'answer 1', ...]]

Body:
This code works:

answers = [
           ['person1', ' 2 1": ["answer 1"], "', ' 3 1": ["answer 0"], "'],
           ['person2', ' 2 1": ["answer 3"], "', ' 3 1": ["answer 1"], "']]

result = []
for person_ans in answers:
    list = []
    for val in person_ans:
        if "[" in val:
            temp = val.split("[")
            output = temp[1].split("]")[0]
            list.append(output)
        else:
            list.append(val)
    result.append(list)
print result

Output:

[['person1', '"answer 1"', '"answer 0"'], ['person2', '"answer 3"', '"answer 1"']]


问:
Remove Sub Strings pandas, python
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

```<code>in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']
</code>```

Desired:

```<code>out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson
</code>```

答:
use rstrip()method to strip the undesired string from the rear of your original string.
e.g.:

mystring = "Brown Academy"

mystring.rstrip("Academy") --> will give u the o/p: 'Brown '

Title: Remove Sub Strings pandas, python

Body:
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']

Desired:

out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson


问:
When I set a value of setRGB, getRGB returns a different value. Why?
Why here I setRGB () with three RGB colors (125, 126, 127), but when getRGB it returns another value that is (125, 126, 128).
For (122, 126, 127), it returns true (122, 126, 127).
Why?
And:
Input: image.setRGB (0, 0, 5072962) // 77 ----- 104 ----- 66 ------- 5072962
Output: 78 ------ 104 ------ 69 ------- 5138501
(With rgb = (red << 16) | (green << 8) | blue;)

My code:

//  77-------104-------66------5072962

```<code>final static int rgb = 5072962;

public static void main(String[] args) {

    BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);

    //image.setRGB(0, 0, 5072962);
    Color c = new Color(125, 126, 127);
    image.setRGB(0, 0, c.getRGB());

    File outputFile = new File("123.jpg");
    try {
        ImageIO.write(image, "jpg", outputFile);
        File f = new File("123.jpg");
        BufferedImage bi = ImageIO.read(f);
        for (int h = 0; h < 1; h++) {
            for (int w = 0; w < 1; w++) {
                int pixel = bi.getRGB(w, h);
                Color c2 = new Color(pixel);

                int red = c2.getRed();
                int green = c2.getGreen();
                int blue = c2.getBlue();

                int rgb = (red << 16) | (green << 8) | blue;
                System.out.printf("%-8d%-8d%-8d%-8d", red, green, blue, rgb);
                System.out.println("");
            }
        }
    } catch (IOException ex) {
        System.out.println("Error output File image!");
    }

}
</code>```

答:
At first, Did you Know about Image file formats ? I have the same problem before in similar case. I would like to suggest you the following.

When you use jpg for the image write operation to store in your storage, RGB values changes slightly because jpg format is a lossy compressed file format. This compression allows you for the optimal space to store the file but it doesn't store the information of RGB values you want.

So, If file format is not a big issue for you , then simply use PNG format. PNG format is a lossless compression file format so that you can retrieve RGB values you have set before in the program.

Hope it might help you.

Body:
Why here I setRGB () with three RGB colors (125, 126, 127), but when getRGB it returns another value that is (125, 126, 128).
For (122, 126, 127), it returns true (122, 126, 127).
Why?
And:
Input: image.setRGB (0, 0, 5072962) // 77 ----- 104 ----- 66 ------- 5072962
Output: 78 ------ 104 ------ 69 ------- 5138501
(With rgb = (red << 16) | (green << 8) | blue;)

My code:

//  77-------104-------66------5072962

final static int rgb = 5072962;

public static void main(String[] args) {

    BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);

    //image.setRGB(0, 0, 5072962);
    Color c = new Color(125, 126, 127);
    image.setRGB(0, 0, c.getRGB());

    File outputFile = new File("123.jpg");
    try {
        ImageIO.write(image, "jpg", outputFile);
        File f = new File("123.jpg");
        BufferedImage bi = ImageIO.read(f);
        for (int h = 0; h < 1; h++) {
            for (int w = 0; w < 1; w++) {
                int pixel = bi.getRGB(w, h);
                Color c2 = new Color(pixel);

                int red = c2.getRed();
                int green = c2.getGreen();
                int blue = c2.getBlue();

                int rgb = (red << 16) | (green << 8) | blue;
                System.out.printf("%-8d%-8d%-8d%-8d", red, green, blue, rgb);
                System.out.println("");
            }
        }
    } catch (IOException ex) {
        System.out.println("Error output File image!");
    }

}


问:
aggregate / count rows grouped by geography (or geometry)
I have a table such as:

```<code>Create Table SalesTable
( StuffID int identity not null,
  County geography not null,
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null )
</code>```

It has a recording of every sale with amount, time, and a geography of the county that the sale happened in.

I want to run a query like this:

```<code>Select sum(SaleAmount), County from SalesTable group by County
</code>```

But if I try to do that, I get:

```<code>The type "geography" is not comparable. It cannot be used in the GROUP BY clause.
</code>```

But I'd like to know how many sales happened per county. Annoyingly, if I had the counties abbreviated (SDC,LAC,SIC, etc) then I could group them because it would simply be a varchar. But then I use the geography datatype for other reasons.

答:
There's a function to work with geography type as char

try this

```<code>Select sum(SaleAmount), County.STAsText() from SalesTable
group by County.STAsText()
</code>```

Body:
I have a table such as:

Create Table SalesTable
( StuffID int identity not null,
  County geography not null,
  SaleAmount decimal(12,8) not null,
  SaleTime datetime not null )

It has a recording of every sale with amount, time, and a geography of the county that the sale happened in.

I want to run a query like this:

Select sum(SaleAmount), County from SalesTable group by County

But if I try to do that, I get:

The type "geography" is not comparable. It cannot be used in the GROUP BY clause.

But I'd like to know how many sales happened per county. Annoyingly, if I had the counties abbreviated (SDC,LAC,SIC, etc) then I could group them because it would simply be a varchar. But then I use the geography datatype for other reasons.

Body:
There's a function to work with geography type as char

try this

Select sum(SaleAmount), County.STAsText() from SalesTable
group by County.STAsText()


问:
find and replace string in a file
I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

```<code>#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
    sed "s/$OLD/$NEW/g" "$f"
   else
    echo "Error: Cannot read $f"
  fi
done
</code>```

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks

答:
Use the -i option of  sed to make the changes in place:

```<code>sed -i "s/$OLD/$NEW/g" "$f"
    ^^
</code>```

Title: find and replace string in a file

Body:
I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
    sed "s/$OLD/$NEW/g" "$f"
   else
    echo "Error: Cannot read $f"
  fi
done

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks

Body:
Use the -i option of  sed to make the changes in place:

sed -i "s/$OLD/$NEW/g" "$f"
    ^^


问:
How to Display Data in a single view from Multiple Tables in MVC using Entity framework
I want to display the the password and user name in the user view
could any one help me?  I created a Userand LogIn table as shown below. How do I display properties from both the User and LogIn table in my Razor view.

Models

```<code>public class User
{
    [Key]
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Mobile { get; set; }
    public string JobTittle { get; set; }
    public string Email { get; set; }
}

public class LogIn
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int LoginID { get; set; }
    [Required(ErrorMessage = "Required.")]
    public string UserName { get; set; }
    public string Password { get; set; }

    public  User User { get; set; }
}
</code>```

Controller

```<code>public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Index()
    {
        return View();
    }
}
</code>```

View

```<code>@model Coding.Models.User

@{
    ViewBag.Title = "Create";
}

<h2>Sign Up</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

答:
ViewModel can have multiple entities or objects from different data models or data source.

useful link:https://www.codeproject.com/Articles/826417/Advantages-of-ViewModel-in-MVC-Model-View-Controll

Example of ViewModel:  As per your requirement

```<code>public class userloginviewmodel
{
     public user users{get;set;}
     public login logins{get;set;}
}
</code>```

Controller code:

```<code>public ActionResult Create()
    {
       userloginviewmodel OBJuserloginviewmodel = new userloginviewmodel();
        OBJuserloginviewmodel .Users = db.Users.FirstOrDefault(x => x.UserID == someId);
        OBJuserloginviewmodel .logins = db.LogIns.FirstOrDefault(x => x.LoginID == someId);

        return View(OBJuserloginviewmodel );
    }
</code>```

viewCode:

```<code>    @model Coding.Models.userloginviewmodel

    @{
        ViewBag.Title = "Create";
    }

    <h2>Sign Up</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">

            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.user.name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.user.name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.user.name, "", new { @class = "text-danger" })
                </div>
            </div>

<div class="form-group">
            @Html.LabelFor(model => model.Login.LoginId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Login.LoginId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Login.LoginId, "", new { @class = "text-danger" })
            </div>
        </div>

        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
</code>```

Additional Note : By using the viewmodel we can achieve most of things we want, even in this, if you want list of users and logins you can just have two more properties in the same viewmodel and get  the result.

Hope the above was helpful

Thanks

Karthik

Body:
I want to display the the password and user name in the user view
could any one help me?  I created a Userand LogIn table as shown below. How do I display properties from both the User and LogIn table in my Razor view.

Models

public class User
{
    [Key]
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Mobile { get; set; }
    public string JobTittle { get; set; }
    public string Email { get; set; }
}

public class LogIn
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int LoginID { get; set; }
    [Required(ErrorMessage = "Required.")]
    public string UserName { get; set; }
    public string Password { get; set; }

    public  User User { get; set; }
}

Controller

public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Index()
    {
        return View();
    }
}

View

@model Coding.Models.User

@{
    ViewBag.Title = "Create";
}

Sign Up

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Body:
ViewModel can have multiple entities or objects from different data models or data source.

useful link:https://www.codeproject.com/Articles/826417/Advantages-of-ViewModel-in-MVC-Model-View-Controll

Example of ViewModel:  As per your requirement

public class userloginviewmodel
{
     public user users{get;set;}
     public login logins{get;set;}
}

Controller code:

public ActionResult Create()
    {
       userloginviewmodel OBJuserloginviewmodel = new userloginviewmodel();
        OBJuserloginviewmodel .Users = db.Users.FirstOrDefault(x => x.UserID == someId);
        OBJuserloginviewmodel .logins = db.LogIns.FirstOrDefault(x => x.LoginID == someId);

        return View(OBJuserloginviewmodel );
    }

viewCode:

    @model Coding.Models.userloginviewmodel

    @{
        ViewBag.Title = "Create";
    }

    <h2>Sign Up</h2>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">

            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.user.name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.user.name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.user.name, "", new { @class = "text-danger" })
                </div>
            </div>

<div class="form-group">
            @Html.LabelFor(model => model.Login.LoginId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Login.LoginId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Login.LoginId, "", new { @class = "text-danger" })
            </div>
        </div>

        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

Additional Note : By using the viewmodel we can achieve most of things we want, even in this, if you want list of users and logins you can just have two more properties in the same viewmodel and get  the result.

Hope the above was helpful

Thanks

Karthik


问:
how to filter the query when an object is related to multiple categories?
I want to fetch the movie results that are related to two categories for
   example the "Romance" & "Drama".. if I say something like
   $genre->with("movie")->where("genre","Romance")->where("genre","Drama")->get();
     Naturally it won't work so is not there any simple way to do it?

```<code>  <!-- my controller -->
   public function show()
      {
            $genres = new genres;
             $y = $genre->with("movie")->where("genre","Romance")->get();
             return $y;
       }
    <!-- model -->
   <?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;
    use App\movies;
     class genres extends Model
       {
         public $table ="genres";
         public function movie(){
             return $this->belongsToMany(movies::class,
                   "relation","genre_id","movie_id");
                                 }
       }
</code>```

答:
Use OR condition like this:

```<code>$genre->with("movie")->where("genre","Romance")->orWhere("genre","Drama") ->get();
</code>```

this is equivalent to where genre = 'Romance' OR genre = 'Drama'

Body:
I want to fetch the movie results that are related to two categories for
   example the "Romance" & "Drama".. if I say something like
   $genre->with("movie")->where("genre","Romance")->where("genre","Drama")->get();
     Naturally it won't work so is not there any simple way to do it?

   public function show()
      {
            $genres = new genres;
             $y = $genre->with("movie")->where("genre","Romance")->get();
             return $y;
       }

   <?php

   namespace App;

   use Illuminate\Database\Eloquent\Model;
    use App\movies;
     class genres extends Model
       {
         public $table ="genres";
         public function movie(){
             return $this->belongsToMany(movies::class,
                   "relation","genre_id","movie_id");
                                 }
       }

Body:
Use OR condition like this:

$genre->with("movie")->where("genre","Romance")->orWhere("genre","Drama") ->get();

this is equivalent to where genre = 'Romance' OR genre = 'Drama'


问:
Error calling forEach on an array literal in javascript
This code generates an error when I run it with node v6.9.2

```<code>var req = {}

['foo', 'bar'].forEach(prop => {
    console.log("prop: " + prop)
});
</code>```

The error is: TypeError: Cannot read property 'forEach' of undefined

Why would that be? There doesn't seem to be anything syntactically wrong with what I'm doing. I note that if I add a semi-colon after the var req = {} line the error disappears, but I still don't understand why since I thought semi-colons were optional in JavaScript as long as each statement was on a separate line.

答:
Automatic semicolon insertion has turned

```<code>var req = {}
['foo', 'bar']
</code>```

into

```<code>var req = {}['foo', 'bar']
</code>```

and of course {} doesn't contain a 'bar' property (because 'foo', 'bar' evaluates to 'bar').

(undefined).forEach(...) gets evaluated, which then leads to the error that you're seeing.

If you're relying on ASI, it's common practice to prefix lines beginning with [] or () with a semicolon:

```<code>var req = {}
;['foo', 'bar']
</code>```

Body:
This code generates an error when I run it with node v6.9.2

var req = {}

['foo', 'bar'].forEach(prop => {
    console.log("prop: " + prop)
});

The error is: TypeError: Cannot read property 'forEach' of undefined

Why would that be? There doesn't seem to be anything syntactically wrong with what I'm doing. I note that if I add a semi-colon after the var req = {} line the error disappears, but I still don't understand why since I thought semi-colons were optional in JavaScript as long as each statement was on a separate line.

Body:
Automatic semicolon insertion has turned

var req = {}
['foo', 'bar']

into

var req = {}['foo', 'bar']

and of course {} doesn't contain a 'bar' property (because 'foo', 'bar' evaluates to 'bar').

(undefined).forEach(...) gets evaluated, which then leads to the error that you're seeing.

If you're relying on ASI, it's common practice to prefix lines beginning with [] or () with a semicolon:

var req = {}
;['foo', 'bar']


问:
Why are there no archives under the organizer section in xcode?
I am in the process of uploading my ios app to the app store and I clicked on the organizer button but no archives came up. All that came up was "Use the Archive command within an Xcode project or import an archive from an Xcode Server bot." Does anyone have any idea what the problem is?</p>

答: If you've already created an archive by going to Product > Archive. I would try restarting Xcode. That might not be helpful, but that's where I would start, let me know.</p>


问:
Confluence Macro: How to include content
There are these two macros available in Confluence: Excerpt Macro and Excerpt Include Macro, but these are somewhat limited.

I created my own User Macro to extend the existing Excerpt Macro in a way that I can add some parameters to the excerpt, like ID, etc.

I am also able to get the content from my macro via the REST api in my code, which is cool.

BUT, I am unable to find a way to get the content and include it into another page via another macro.

In other words, I am trying to figure out a way to create my own User Macro to extend the existing Excerpt Include Macro.

Is there a way to see the Template content for these existing Confluence Macros, or is there a way to have a User Macro include some content from some other page?

答: This is not your exact answer, but there is a plug-in multiexcerpt which probably does exactly what you are looking for.</p>


问:
How to connect to a Remote Database from native Iphone app
I want to connect to a remote database(MySQL or SQL Server or Oracle) via internet from my native iphone app.  I can't find any API or Framework in System to add.  does any one know how to connect to a remote Database?  pleased help me.  Thank you very much</p>

答:
Disclaimer : Shamelessly plugging my own product :)

We've built an online system called Kumulos that allows iOS and OSX developers to build and host online databases in the cloud, while easily creating custom API methods for accessing it. It even builds all the Objective-C bindings for you.

Its really really easy to use and its free while in Beta. We'd love some honest developer feedback :)

Check it out here

OwnerDisplayName: ngo hoang lien


问:
How to fprintf on file with recursive
I'm a newbie with recursion.  How do I fopen and fclose a file in a recursive function?

```<code>void make(LINK lis, char *name, int flag, FILE *f)
{
    if (lis == NULL) {
        fclose(f);
    }
    else {
        if (flag == 0) {
            FILE *f = fopen(name, "w");
            flag = 1;
        }
        else {
            fprintf(f, "CODICE: %d\n", lis->d.codice);
            make(lis->next, name, 1, f);
        }
    }
}
</code>```

My goal is to recursively write "codice" --> CODE in a file.

答:
How do I fopen and fclose a file in a recursive function?

Be sure to do so at the same level of recursion.

Consider first how the nth and first would look separately:

```<code>void make_nth(LINK lis, FILE *outf) {
  if (lis) {
    fprintf(outf, "CODICE: %d\n", lis->d.codice);
    make_nth(lis->next, outf);
  }
}

void make_1st(LINK lis, const char *name) {
  FILE *f = fopen(name, "w");
  if (f) {
    make_nth(lis, f);
    fclose(f);
  }
}

// Usage
LINK lis = ...;
make_1st(lis, codice.txt);
</code>```

Now put that together.  Various ways exist to do this.

```<code>void make(LINK lis, const char *name, FILE *outf) {
  if (name) {
    assert(outf == NULL);
    FILE *f = fopen(name, "w");
    if (f) {
      make(lis, NULL, f);
      fclose(f);
    }
  } else {
    if (lis) {
      fprintf(outf, "CODICE: %d\n", lis->d.codice);
      make(lis->next, NULL, outf);
    }
  }
}

// Usage
LINK lis = ...;
make(lis, codice.txt, NULL);
</code>```

Title: How to fprintf on file with recursive

Body:
I'm a newbie with recursion.  How do I fopen and fclose a file in a recursive function?

void make(LINK lis, char *name, int flag, FILE *f)
{
    if (lis == NULL) {
        fclose(f);
    }
    else {
        if (flag == 0) {
            FILE *f = fopen(name, "w");
            flag = 1;
        }
        else {
            fprintf(f, "CODICE: %d\n", lis->d.codice);
            make(lis->next, name, 1, f);
        }
    }
}

My goal is to recursively write "codice" --> CODE in a file.

Body:
How do I fopen and fclose a file in a recursive function?

Be sure to do so at the same level of recursion.

Consider first how the nth and first would look separately:

void make_nth(LINK lis, FILE *outf) {
  if (lis) {
    fprintf(outf, "CODICE: %d\n", lis->d.codice);
    make_nth(lis->next, outf);
  }
}

void make_1st(LINK lis, const char *name) {
  FILE *f = fopen(name, "w");
  if (f) {
    make_nth(lis, f);
    fclose(f);
  }
}

// Usage
LINK lis = ...;
make_1st(lis, codice.txt);

Now put that together.  Various ways exist to do this.

void make(LINK lis, const char *name, FILE *outf) {
  if (name) {
    assert(outf == NULL);
    FILE *f = fopen(name, "w");
    if (f) {
      make(lis, NULL, f);
      fclose(f);
    }
  } else {
    if (lis) {
      fprintf(outf, "CODICE: %d\n", lis->d.codice);
      make(lis->next, NULL, outf);
    }
  }
}

// Usage
LINK lis = ...;
make(lis, codice.txt, NULL);


问:
How to get all jobs status through spark REST API?
I am using spark 1.5.1 and I'd like to retrieve all jobs status through REST API.

I am getting correct result using  /api/v1/applications/{appId}. But while accessing jobs /api/v1/applications/{appId}/jobs getting "no such app:{appID}" response.

How should I pass app ID here to retrieve jobs status of application using spark REST API?

答:
Spark provides 4 hidden RESTFUL API

1) Submit the job - curl -X POST http://SPARK_MASTER_IP:6066/v1/submissions/create

2) To kill the job - curl -X POST http://SPARK_MASTER_IP:6066/v1/submissions/kill/driver-id

3) To check status if the job - curl http://SPARK_MASTER_IP:6066/v1/submissions/status/driver-id

4) Status of the Spark Cluster - http://SPARK_MASTER_IP:8080/json/

If you want to use another APIs you can try Livy , lucidworks
url - https://doc.lucidworks.com/fusion/3.0/Spark_ML/Spark-Getting-Started.html


问:
AR Query for jsonb attribute column
I'm using Postgres for my db, and I have a column in my Auction model as a jsonb column. I want to create a query that searches the Auction's json column to see whether a user's name OR email exists in any Auction instance's json column.

Right now I have @auctions = Auction.where('invitees @> ?', {current_user.name.downcase => current_user.email.downcase}.to_json), but that only brings back exact key => value matches I want to know whether the name OR the email exists.

答:
You're using the @> operator. The description for it is this:

“Does the left JSON value contain the right JSON path/value entries
  at the top level?”

You probably want the ? operator if you want to return a row when the key (name in your case) matches.

There's not a good way to search for values only in a JSON column (see this answer for more details), but you could check if the key exists alone or the key and value match exists.

The same ActiveRecord methods and chaining apply as when using non-JSON columns, namely where and where(…).or(where(…)):

```<code>class Auction
  def self.by_invitee(user)
    name = user.name.downcase
    json = { name => user.email } # note: you should be downcasing emails anyways
    where('invitee ? :name', name: name).or(
      where('invitee @> :json', json: json)
    )
  end
end
</code>```

Title: AR Query for jsonb attribute column

Body:
You're using the @> operator. The description for it is this:

“Does the left JSON value contain the right JSON path/value entries
  at the top level?”

You probably want the ? operator if you want to return a row when the key (name in your case) matches.

There's not a good way to search for values only in a JSON column (see this answer for more details), but you could check if the key exists alone or the key and value match exists.

The same ActiveRecord methods and chaining apply as when using non-JSON columns, namely where and where(…).or(where(…)):

class Auction
  def self.by_invitee(user)
    name = user.name.downcase
    json = { name => user.email } # note: you should be downcasing emails anyways
    where('invitee ? :name', name: name).or(
      where('invitee @> :json', json: json)
    )
  end
end


答:
I'd probably go with a regular expression substitution:</p>

```<code>import re

df['school']=df['school'].apply(lambda x: re.sub(r'\s+((Academy)|(Prep)|(High)|(High School))$','',x))
</code>```

Title: Remove Sub Strings pandas, python

Body:
I'd probably go with a regular expression substitution:

import re

df['school']=df['school'].apply(lambda x: re.sub(r'\s+((Academy)|(Prep)|(High)|(High School))$','',x))


问:
any MQ services based on email?
I am looking for MQ systems (rabbitmq , activemq) for our programs. Almost all MQ run on ports. I was wondering if there are any MQ systems running on smtp or email services.

Basically I am trying to avoid the hassle of setting up a new software and opening up ports in different firewalls (its a hassle).

答:
RabbitMQ is designed from the ground up to interoperate with other messaging systems: it is the leading implementation of AMQP, the open standard for business messaging, and, through adapters, supports XMPP, SMTP, STOMP and HTTP for lightweight web messaging.

supports SMTP? from: http://www.rabbitmq.com/

Title: any MQ services based on email?


问:
How do I change an attribute or class using only Javascript?
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

```<code>var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}
</code>```

答:
i think some wrong in your code, try this code

```<code>element.setAttribute("style", "background-color: orange;"); // bad
</code>```

or

```<code>element.style.backgroundColor = "orange"; // good
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}

Body:
i think some wrong in your code, try this code

element.setAttribute("style", "background-color: orange;"); // bad

or

element.style.backgroundColor = "orange"; // good


问:
Finding Lighting Direction from lunar image using crater shadow
I am very new to computer vision and image processing and working on a problem of detecting light direction (sun azimuth and elevation) using only a single image. I attempted the method mentioned in "Determining Light Direction in Spheres using Average Gradient by Richard Dosselmann". But I couldn't get the azimuth or elevation angles properly. I tried to calculate image gradients (gx and gy) using sobel operator and taken average of gx and gy. Using arctan(gy,gx), I was trying to get an elevation angle. but it didn't work properly. To elaborate my problem, from the following lunar crater image, the solar azimuth with respect to north is 90degree and elevation is 45degree, what I suppose to find.lunar crater. Please help me in finding lighting source direction by using only an image.</p>

答:
Very interesting question. I would try the following approach:

Detect circles in the image using Hough transform. You will have to adjust the thresholds so that both the crater and its shadow are detected.

For each pair of overlapping circles, get the pair of centers.

Use the pair to calculate lighting direction. I am not sure if you can calculate both the azimuth and the elevation with only one pair, but with multiple pairs you should be able to come up with a least squares-like method.


问:
Editable cells in dynamic table
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }</code>```

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

```

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

答:
 $(document).ready(function () {
        $("#createit").click(function () {
            var num_rows = document.getElementById('rows').value;
            var num_cols = document.getElementById('cols').value;
            var tbody = '';
            var tabindex = 0
            for (var i = 0; i < num_rows; i++) {
                tbody += '
';
                for (var j = 0; j < num_cols; j++) {
                    tbody += '';
                    tbody += 'Cell' + i + j;
                    tbody += '	'
                }
                tbody += '
';
            }
            //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
            $('.editableTable').append(tbody);
        });
    });
    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
    $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }</code>```

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

```

Title: Editable cells in dynamic table

Body:
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

Body:
 $(document).ready(function () {
        $("#createit").click(function () {
            var num_rows = document.getElementById('rows').value;
            var num_cols = document.getElementById('cols').value;
            var tbody = '';
            var tabindex = 0
            for (var i = 0; i < num_rows; i++) {
                tbody += '<tr>';
                for (var j = 0; j < num_cols; j++) {
                    tbody += '<td tabindex=' + tabindex++ + '>';
                    tbody += 'Cell' + i + j;
                    tbody += '</td>'
                }
                tbody += '</tr>';
            }
            //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
            $('.editableTable').append(tbody);
        });
    });
    $(document).on('dblclick', 'td', function () {
        console.log('clicked');
        this.contentEditable = 'true';
    });
    $(document).on('keydown', 'td', function (event) {
        if (event.keyCode === 9 || event.keyCode === 13) {
            this.contentEditable = 'false';
            //  $(this).next().focus().dblclick().focus();
            var tabindex = $(this).attr('tabindex');
            tabindex++;
            var next = $('[tabindex=' + tabindex + ']').focus().dblclick();
            if (next.is('td') == false)
                return true;
            var sel, range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(next[0]);
                range.collapse(true);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(next[0]);
                range.collapse(true);
                range.select();
            }

            return false;
        }
    });

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
    <label>Cols: <input type="text" name="cols" id="cols"/></label><br/>
    <input name="generate" type="button" value="Create Table!" id='createit' />
    <div id="wrapper">
        <table class="editableTable">
            <tbody></tbody>
        </table>
    </div>


答:
You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.

Then simply iterate through them and i.e. set their background color with

 element.style.backgroundColor = 'orange';

Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:

 querySelectorAll('.post-feature[style*="http"][style*="background-image"]')

Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.

window.addEventListener('load', function() {
  var elements = document.querySelectorAll('.post-feature[style*="http"]');
  for (var i = 0; i < elements.length; i++) {

      elements[i].style.backgroundColor = 'orange';   /* add propert value */

      /*  replace class
      elements[i].className = 'myClass';
      */

      /*  add a class
      elements[i].classList.add('myClass');
      */
  }
  /* temp log */
  console.log('Found ', elements.length,' element(s)');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}</code>```

```
</div>
</div>
</p>

<hr>

<p><em>Updated</em></p>

<p>To only change styling, like colors etc., you don't even need a script, you can use CSS alone</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}
/*  for elements that contain "http" and "background-image"  */
.post-feature[style*="http"i][style*="background-image"i] {
  background-color: orange;
}</code>```

```
</div>
</div>
</p>

<p><em>As a note, and as discussed in a few comments, if to make sure it is the <code>background-image</code> property that also contain the <code>http</code> in its <code>url()</code>, you can adjust the selector to this, which as well can be used without any script, as a CSS rule</em></p>

```.post-feature[style*="background-image:url(http"i] {
  background-color: orange;
}
```

<p><em>The above selector can of course also be used in the first sample, like this</em></p>

```querySelectorAll('.post-feature[style*="background-image:url(http"i]')
```

Title: How do I change an attribute or class using only Javascript?

Body:
You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.

Then simply iterate through them and i.e. set their background color with

 element.style.backgroundColor = 'orange';

Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:

 querySelectorAll('.post-feature[style*="http"][style*="background-image"]')

Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.

window.addEventListener('load', function() {
  var elements = document.querySelectorAll('.post-feature[style*="http"]');
  for (var i = 0; i < elements.length; i++) {

      elements[i].style.backgroundColor = 'orange';   /* add propert value */

      /*  replace class
      elements[i].className = 'myClass';
      */

      /*  add a class
      elements[i].classList.add('myClass');
      */
  }
  /* temp log */
  console.log('Found ', elements.length,' element(s)');
})

div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

Updated

To only change styling, like colors etc., you don't even need a script, you can use CSS alone

div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}
/*  for elements that contain "http" and "background-image"  */
.post-feature[style*="http"i][style*="background-image"i] {
  background-color: orange;
}

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

<div class="post-feature" style="background-image:url(HTTP://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

As a note, and as discussed in a few comments, if to make sure it is the background-image property that also contain the http in its url(), you can adjust the selector to this, which as well can be used without any script, as a CSS rule

.post-feature[style*="background-image:url(http"i] {
  background-color: orange;
}

The above selector can of course also be used in the first sample, like this

querySelectorAll('.post-feature[style*="background-image:url(http"i]')


问:
Remove Sub Strings pandas, python
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

```<code>in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']
</code>```

Desired:

```<code>out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson
</code>```

答:
Using split</p>

```<code>df.school = df.school.str.split(' ').str[0]

    school  time
0   Brown   09:00
1   Covfefe 10:00
2   Bradley 11:00
3   Johnson 12:00
</code>```

Title: Remove Sub Strings pandas, python

Body:
I have a df of high schools.  I'm trying to strip out the generic endings of the school's name.

in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']

Desired:

out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson

Body:
Using split

df.school = df.school.str.split(' ').str[0]

    school  time
0   Brown   09:00
1   Covfefe 10:00
2   Bradley 11:00
3   Johnson 12:00


问:
Passing XML Paths and evaluating
I'm working on a project where I need to parse an XML file and perform the exact same code on 100s of different XML Paths/Nodes.  My code currently looks like this…

```<code>def items = parser.parseText(inputFile.text)

items.item.each { item ->
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.weight_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.another_node[3].sub_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    // do this a 100 times or so with other item node paths
}
</code>```

Since the 'stuff to do' and the exception 'stuff' is the exact same every time and the only thing that changes is the node I'm working with. Because of this I would rather send the node expression to a method or extend the node class like this…

```<code>def myMethod(currentNode) {
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}

items.item.each { item ->
    myMethod(item.some_node)
    myMethod(item.weight_node)
    myMethod(item.another_node[3].sub_node)
    myMethod(item.some_node)
}

// OR

def myProcess(NodeList n){
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}
NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    item.another_node[3].sub_node.myMethod()
    item.some_node.myMethod()
}
</code>```

With the method attempt I can't figure out how to pass the XPath to the method and then use it.  With the class extension method it works so long as the node actually exists. If it doesn't I get an error trying to invoke myProcess.

Any ideas?

答:
Since there is no xml, taking a sample xml.

You do need to write for each node like it was mentioned in initially.

In groovy, that is something which is easily achieved using find (returns single value) or findAll (multiple values). Please see the example below.

```<code>def jdbcResponse = """<Results>
    <ResultSet fetchSize="10">
        <Row rowNumber="1">
            <T1>TEXT1</T1>
            <T2>TASK1</T2>
            <T3>Value1</T3>
            <T4>xyz</T4>
      </Row>
       <Row rowNumber="2">
            <T1>TEXT2</T1>
            <T2>TASK2</T2>
            <T3>Value1a</T3>
            <T4>ABC</T4>
      </Row>
     </ResultSet>
</Results>"""

def xml = new XmlSlurper().parseText(jdbcResponse)

//Return the matching element
def getData = { elementName ->
    xml.'**'.findAll{it.name() == elementName}
}

//Coerced result to List of string as T1/2 is not complex
def t1s = getData('T1') as List<String>
def t2s = getData('T2') as List<String>
println t1s

//Here you get Rows which is complex, so not coerced
def rows = getData('Row')
//Check if first row T1 is TEXT1
assert rows[0].T1.text() == 'TEXT1'
</code>```

Title: Passing XML Paths and evaluating

Body:
I'm working on a project where I need to parse an XML file and perform the exact same code on 100s of different XML Paths/Nodes.  My code currently looks like this…

def items = parser.parseText(inputFile.text)

items.item.each { item ->
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.weight_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.another_node[3].sub_node
    } catch(Exception ex) {
        //exception stuff
    }
    try {
        // do stuff with item.some_node
    } catch(Exception ex) {
        //exception stuff
    }
    // do this a 100 times or so with other item node paths
}

Since the 'stuff to do' and the exception 'stuff' is the exact same every time and the only thing that changes is the node I'm working with. Because of this I would rather send the node expression to a method or extend the node class like this…

def myMethod(currentNode) {
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}

items.item.each { item ->
    myMethod(item.some_node)
    myMethod(item.weight_node)
    myMethod(item.another_node[3].sub_node)
    myMethod(item.some_node)
}

// OR

def myProcess(NodeList n){
    try {
        // do stuff
    } catch(Exception ex) {
        //exception stuff
    }
}
NodeList.metaClass.myProcess = { -> myProcess(delegate) }

items.item.each { item ->
    item.some_node.myMethod()
    item.weight_node.myMethod()
    item.another_node[3].sub_node.myMethod()
    item.some_node.myMethod()
}

With the method attempt I can't figure out how to pass the XPath to the method and then use it.  With the class extension method it works so long as the node actually exists. If it doesn't I get an error trying to invoke myProcess.

Any ideas?

Body:
Since there is no xml, taking a sample xml.

You do need to write for each node like it was mentioned in initially.

In groovy, that is something which is easily achieved using find (returns single value) or findAll (multiple values). Please see the example below.

def jdbcResponse = """<Results>
    <ResultSet fetchSize="10">
        <Row rowNumber="1">
            <T1>TEXT1</T1>
            <T2>TASK1</T2>
            <T3>Value1</T3>
            <T4>xyz</T4>
      </Row>
       <Row rowNumber="2">
            <T1>TEXT2</T1>
            <T2>TASK2</T2>
            <T3>Value1a</T3>
            <T4>ABC</T4>
      </Row>
     </ResultSet>
</Results>"""

def xml = new XmlSlurper().parseText(jdbcResponse)

//Return the matching element
def getData = { elementName ->
    xml.'**'.findAll{it.name() == elementName}
}

//Coerced result to List of string as T1/2 is not complex
def t1s = getData('T1') as List<String>
def t2s = getData('T2') as List<String>
println t1s

//Here you get Rows which is complex, so not coerced
def rows = getData('Row')
//Check if first row T1 is TEXT1
assert rows[0].T1.text() == 'TEXT1'


答:
check this fiddle

https://jsfiddle.net/vywk72j8/2/

```<code><div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);">
tt</div>

var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
    feature.style.backgroundColor = "orange";
} else {
    alert('no change');
}
</code>```

In your code, you are fetching the attribute value in features

```<code>var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");
</code>```

Here features is a string containing attribute value, not an element so you cannot use it to set value.

Body:
check this fiddle

https://jsfiddle.net/vywk72j8/2/

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);">
tt</div>

var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
    feature.style.backgroundColor = "orange";
} else {
    alert('no change');
}

In your code, you are fetching the attribute value in features

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

Here features is a string containing attribute value, not an element so you cannot use it to set value.


问:
How can I sort a Map[string]int by its values?
Given this code block

```<code>map[string]int {"hello":10, "foo":20, "bar":20}
</code>```

I would like to print out

```<code>foo, 20
bar, 20
hello, 10
</code>```

In the order of highest to lowest

答:
There's a new sort.Slice function in go 1.8, so now this is simpler.

```<code>package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]int{
        "something": 10,
        "yo":        20,
        "blah":      20,
    }

    type kv struct {
        Key   string
        Value int
    }

    var ss []kv
    for k, v := range m {
        ss = append(ss, kv{k, v})
    }

    sort.Slice(ss, func(i, j int) bool {
        return ss[i].Value > ss[j].Value
    })

    for _, kv := range ss {
        fmt.Printf("%s, %d\n", kv.Key, kv.Value)
    }
}
</code>```

https://play.golang.org/p/y1_WBENH4N

Body:
Given this code block

map[string]int {"hello":10, "foo":20, "bar":20}

I would like to print out

foo, 20
bar, 20
hello, 10

In the order of highest to lowest

Body:
There's a new sort.Slice function in go 1.8, so now this is simpler.

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]int{
        "something": 10,
        "yo":        20,
        "blah":      20,
    }

    type kv struct {
        Key   string
        Value int
    }

    var ss []kv
    for k, v := range m {
        ss = append(ss, kv{k, v})
    }

    sort.Slice(ss, func(i, j int) bool {
        return ss[i].Value > ss[j].Value
    })

    for _, kv := range ss {
        fmt.Printf("%s, %d\n", kv.Key, kv.Value)
    }
}

https://play.golang.org/p/y1_WBENH4N


问:
MYSQL : Copy data of tables from 2 databases. Both database are in different servers(Hosting companies)
I have an application where I copy data from a  table of database which is in hosting company myhosting.com.

I need to copy this data to another table of a database which is in a hosting company inmotionhosting.com

It is basically copying data from 2 tables which are in two different hosting company.
Both the database are mysql and I have full rights in both the databases.

I know that we can download entire database and upload the database in another hosting company but it does not solve my purpose.

答:
This should be very easy in PHP. Just make multiple connections ($link1, $link2, etc.) - one to each server. SELECT data from a table in $link1 and INSERT (or UPDATE) it in $link2.

The only catch is that often a hosting company will only, by default, open MySQL port (normally 3306) for the local server. If that is the case, then if your program is running on server A then it will be able to connect to MySQL on server A without a problem but not MySQL on server B. There should be an easy way in the server control panel to open up port 3306 for remote access - if not then you will have to ask the hosting company (one of them) to do that for you.


问:
How to implement Builder pattern in Kotlin?
Hi I am a newbie in the Kotlin world. I like what I see so far and started to think to convert some of our libraries we use in our application from Java to Kotlin.

These libraries are full of Pojos with setters, getters and Builder classes. Now I have googled to find what is the best way to implement Builders in Kotlin but no success.

2nd Update: The question is how to write a Builder design-pattern for a simple pojo with some parameters in Kotlin? The code below is my attempt by writing java code and then using the eclipse-kotlin-plugin to convert to Kotlin.

```<code>class Car private constructor(builder:Car.Builder) {
    var model:String? = null
    var year:Int = 0
    init {
        this.model = builder.model
        this.year = builder.year
    }
    companion object Builder {
        var model:String? = null
        private set

        var year:Int = 0
        private set

        fun model(model:String):Builder {
            this.model = model
            return this
        }
        fun year(year:Int):Builder {
            this.year = year
            return this
        }
        fun build():Car {
            val car = Car(this)
            return car
        }
    }
}
</code>```

答:
I have seen many examples that declare extra funs as builders. I personally like this approach. Save effort to write builders.

```<code>package android.zeroarst.lab.koltinlab

import kotlin.properties.Delegates

class Lab {
    companion object {
        @JvmStatic fun main(args: Array<String>) {

            val roy = Person {
                name = "Roy"
                age = 33
                height = 173
                single = true
                car {
                    brand = "Tesla"
                    model = "Model X"
                    year = 2017
                }
                car {
                    brand = "Tesla"
                    model = "Model S"
                    year = 2018
                }
            }

            println(roy)
        }

        class Person() {
            constructor(init: Person.() -> Unit) : this() {
                this.init()
            }

            var name: String by Delegates.notNull()
            var age: Int by Delegates.notNull()
            var height: Int by Delegates.notNull()
            var single: Boolean by Delegates.notNull()
            val cars: MutableList<Car> by lazy { arrayListOf<Car>() }

            override fun toString(): String {
                return "name=$name, age=$age, " +
                        "height=$height, " +
                        "single=${when (single) {
                            true -> "looking for a girl friend T___T"
                            false -> "Happy!!"
                        }}\nCars: $cars"
            }
        }

        class Car() {

            var brand: String by Delegates.notNull()
            var model: String by Delegates.notNull()
            var year: Int by Delegates.notNull()

            override fun toString(): String {
                return "(brand=$brand, model=$model, year=$year)"
            }
        }

        fun Person.car(init: Car.() -> Unit): Unit {
            cars.add(Car().apply(init))
        }

    }
}
</code>```

I have not yet found a way that can force some fields to be initialized in DSL like showing errors instead of throwing exceptions. Let me know if anyone knows.

Body:
Hi I am a newbie in the Kotlin world. I like what I see so far and started to think to convert some of our libraries we use in our application from Java to Kotlin.

These libraries are full of Pojos with setters, getters and Builder classes. Now I have googled to find what is the best way to implement Builders in Kotlin but no success.

2nd Update: The question is how to write a Builder design-pattern for a simple pojo with some parameters in Kotlin? The code below is my attempt by writing java code and then using the eclipse-kotlin-plugin to convert to Kotlin.

class Car private constructor(builder:Car.Builder) {
    var model:String? = null
    var year:Int = 0
    init {
        this.model = builder.model
        this.year = builder.year
    }
    companion object Builder {
        var model:String? = null
        private set

        var year:Int = 0
        private set

        fun model(model:String):Builder {
            this.model = model
            return this
        }
        fun year(year:Int):Builder {
            this.year = year
            return this
        }
        fun build():Car {
            val car = Car(this)
            return car
        }
    }
}

Body:
I have seen many examples that declare extra funs as builders. I personally like this approach. Save effort to write builders.

package android.zeroarst.lab.koltinlab

import kotlin.properties.Delegates

class Lab {
    companion object {
        @JvmStatic fun main(args: Array<String>) {

            val roy = Person {
                name = "Roy"
                age = 33
                height = 173
                single = true
                car {
                    brand = "Tesla"
                    model = "Model X"
                    year = 2017
                }
                car {
                    brand = "Tesla"
                    model = "Model S"
                    year = 2018
                }
            }

            println(roy)
        }

        class Person() {
            constructor(init: Person.() -> Unit) : this() {
                this.init()
            }

            var name: String by Delegates.notNull()
            var age: Int by Delegates.notNull()
            var height: Int by Delegates.notNull()
            var single: Boolean by Delegates.notNull()
            val cars: MutableList<Car> by lazy { arrayListOf<Car>() }

            override fun toString(): String {
                return "name=$name, age=$age, " +
                        "height=$height, " +
                        "single=${when (single) {
                            true -> "looking for a girl friend T___T"
                            false -> "Happy!!"
                        }}\nCars: $cars"
            }
        }

        class Car() {

            var brand: String by Delegates.notNull()
            var model: String by Delegates.notNull()
            var year: Int by Delegates.notNull()

            override fun toString(): String {
                return "(brand=$brand, model=$model, year=$year)"
            }
        }

        fun Person.car(init: Car.() -> Unit): Unit {
            cars.add(Car().apply(init))
        }

    }
}

I have not yet found a way that can force some fields to be initialized in DSL like showing errors instead of throwing exceptions. Let me know if anyone knows.