问:
VBA: Add data to a graph
I am new to VBA but I got this project to work on. I have this excel macro file that takes in as user input a specific date (month, day, year) and displays the graph of that day using the data read from the file of that selected date. Each file is named like "xxxx_20170706.csv". I need to modify this file to achieve below.

Each file is generated once a day containing the temperatures recorded every minute. The problem is, because each file is generated only once a day, and it contains the temperature data of the previous day (data keep being recorded from 00:00 till 23:59), you cannot check or use data of today. Basically, you have to wait until the next day if you wanna see the graph of a day.

In order to fix this issue, we decided to generate one file every hour for each day (that is, 24 files generated per day), and each file contains data of the previous hour. For example, at 1:00am of a day, a file is generated containing temperature data of time from 0:00am till 0:59am of the day. This way, we will be able to see the data of even today.

This means, at 5:30 in the morning, there should be 5 different files generated.

The problem I am having is, I am not sure how I can generate a graph from multiple files. The user input will stay the same, and only prompt a specific date they want to see the temperature data of. The output needs to be one graph reflecting temperature data of the date that exist at that point.

Each file will become named "xxxx_20170706_YY.csv" where YY is the 2 digit hours (from 00 up to 23).

I tried using loop incrementing i and adding it to the end of the file name so it can keep reading the existing files of the selected date. However, it did not work and only displayed the graph of data from the last file read.
If there are 5 files for a day, then all of these 5 files must be used for the graph.

How could this be achieved? An idea I came up with is, I create a new excel file, and each time a file is read in a for-loop, I keep adding the data at the bottom of the file, and at the end read that new excel file once, and generate the graph.

Is there any other better way? Thanks in advance for your help!

答:
I would do that this way:

loop through the hours to current hour to get the file names

inside a loop create query (string)

create connection

create recordset

dump data into Excel sheet, which is used as a source for chart

Please, read my comments in below code:

```<code>Option Explicit

'needs reference to MS ActiveX Data Objects x.x Library
Sub GetCsvData()
    Dim sPath As String, sFileName As String
    Dim i As Integer, iCurrHour As Integer
    Dim sSQL As String, sConn As String
    Dim oConn As ADODB.Connection, oRst As Recordset, oWsh As Worksheet

    On Error GoTo Err_GetCsvData

    iCurrHour = Hour(Now) - 1
    For i = 0 To iCurrHour
        sFileName = "xxxx_" & Format(Date, "yyyyMMdd") & "_" & Right("00" & CStr(i), 2) & ".csv"
        sSQL = sSQL & "SELECT * FROM " & sFileName & vbCr & "UNION ALL" & vbCr
    Next

    sSQL = "SELECT fnl.*" & vbCr & "FROM (" & vbCr & sSQL & ") AS fnl;"

    MsgBox sSQL

    'temporary exit sub; remove below line
    GoTo Exit_GetCsvData

    sPath = "c:\txtFilesFolder\" 'path have to ends with "\"

    'change HDR=Yes if the first row of csv file contains the names of columns
    sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sPath & ";Extended Properties='text;HDR=No;FMT=Delimited';"

    Set oConn = New ADODB.Connection
    With oConn
        .ConnectionString = sConn
        .Open
    End With

    Set oRst = New ADODB.Recordset
    oRst.Open sSQL, oConn, adOpenStatic, adLockReadOnly

    Set oWsh = ThisWorkbook.Worksheets("SourceSheetForChart")
    oWsh.Range("A1").CopyFromRecordset oRst

Exit_GetCsvData:
    Set oWsh = Nothing
    If Not oRst Is Nothing Then oRst.Close
    Set oRst = Nothing
    If Not oConn Is Nothing Then oConn.Close
    Set oConn = Nothing
    Exit Sub

Err_GetCsvData:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_GetCsvData

End Sub
</code>```

Note: if your text files contain very specific delimiter or decimal separator, you have create schema.ini file.

For further details, please see:

Much ADO about text files

Schema.ini File

Good luck!

Title: VBA: Add data to a graph

Body:
I would do that this way:

loop through the hours to current hour to get the file names

inside a loop create query (string)

create connection

create recordset

dump data into Excel sheet, which is used as a source for chart

Please, read my comments in below code:

Option Explicit

'needs reference to MS ActiveX Data Objects x.x Library
Sub GetCsvData()
    Dim sPath As String, sFileName As String
    Dim i As Integer, iCurrHour As Integer
    Dim sSQL As String, sConn As String
    Dim oConn As ADODB.Connection, oRst As Recordset, oWsh As Worksheet

    On Error GoTo Err_GetCsvData

    iCurrHour = Hour(Now) - 1
    For i = 0 To iCurrHour
        sFileName = "xxxx_" & Format(Date, "yyyyMMdd") & "_" & Right("00" & CStr(i), 2) & ".csv"
        sSQL = sSQL & "SELECT * FROM " & sFileName & vbCr & "UNION ALL" & vbCr
    Next

    sSQL = "SELECT fnl.*" & vbCr & "FROM (" & vbCr & sSQL & ") AS fnl;"

    MsgBox sSQL

    'temporary exit sub; remove below line
    GoTo Exit_GetCsvData

    sPath = "c:\txtFilesFolder\" 'path have to ends with "\"

    'change HDR=Yes if the first row of csv file contains the names of columns
    sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sPath & ";Extended Properties='text;HDR=No;FMT=Delimited';"

    Set oConn = New ADODB.Connection
    With oConn
        .ConnectionString = sConn
        .Open
    End With

    Set oRst = New ADODB.Recordset
    oRst.Open sSQL, oConn, adOpenStatic, adLockReadOnly

    Set oWsh = ThisWorkbook.Worksheets("SourceSheetForChart")
    oWsh.Range("A1").CopyFromRecordset oRst

Exit_GetCsvData:
    Set oWsh = Nothing
    If Not oRst Is Nothing Then oRst.Close
    Set oRst = Nothing
    If Not oConn Is Nothing Then oConn.Close
    Set oConn = Nothing
    Exit Sub

Err_GetCsvData:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_GetCsvData

End Sub

Note: if your text files contain very specific delimiter or decimal separator, you have create schema.ini file.

For further details, please see:

Much ADO about text files

Schema.ini File

Good luck!


来源: stackexchange

问:
Why is Footable pagination not rendering properly?
I'm trying to implement Footable, a JQuery plugin used to make tables responsive. There is an add-on for Footable to add pagination. [Demo]

And (http://fooplugins.com/footable/demos/paging.htm) for using the pagination add-on. I tried following this demo but my pagination came up as a vertical un-ordered list. The buttons are functional but unsightly. Here is a link images which i can not post here because my repuation is not high enough.

Here is my code for the table:

```<code><table class="table table-hover" ng-show='form.length>0' data-page-navigation=".pagination">
    <thead>
        <th ng-repeat="(key, formAttr) in form | orderBy:'attributes.order'" >{{formAttr.attributes.name}}<br/>({{formAttr.type}})</th>
        <th>Submission Time</th>
    </thead>
    <tbody>
        <tr ng-repeat="(key, response) in formResponses">
            <td ng-repeat="(key, formAttr) in form | orderBy:'attributes.order'">{{$parent.response.results[formAttr.att_id]}}</td>
            <td>{{response.submission_time}}</td>
        </tr>
    </tbody>
    <tfoot class="">
        <tr>
            <td colspan="5">
                <div class="pagination pagination-centered"></div>
            </td>
        </tr>
    </tfoot>
</table>
</code>```

答:
(If not placing the pagination in the table footer) Don't use a CSS class for table-to-pagination relationships.  Use CSS ID instead.

Consider the following...

BAD -  Example using CSS class to relate pagination object to table:

```<code><table id="table1" class="footable" data-page-navigation=".pagination" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div class="pagination hide-if-no-paging"></div>

<table id="table2" class="footable" data-page-navigation=".pagination" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div class="pagination hide-if-no-paging"></div>
</code>```

The footable javascript code will see two pagination objects.  Which will be used by table1 and which will be used by table2 is not deterministic.  This throws the footable javascript into a tizzy.

Rather than use CSS classes, be more specific by using a CSS ID instead.

GOOD - Example using CSS ID to relate pagination object to table:

```<code><table id="table1" class="footable" data-page-navigation="#pagination1" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div id="pagination1" class="pagination hide-if-no-paging"></div>

<table id="table2" class="footable" data-page-navigation="#pagination2" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div id="pagination2" class="pagination hide-if-no-paging"></div>
</code>```

Javascript Example:

```<code>$(document).ready(function () {
    $(".footable").footable();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement Footable, a JQuery plugin used to make tables responsive. There is an add-on for Footable to add pagination. [Demo]

And (http://fooplugins.com/footable/demos/paging.htm) for using the pagination add-on. I tried following this demo but my pagination came up as a vertical un-ordered list. The buttons are functional but unsightly. Here is a link images which i can not post here because my repuation is not high enough.

Here is my code for the table:

0' data-page-navigation=".pagination">

        {{formAttr.attributes.name}}
({{formAttr.type}})
        Submission Time

            {{$parent.response.results[formAttr.att_id]}}
            {{response.submission_time}}

Body:
(If not placing the pagination in the table footer) Don't use a CSS class for table-to-pagination relationships.  Use CSS ID instead.

Consider the following...

BAD -  Example using CSS class to relate pagination object to table:

<table id="table1" class="footable" data-page-navigation=".pagination" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div class="pagination hide-if-no-paging"></div>

<table id="table2" class="footable" data-page-navigation=".pagination" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div class="pagination hide-if-no-paging"></div>

The footable javascript code will see two pagination objects.  Which will be used by table1 and which will be used by table2 is not deterministic.  This throws the footable javascript into a tizzy.

Rather than use CSS classes, be more specific by using a CSS ID instead.

GOOD - Example using CSS ID to relate pagination object to table:

<table id="table1" class="footable" data-page-navigation="#pagination1" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div id="pagination1" class="pagination hide-if-no-paging"></div>

<table id="table2" class="footable" data-page-navigation="#pagination2" data-page-size="10">
    <thead>
        <th>Some Title</th>
        <th>Some other Title</th>
    </thead>
    <tbody>
        <tr>
            <td>some data</td>
            <td>some more data</td>
        </tr>
    </tbody>
</table>
<div id="pagination2" class="pagination hide-if-no-paging"></div>

Javascript Example:

$(document).ready(function () {
    $(".footable").footable();
});


问:
Running my c# exe on another computer?
I've completed a C# program which uses winforms and Microsoft.Speech (both recognition and synthesis) library, built it and it runs fine on the same computer. However when I copy the whole application directory to another computer the program starts and shuts down immediately.

Things I have tried:

Main method has a try-catch which prints all exceptions. I've tried
running the both straight from the directory and command line, both
resulting identically the program closing immediately without any
exceptions thrown

I've checked that the computer I'm trying to run the executable on has the correct version of .NET framework (my executable uses 4.5.2
and the computer states it already has a newer version)

I've also downloaded the Microsoft.Speech libraries on the new computer, no effect

Obviously I have gone wrong about the whole deployment task here. Most of the beginner guides suggest using the Setup and Deployment project template, but that is no longer supported in Visual Studio. As this is a whole new area of programming to me I'm now completely lost on how to proceed. Please help.

答: add a try{}(Exception ex)catch{} statement and within the catch statement you write the ex.toString() to a file, so you can read the error.</p>

Title: Running my c# exe on another computer?


问:
Get string from a list contain Unicode in JavaScript
I have a list of Unicode values [65, 66, 67] and I want the corresponding string "ABC". I looked into the documentation and found the function String.fromCharCode()that does what I need to do. The only problem is that the arguments needs to be a sequence of numbers.

So if I use String.fromCharCode([65, 66, 67]) it gives me " ".

Is there a way that allows the list to be treated as a sequence for a function?

答:
Map on the list and then join:

var s = [65, 66, 67].map(x => String.fromCharCode(x)).join("");
console.log(s);```

ContentLicense: CC BY-SA 4.0


问:
SAS proc SQL, Left Join, file name is too long
When I did the left join

```<code>left join V_testtest_testtest_DIRECT_DAILY_FACT   a
</code>```

I get the message below,
ERROR 65-58: Name 'V_testtest_testtest_DIRECT_DAILY_FACT' is too long for a SAS name in this context. Any suggestion? Thank you

答:
The maximum length for a table name in SAS is 32 characters - V_testtest_testtest_DIRECT_DAILY_FACT is 37 characters.  As @Gordon suggests, you need to shorten the name.

As @Reeza suggests, one way to do this is to create a view in the native DB that has a shorter name.  Alternatively, use pass-through syntax in your query.

Body:
When I did the left join

left join V_testtest_testtest_DIRECT_DAILY_FACT   a

I get the message below,
ERROR 65-58: Name 'V_testtest_testtest_DIRECT_DAILY_FACT' is too long for a SAS name in this context. Any suggestion? Thank you


答:
You need to spread the array using ... spread Syntax.

console.log(String.fromCharCode(...[65, 66, 67]));```

From MDN

Spread syntax allows an iterable such as an array expression to be
  expanded in places where zero or more arguments (for function calls)
  or elements (for array literals) are expected, or an object expression
  to be expanded in places where zero or more key-value pairs (for
  object literals) are expected.

Title: Get string from a list contain Unicode in JavaScript

Body:
I have a list of Unicode values [65, 66, 67] and I want the corresponding string "ABC". I looked into the documentation and found the function String.fromCharCode()that does what I need to do. The only problem is that the arguments needs to be a sequence of numbers.

So if I use String.fromCharCode([65, 66, 67]) it gives me " ".

Is there a way that allows the list to be treated as a sequence for a function?

Body:
You need to spread the array using ... spread Syntax.

console.log(String.fromCharCode(...[65, 66, 67]));

From MDN

Spread syntax allows an iterable such as an array expression to be
  expanded in places where zero or more arguments (for function calls)
  or elements (for array literals) are expected, or an object expression
  to be expanded in places where zero or more key-value pairs (for
  object literals) are expected.


问:
Jenkins build trigger
I used jenkins remote trigger build option at job A and triggered another job B. When I open job B build, I could see "Started by remote project <path to job A>". I am trying to get the value  from job B after execution but I not working. I tried working with BuildUser plugin which gave null output. Could someone help me to find a way to find the information?</p>

答:
The Parameterized Remote Trigger Plugin job setup options have a section Build Info with a field Parameters. Define parameters there like:

```<code>TRIGGERED_BY_JOB=${JOB_NAME}
TRIGGERED_BY_BUILD_NO=${BUILD_NUMBER}
</code>```

and use them accordingly in your job B.

See Jenkins Set Environment Variables for other available information.

Title: Jenkins build trigger

Body:
The Parameterized Remote Trigger Plugin job setup options have a section Build Info with a field Parameters. Define parameters there like:

TRIGGERED_BY_JOB=${JOB_NAME}
TRIGGERED_BY_BUILD_NO=${BUILD_NUMBER}

and use them accordingly in your job B.

See Jenkins Set Environment Variables for other available information.


问:
Why does my array of NSManagedObjects is losing its properties?
In my UIViewController I call a method in another class which returns me a list of NSManagedObjects, which I instantiate in an array.
Here is the code:

```<code>fileprivate var albumList = [Album]()

private func loadAlbums() {
    APIHandler().getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}
</code>```

But this was causing my array to have nil properties once loadAlbums was finished and APIHandler's instance cleared. I solved this for now by having an instance of APIHandler on my UIViewController and calling the function from there, like this:

```<code>let api = SpotifyAPIHandler()
fileprivate var albumList = [Album]()

private func loadAlbums() {
    api.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}
</code>```

Still I am not happy with this. Why does this happen?
How can I instantiate a completely new list?

答:
I think what's happening is you're creating a new instance of APIHandler every time you're calling the loadAlbums() func instead what you can do is have a static refrence of ur APIHander in the APIHander class like so

```<code>class APIHander: NSObject {
    static let handler = APIHander()
}
</code>```

Then you would call your API like this

```<code>private func loadAlbums() {
    APIHandler.handler.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}
</code>```

Body:
In my UIViewController I call a method in another class which returns me a list of NSManagedObjects, which I instantiate in an array.
Here is the code:

fileprivate var albumList = [Album]()

private func loadAlbums() {
    APIHandler().getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}

But this was causing my array to have nil properties once loadAlbums was finished and APIHandler's instance cleared. I solved this for now by having an instance of APIHandler on my UIViewController and calling the function from there, like this:

let api = SpotifyAPIHandler()
fileprivate var albumList = [Album]()

private func loadAlbums() {
    api.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}

Still I am not happy with this. Why does this happen?
How can I instantiate a completely new list?

Body:
I think what's happening is you're creating a new instance of APIHandler every time you're calling the loadAlbums() func instead what you can do is have a static refrence of ur APIHander in the APIHander class like so

class APIHander: NSObject {
    static let handler = APIHander()
}

Then you would call your API like this

private func loadAlbums() {
    APIHandler.handler.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}


问:
How to check if two variables from different function are equals?
I'm new to Xcode and Swift but I'm trying my best :)
I need a little help. I have wrote this code so far... but I have an issue and I don't know how to solve it...
Well, my issue is that I cannot check if two variables are equal or not. To be more precise, I'd like to check if "fileAudio" number is equal to the photo number shown in the app.

I'd also need some help to show two random pictures (leftImage and rightImage) and the "playSound" button to be linked to one of them. At this moment... I only could make it linked to the leftImage.

```<code>var soundFiles: [String] = [
    "s0",
    "s1",
    "s2",
    "s3",
    "s4",
    "s5",
    "s6",
    "s7",
    "s8",
    "s9"
]

var images1: [UIImage] = [

    UIImage(named: "foto0.png")!,
    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var images2: [UIImage] = [
    UIImage(named: "foto0.png")!,
    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var happySad: [UIImage] = [
    UIImage(named: "sad.png")!,
    UIImage(named: "happy.png")!
    ]

var currentImageIndex = 0
var currentImage2Index = 0

var player: AVAudioPlayer!
var ran1:Int = 0
var ran2:Int = 0

@IBOutlet weak var leftImage: UIImageView!

@IBOutlet weak var rightImage: UIImageView!

@IBOutlet weak var sh: UIImageView!

@IBAction func playSound(_ sender: Any) {

    let fileaudio:String = "s"+String(ran1)
    let soundFilePath = Bundle.main.url(forResource: fileaudio, withExtension: ".m4a")!
    player = try! AVAudioPlayer(contentsOf: soundFilePath)
    player.prepareToPlay()
    player.play()
}
  @IBAction func nextImages(_ sender: Any) {
    ran1 = Int(arc4random_uniform(7) + 1)
    ran2 = Int(arc4random_uniform(6) + 2)

    let imageName1:String = "foto"+String(ran1)
    leftImage.image = UIImage.init(named: imageName1)

    let imageName2:String = "foto"+String(ran2)
    rightImage.image = UIImage.init(named: imageName2)

    leftImage.isUserInteractionEnabled = true
    self.view.addSubview(leftImage)
    let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap1))
    leftImage.addGestureRecognizer(gesture1)

    sh.image = UIImage(named: "question")
    rightImage.isUserInteractionEnabled = true
    self.view.addSubview(rightImage)
    let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap2))
    rightImage.addGestureRecognizer(gesture2)
 }

func singleTap1() {

    if currentImageIndex == ran1 {
        print("\(currentImageIndex)")
        sh.image = UIImage(named: "happy.png")
    } else {
        print("\(currentImageIndex)")
        sh.image = UIImage(named: "sad.png")
    }
}

func singleTap2() {
  if ran1 == ran2 {
        sh.image = UIImage(named: "happy.png")
    } else {
        sh.image = UIImage(named: "sad.png")
    }

}
</code>```

thank you, Radu

答:
You should generate a random number from 0 to 1 to represent the two buttons. One singleTap: function should handle both cases.

```<code>fileprivate var leftRightNum: Int!

@IBAction func nextImages(_ sender: Any) {
    ran1 = Int(arc4random_uniform(7) + 1)
    ran2 = Int(arc4random_uniform(6) + 2)

    let imageName1:String = "foto"+String(ran1)
    leftImage.image = UIImage.init(named: imageName1)

    let imageName2:String = "foto"+String(ran2)
    rightImage.image = UIImage.init(named: imageName2)

    leftImage.isUserInteractionEnabled = true
    self.view.addSubview(leftImage)
    let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap(_:)))
    leftImage.addGestureRecognizer(gesture1)

    sh.image = UIImage(named: "question")
    rightImage.isUserInteractionEnabled = true
    self.view.addSubview(rightImage)
    let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap(_:)))
    rightImage.addGestureRecognizer(gesture2)

    leftRightNum = Int(arc4random_uniform(2))
 }

@IBAction func playSound(_ sender: Any) {
    let fileaudio:String = "s"+String(leftRightNum == 0 ? ran1 : ran2)
    let soundFilePath = Bundle.main.url(forResource: fileaudio, withExtension: ".m4a")!
    player = try! AVAudioPlayer(contentsOf: soundFilePath)
    player.prepareToPlay()
    player.play()
}

func singleTap(_ recognizer: UIGestureRecognizer) {
    if (recognizer.view == leftImage && leftRightNum == 0) || (recognizer.view == rightImage && leftRightNum == 1) {
        sh.image = UIImage(named: "happy.png")
    } else {
        sh.image = UIImage(named: "sad.png")
    }
}
</code>```

Body:
I'm new to Xcode and Swift but I'm trying my best :)
I need a little help. I have wrote this code so far... but I have an issue and I don't know how to solve it...
Well, my issue is that I cannot check if two variables are equal or not. To be more precise, I'd like to check if "fileAudio" number is equal to the photo number shown in the app.

I'd also need some help to show two random pictures (leftImage and rightImage) and the "playSound" button to be linked to one of them. At this moment... I only could make it linked to the leftImage.

var soundFiles: [String] = [
    "s0",
    "s1",
    "s2",
    "s3",
    "s4",
    "s5",
    "s6",
    "s7",
    "s8",
    "s9"
]

var images1: [UIImage] = [

    UIImage(named: "foto0.png")!,
    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var images2: [UIImage] = [
    UIImage(named: "foto0.png")!,
    UIImage(named: "foto1.png")!,
    UIImage(named: "foto2.png")!,
    UIImage(named: "foto3.png")!,
    UIImage(named: "foto4.png")!,
    UIImage(named: "foto5.png")!,
    UIImage(named: "foto6.png")!,
    UIImage(named: "foto7.png")!,
    UIImage(named: "foto8.png")!
]

var happySad: [UIImage] = [
    UIImage(named: "sad.png")!,
    UIImage(named: "happy.png")!
    ]

var currentImageIndex = 0
var currentImage2Index = 0

var player: AVAudioPlayer!
var ran1:Int = 0
var ran2:Int = 0

@IBOutlet weak var leftImage: UIImageView!

@IBOutlet weak var rightImage: UIImageView!

@IBOutlet weak var sh: UIImageView!

@IBAction func playSound(_ sender: Any) {

    let fileaudio:String = "s"+String(ran1)
    let soundFilePath = Bundle.main.url(forResource: fileaudio, withExtension: ".m4a")!
    player = try! AVAudioPlayer(contentsOf: soundFilePath)
    player.prepareToPlay()
    player.play()
}
  @IBAction func nextImages(_ sender: Any) {
    ran1 = Int(arc4random_uniform(7) + 1)
    ran2 = Int(arc4random_uniform(6) + 2)

    let imageName1:String = "foto"+String(ran1)
    leftImage.image = UIImage.init(named: imageName1)

    let imageName2:String = "foto"+String(ran2)
    rightImage.image = UIImage.init(named: imageName2)

    leftImage.isUserInteractionEnabled = true
    self.view.addSubview(leftImage)
    let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap1))
    leftImage.addGestureRecognizer(gesture1)

    sh.image = UIImage(named: "question")
    rightImage.isUserInteractionEnabled = true
    self.view.addSubview(rightImage)
    let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap2))
    rightImage.addGestureRecognizer(gesture2)
 }

func singleTap1() {

    if currentImageIndex == ran1 {
        print("\(currentImageIndex)")
        sh.image = UIImage(named: "happy.png")
    } else {
        print("\(currentImageIndex)")
        sh.image = UIImage(named: "sad.png")
    }
}

func singleTap2() {
  if ran1 == ran2 {
        sh.image = UIImage(named: "happy.png")
    } else {
        sh.image = UIImage(named: "sad.png")
    }

}

thank you, Radu

Body:
You should generate a random number from 0 to 1 to represent the two buttons. One singleTap: function should handle both cases.

fileprivate var leftRightNum: Int!

@IBAction func nextImages(_ sender: Any) {
    ran1 = Int(arc4random_uniform(7) + 1)
    ran2 = Int(arc4random_uniform(6) + 2)

    let imageName1:String = "foto"+String(ran1)
    leftImage.image = UIImage.init(named: imageName1)

    let imageName2:String = "foto"+String(ran2)
    rightImage.image = UIImage.init(named: imageName2)

    leftImage.isUserInteractionEnabled = true
    self.view.addSubview(leftImage)
    let gesture1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap(_:)))
    leftImage.addGestureRecognizer(gesture1)

    sh.image = UIImage(named: "question")
    rightImage.isUserInteractionEnabled = true
    self.view.addSubview(rightImage)
    let gesture2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap(_:)))
    rightImage.addGestureRecognizer(gesture2)

    leftRightNum = Int(arc4random_uniform(2))
 }

@IBAction func playSound(_ sender: Any) {
    let fileaudio:String = "s"+String(leftRightNum == 0 ? ran1 : ran2)
    let soundFilePath = Bundle.main.url(forResource: fileaudio, withExtension: ".m4a")!
    player = try! AVAudioPlayer(contentsOf: soundFilePath)
    player.prepareToPlay()
    player.play()
}

func singleTap(_ recognizer: UIGestureRecognizer) {
    if (recognizer.view == leftImage && leftRightNum == 0) || (recognizer.view == rightImage && leftRightNum == 1) {
        sh.image = UIImage(named: "happy.png")
    } else {
        sh.image = UIImage(named: "sad.png")
    }
}


问:
Service Fabric and Application Insights
I am new to service Fabric and trying to integrate my windows service application into service fabric. For logging information, we are planning to use Application Insights. But the events are not logged if i send it through my SF application. At the same time, through a normal console/windows application, I can able to log the message to applicationinsights and can be viewed from there.

Then I tried to create a VM in azure environment, and create SF application there and send the log information to AI and its worked successfully. I copied the same codebase  into my local machine and run it, its not working. I am not sure whether its related to any firewall or proxy settings. Can anyone help on this?

I have used the nuget package to install Microsoft.ApplicationInsights dll in my machine. The version that I used is 2.2.0. And I am using .Net framework 4.6.1

答:
You can adapt the watchdog Service from Microsoft Samples. The watchdog Service is a generic standalone Service Fabric Stateful Service that will log data into Application Insights.

Add the watchdog app and watchdog service into your solution.

Add your Azure App ID in the WatchDogService -PackageRoot/Config/ServiceManifest.xml

In the service that you need monitored, in the Run Async command, add the following lines (Example is in the Test Stateless Service provided in the link below)

Code:

```<code> protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        // Register the health check and metrics with the watchdog.
        bool healthRegistered = await this.RegisterHealthCheckAsync(cancellationToken);
        bool metricsRegistered = await this.RegisterMetricsAsync(cancellationToken);

        while (true)
        {
            // Report some fake metrics to Service Fabric.
            this.ReportFakeMetrics(cancellationToken);
            await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);

            // Check that registration was successful. Could also query the watchdog for additional safety.
            if (false == healthRegistered)
            {
                healthRegistered = await this.RegisterHealthCheckAsync(cancellationToken);
            }
            if (false == metricsRegistered)
            {
                metricsRegistered = await this.RegisterMetricsAsync(cancellationToken);
            }
        }
    }
</code>```

Copy the RegisterHealthCheckAsync, RegisterMetricsAsync and ReportFakeMetrics methods, as is, into your service.cs file.

That should be it! It uses Azure Storage optionally. I did not have to implement that to get the watchdog up and running.

Here is the link : https://github.com/Azure-Samples/service-fabric-watchdog-service

Title: Service Fabric and Application Insights

Body:
You can adapt the watchdog Service from Microsoft Samples. The watchdog Service is a generic standalone Service Fabric Stateful Service that will log data into Application Insights.

Add the watchdog app and watchdog service into your solution.

Add your Azure App ID in the WatchDogService -PackageRoot/Config/ServiceManifest.xml

In the service that you need monitored, in the Run Async command, add the following lines (Example is in the Test Stateless Service provided in the link below)

Code:

 protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        // Register the health check and metrics with the watchdog.
        bool healthRegistered = await this.RegisterHealthCheckAsync(cancellationToken);
        bool metricsRegistered = await this.RegisterMetricsAsync(cancellationToken);

        while (true)
        {
            // Report some fake metrics to Service Fabric.
            this.ReportFakeMetrics(cancellationToken);
            await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);

            // Check that registration was successful. Could also query the watchdog for additional safety.
            if (false == healthRegistered)
            {
                healthRegistered = await this.RegisterHealthCheckAsync(cancellationToken);
            }
            if (false == metricsRegistered)
            {
                metricsRegistered = await this.RegisterMetricsAsync(cancellationToken);
            }
        }
    }

Copy the RegisterHealthCheckAsync, RegisterMetricsAsync and ReportFakeMetrics methods, as is, into your service.cs file.

That should be it! It uses Azure Storage optionally. I did not have to implement that to get the watchdog up and running.

Here is the link : https://github.com/Azure-Samples/service-fabric-watchdog-service


问:
How can I create table in bash output, that shows every item about specific user?
I have simple bash script

```<code>#!/bin/bash

grep home /etc/passwd | grep $1
</code>```

that shows information about user,
    example of output:

```<code> Vladislav:x:1000:1000:Vladislav,,,:/home/vladislav:/bin/bash
</code>```

Is it possible to make it look like table (example screenshot) ? I mean - with 2 columns and
simple separator between rows

答:
if all you want is columns you can format it like:

```<code>grep home /etc/passwd | grep $1 | sed 's/:/ /g' | awk '{NAME=$1;ENC=$2;AMT=3;MIN=$4;$1=$2=$3=$4="";print "name\t"NAME"\nEncrypted password\t"ENC"\nAmount of days\t"AMT"\nMinimum count of days\t"MIN"\nOther item description\t"$0}'
</code>```

This will take your original output, replace the : with a literal space then feed it into awk and format your "table".

The output I get from your sample input string is:

```<code>name    Vladislav
Encrypted password  x
Amount of days  3
Minimum count of days   1000
Other item description      Vladislav,,, /home/vladislav /bin/bash
</code>```

Body:
I have simple bash script

#!/bin/bash

grep home /etc/passwd | grep $1

that shows information about user,
    example of output:

 Vladislav:x:1000:1000:Vladislav,,,:/home/vladislav:/bin/bash

Is it possible to make it look like table (example screenshot) ? I mean - with 2 columns and
simple separator between rows

Body:
if all you want is columns you can format it like:

grep home /etc/passwd | grep $1 | sed 's/:/ /g' | awk '{NAME=$1;ENC=$2;AMT=3;MIN=$4;$1=$2=$3=$4="";print "name\t"NAME"\nEncrypted password\t"ENC"\nAmount of days\t"AMT"\nMinimum count of days\t"MIN"\nOther item description\t"$0}'

This will take your original output, replace the : with a literal space then feed it into awk and format your "table".

The output I get from your sample input string is:

name    Vladislav
Encrypted password  x
Amount of days  3
Minimum count of days   1000
Other item description      Vladislav,,, /home/vladislav /bin/bash


问:
how to know remotely if spark job is running on cluster
I am running spark job on ec2 cluster, I have a trigger that submits job periodically. I do not want to submit job if one job is already running on cluster. Is there any api that can give me this information?</p>

答:
you can consult the UI to see the status
eg.
If you run locally, take a look at the localhost:4040</p>


问:
User Provided CSV in Django Web Project
I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

```<code><input type="file" accept="text/csv" id="mycsv">
</code>```

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

答:
Files uploaded by the user will go to the media folder that you have defined in your settings.py file.

You should be able to access user uploaded files in the media directory from your python code with something like this:

```<code>file_ = open(os.path.join(settings.MEDIA_ROOT, 'name_of_file'))
</code>```

More info on MEDIA_ROOT and MEDIA_URL can be found here.

Title: User Provided CSV in Django Web Project

Body:
I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

<input type="file" accept="text/csv" id="mycsv">

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

Body:
Files uploaded by the user will go to the media folder that you have defined in your settings.py file.

You should be able to access user uploaded files in the media directory from your python code with something like this:

file_ = open(os.path.join(settings.MEDIA_ROOT, 'name_of_file'))

More info on MEDIA_ROOT and MEDIA_URL can be found here.


问:
OpenGL float precision makes unexpected differece
I have a function which rotates the camera around the player by yaw and pitch angles.

```<code>void Camera::updateVectors() {
    GLfloat radius = glm::length(center - position);
    position.x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position.y = sin(glm::radians(this->pitch));
    position.z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position *= radius;
    this->front = glm::normalize(center - position);
    this->right = glm::normalize(glm::cross(this->front, this->worldUp));
    this->up = glm::normalize(glm::cross(this->right, this->front));
    lookAt = glm::lookAt(this->position, this->position + this->front, this->up);
}
</code>```

When I move the player the camera should moves with it by adding a translation vector to both the center and position of the camera:

```<code>void Camera::Transform(glm::vec3& t) {
    this->position += t;
    this->center += t;
}
</code>```

Vefore moving the player the camera rotation works fine and the player movement also works fine but once I try to rotate the camera after player moving it start to change position unexpected.

After making some debugging I noticed that the radius which Is calculated at first line which is the distance between center and position of the camera like 49.888889 or 50.000079 and due to the initialized values it should be 50.0, this very small difference makes the result unexpected at all.
so how could I treat this float precision or is there a bug in my code or calculations.

Edit:
 position the player depends on its yaw and pitch and update the center of the camera

```<code>GLfloat velocity = this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Transform(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Transform(f);
}
</code>```

答:
the solution simply is making transformations on the camera view matrix instead of making it by lookAt function
 first initialize the camera

```<code>void Camera::initCamera(glm::vec3& pos, glm::vec3& center, GLfloat yaw, GLfloat pitch) {
    view = glm::translate(view, center-pos);
    view = glm::rotate(view, glm::radians(yaw), glm::vec3(0.0, 1.0, 0.0));
    view = glm::rotate(view, glm::radians(pitch), glm::vec3(1.0, 0.0, 0.0));
    view = glm::translate(view, pos-center);
}
</code>```

then the rotation function:

```<code>void Camera::Rotate(GLfloat xoffset, GLfloat yoffset, glm::vec3& c) {
    xoffset *= this->mouseSensitivity;
    yoffset *= this->mouseSensitivity;
    view = glm::translate(view, c );//c is the player position
    view = glm::rotate(view, glm::radians(xoffset), glm::vec3(0.0, 1.0, 0.0));
    view = glm::rotate(view, glm::radians(yoffset), glm::vec3(1.0, 0.0, 0.0));
    view = glm::translate(view,  - c);
}
</code>```

and the camera move function:

```<code>void Camera::Translate(glm::vec3& t) {
    view = glm::translate(view, -t);
}
</code>```

and in the player class when the player moves it push camera to move in its direction by this code

```<code>void Mesh::Move(Move_Directions direction, GLfloat deltaTime) {
GLfloat velocity = 50.0f * this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Translate(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Translate(f);
}
if (direction == RIGHT) {
    matrix = glm::rotate(matrix, (GLfloat) -M_PI * deltaTime, glm::vec3(0.0, 1.0, 0.0));
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
}
if (direction == LEFT) {
    matrix = glm::rotate(matrix, (GLfloat) M_PI * deltaTime, glm::vec3(0.0, 1.0, 0.0));
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
}
}
</code>```

thanks for every body helped

Body:
I have a function which rotates the camera around the player by yaw and pitch angles.

void Camera::updateVectors() {
    GLfloat radius = glm::length(center - position);
    position.x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position.y = sin(glm::radians(this->pitch));
    position.z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position *= radius;
    this->front = glm::normalize(center - position);
    this->right = glm::normalize(glm::cross(this->front, this->worldUp));
    this->up = glm::normalize(glm::cross(this->right, this->front));
    lookAt = glm::lookAt(this->position, this->position + this->front, this->up);
}

When I move the player the camera should moves with it by adding a translation vector to both the center and position of the camera:

void Camera::Transform(glm::vec3& t) {
    this->position += t;
    this->center += t;
}

Vefore moving the player the camera rotation works fine and the player movement also works fine but once I try to rotate the camera after player moving it start to change position unexpected.

After making some debugging I noticed that the radius which Is calculated at first line which is the distance between center and position of the camera like 49.888889 or 50.000079 and due to the initialized values it should be 50.0, this very small difference makes the result unexpected at all.
so how could I treat this float precision or is there a bug in my code or calculations.

Edit:
 position the player depends on its yaw and pitch and update the center of the camera

GLfloat velocity = this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Transform(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Transform(f);
}

Body:
the solution simply is making transformations on the camera view matrix instead of making it by lookAt function
 first initialize the camera

void Camera::initCamera(glm::vec3& pos, glm::vec3& center, GLfloat yaw, GLfloat pitch) {
    view = glm::translate(view, center-pos);
    view = glm::rotate(view, glm::radians(yaw), glm::vec3(0.0, 1.0, 0.0));
    view = glm::rotate(view, glm::radians(pitch), glm::vec3(1.0, 0.0, 0.0));
    view = glm::translate(view, pos-center);
}

then the rotation function:

void Camera::Rotate(GLfloat xoffset, GLfloat yoffset, glm::vec3& c) {
    xoffset *= this->mouseSensitivity;
    yoffset *= this->mouseSensitivity;
    view = glm::translate(view, c );//c is the player position
    view = glm::rotate(view, glm::radians(xoffset), glm::vec3(0.0, 1.0, 0.0));
    view = glm::rotate(view, glm::radians(yoffset), glm::vec3(1.0, 0.0, 0.0));
    view = glm::translate(view,  - c);
}

and the camera move function:

void Camera::Translate(glm::vec3& t) {
    view = glm::translate(view, -t);
}

and in the player class when the player moves it push camera to move in its direction by this code

void Mesh::Move(Move_Directions direction, GLfloat deltaTime) {
GLfloat velocity = 50.0f * this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Translate(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Translate(f);
}
if (direction == RIGHT) {
    matrix = glm::rotate(matrix, (GLfloat) -M_PI * deltaTime, glm::vec3(0.0, 1.0, 0.0));
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
}
if (direction == LEFT) {
    matrix = glm::rotate(matrix, (GLfloat) M_PI * deltaTime, glm::vec3(0.0, 1.0, 0.0));
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
}
}

thanks for every body helped


问:
git not honoring git info exclude
I am working on a shared repository and I want to exclude all the files under certain directory just for myself.
So I made an entry in $GIT_ROOT/.git/info/exclude

```<code>/path/to/folder/
</code>```

After this I removed the indexes using

```<code>git rm -r --cached /path/to/folder/*
</code>```

A git status after this show a long list of deleted file staged for commit.
I commit the changes and till here all is good as any changes  made by me are not tracked by git. But I can not push the same to remote as this will mess up other developers working repo.
After this If I pull from remote it shows me a merge conflict modified by them/deleted by us. And with git reset --hard origin/<branch_name> It starts tracking the folder again.

Can this not be achieved because I can not push to remote ?

答: The thing is that you are committing the files as "removed". That means that anybody that wants to merge your change will get the files removed. Also, if anyone (who hasn't merged your change) modifies those files, when you merge the change from the other developer, you will get a tree conflict. The best you can do under the circumstance is to tell git to not care about those files, while keeping them under the project. This is done with git update-index --assume-unchanged

Title: git not honoring git info exclude

Body:
I am working on a shared repository and I want to exclude all the files under certain directory just for myself.
So I made an entry in $GIT_ROOT/.git/info/exclude

/path/to/folder/

After this I removed the indexes using

git rm -r --cached /path/to/folder/*

A git status after this show a long list of deleted file staged for commit.
I commit the changes and till here all is good as any changes  made by me are not tracked by git. But I can not push the same to remote as this will mess up other developers working repo.
After this If I pull from remote it shows me a merge conflict modified by them/deleted by us. And with git reset --hard origin/<branch_name> It starts tracking the folder again.

Can this not be achieved because I can not push to remote ?


问:
Wordpress Advanced Custom Fields - Advanced Repeater
So I working on a wordpress site with the FoundationPress Theme and I recently upgraded ACF to the Pro version which allows for the repeater field.  So I'm trying to allow the client to add new social media accounts with the repeater.

http://imgur.com/FT58SpD

http://imgur.com/MydpAwl

Above you can see how the repeater is set up on the backend.

Header.php:

```<code><div class="medium-3 columns">
  <?php
    if (have_rows('social_media')):
      while(have_rows('social_media')):the_row();

        $link = get_sub_field('social_media_link'); ?>
        <a href="<?php echo $link; ?>" />
      <?php endwhile;
    endif;
  ?>
</div>
</code>```

Nothing is outputted into the HTML.

Let me know if I left out any information

答:
The options page requires an additional value in the field code (see https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/).</p>

```<code>  <div class="medium-3 columns">
  <?php
    if (have_rows('social_media', 'option')):
      while(have_rows('social_media', 'option')):the_row();

        $link = get_sub_field('social_media_link'); ?>
        <a href="<?php echo $link; ?>" />
      <?php endwhile;
    endif;
  ?>
</div>
</code>```

Body:
So I working on a wordpress site with the FoundationPress Theme and I recently upgraded ACF to the Pro version which allows for the repeater field.  So I'm trying to allow the client to add new social media accounts with the repeater.

http://imgur.com/FT58SpD

http://imgur.com/MydpAwl

Above you can see how the repeater is set up on the backend.

Header.php:

  <?php
    if (have_rows('social_media')):
      while(have_rows('social_media')):the_row();

        $link = get_sub_field('social_media_link'); ?>
        <a href="<?php echo $link; ?>" />
      <?php endwhile;
    endif;
  ?>

Nothing is outputted into the HTML.

Let me know if I left out any information

Body:
The options page requires an additional value in the field code (see https://www.advancedcustomfields.com/resources/get-values-from-an-options-page/).

  <div class="medium-3 columns">
  <?php
    if (have_rows('social_media', 'option')):
      while(have_rows('social_media', 'option')):the_row();

        $link = get_sub_field('social_media_link'); ?>
        <a href="<?php echo $link; ?>" />
      <?php endwhile;
    endif;
  ?>
</div>


问:
bash - find duplicate file in directory and rename
I have a directory that has thousands of files in it with various extensions.  I also have a drop location where users drop files to be migrated to this directory.  I'm looking for a script that will scan the target directory for a duplicate file name, if found, rename the file in the drop folder, then move it to the target directory.
Example:

/target/file.doc
/drop/file.doc

Script will rename file.doc to file1.doc then move it to /target/.
It needs to maintain the file extension too.

答:
You have to take a bit more care than simply checking if a file exists before moving in order to provide a flexible solution that can handle files with or without extensions. You also may want to provide a way of forming duplicate filenames that preserves sort order. e.g. if file.txt already exists, you may want to use file_001.txt as the duplicate in target rather than file1.txt as when you reach 10 you will no longer have a canonical sort by filename.

Also, you never want to iterate with for i in $(ls dir) that is wrought with pitfalls. See Bash Pitfalls No. 1

Putting those pieces together, and including detail in the comments below, you could do something similar to the following and have a reasonable flexible solution allowing you to specify only the filename.ext to move or /path/to/drop/filename.ext. You must specify the drop and target directories in the script to meet your circumstance., e.g.

```<code>#!/bin/bash

tgt=target          ## set target and drop directories as required
drp=drop
declare -i cnt=1    ## counter for filename_$cnt

test -z "$1" && {   ## validate one argument given
    printf "error: insufficient input\nusage: %s filename\n" "${0##*/}"
    exit 1
}
test -w "$1" || test -w "$drp/$1" || {   ## validate valid filename is writeable
    printf "error: file not found or lack permission to move '%s'.\n" "$1"
    exit 1
}

fn="${1##*/}"                   ## strip any path info from filename
if test "$1" != "${1%.*}" ; then
    ext="${fn##*.}"             ## get file extension
    fnwoe="${fn%."$ext"}"       ## get filename without extension
    test "$fnwoe" = '' && ext=  ## was a dotfile, reset ext
fi

vfn="$fn"   ## set valid filename = filename

## form valid filename e.g. "$fn_001.$ext" if duplicate found
while test -e "$tgt/$vfn"; do
    if test -n "$ext"   ## did we have have an extension?
    then
        printf -v vfn "%s_%03d.%s" "$fnwoe" "$((cnt++))" "$ext"
    else
        printf -v vfn "%s_%03d" "$fn" "$((cnt++))"
    fi
done

mv "$drp/$fn" "$tgt/$vfn"       ## move file under non-conflicting name
</code>```

Example drop and target

```<code>$ ls -1 drop
file
file.txt

$ ls -1 target
file.txt
file_001.txt
file_002.txt
</code>```

Example Use

```<code>$ bash mvdrop.sh file
$ bash mvdrop.sh drop/file.txt
</code>```

Resulting drop and target

```<code>$ ls -1 drop

$ ls -1 target
file
file.txt
file_001.txt
file_002.txt
file_003.txt
</code>```

Body:
You have to take a bit more care than simply checking if a file exists before moving in order to provide a flexible solution that can handle files with or without extensions. You also may want to provide a way of forming duplicate filenames that preserves sort order. e.g. if file.txt already exists, you may want to use file_001.txt as the duplicate in target rather than file1.txt as when you reach 10 you will no longer have a canonical sort by filename.

Also, you never want to iterate with for i in $(ls dir) that is wrought with pitfalls. See Bash Pitfalls No. 1

Putting those pieces together, and including detail in the comments below, you could do something similar to the following and have a reasonable flexible solution allowing you to specify only the filename.ext to move or /path/to/drop/filename.ext. You must specify the drop and target directories in the script to meet your circumstance., e.g.

#!/bin/bash

tgt=target          ## set target and drop directories as required
drp=drop
declare -i cnt=1    ## counter for filename_$cnt

test -z "$1" && {   ## validate one argument given
    printf "error: insufficient input\nusage: %s filename\n" "${0##*/}"
    exit 1
}
test -w "$1" || test -w "$drp/$1" || {   ## validate valid filename is writeable
    printf "error: file not found or lack permission to move '%s'.\n" "$1"
    exit 1
}

fn="${1##*/}"                   ## strip any path info from filename
if test "$1" != "${1%.*}" ; then
    ext="${fn##*.}"             ## get file extension
    fnwoe="${fn%."$ext"}"       ## get filename without extension
    test "$fnwoe" = '' && ext=  ## was a dotfile, reset ext
fi

vfn="$fn"   ## set valid filename = filename

## form valid filename e.g. "$fn_001.$ext" if duplicate found
while test -e "$tgt/$vfn"; do
    if test -n "$ext"   ## did we have have an extension?
    then
        printf -v vfn "%s_%03d.%s" "$fnwoe" "$((cnt++))" "$ext"
    else
        printf -v vfn "%s_%03d" "$fn" "$((cnt++))"
    fi
done

mv "$drp/$fn" "$tgt/$vfn"       ## move file under non-conflicting name

Example drop and target

$ ls -1 drop
file
file.txt

$ ls -1 target
file.txt
file_001.txt
file_002.txt

Example Use

$ bash mvdrop.sh file
$ bash mvdrop.sh drop/file.txt

Resulting drop and target

$ ls -1 drop

$ ls -1 target
file
file.txt
file_001.txt
file_002.txt
file_003.txt


问:
Why is the payload lost from FCM push notification?
I have integrate FCM using a NodeJS app server and am able to successfully send Push Notifications using below code. I am using Service Worker on client side to handle the Push notifications in a PWA

```<code>fetch(firebase_url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `key=${firebase_auth}`
    },
    body: JSON.stringify({
        "to" : recieverToken,
        "data" : {
            "text": "Hello world"
        },
        "notification": {
            "title": "Portugal vs. Denmark",
            "body": "5 to 1"
        }
    })
})
</code>```

The problem I have is that the payload data is null as shown and I couldn't find the reason behind it

答:
```<code>function post(postkey,messageTitle,messageBody) {
    $.ajax({
        type : 'POST',
        url : "https://fcm.googleapis.com/fcm/send",
        headers : {
            Authorization : 'key=%%YOUR FCMKEY%%'
        },
        contentType : 'application/json',
        data : JSON.stringify({
            "to": postkey,
            "notification": {
                "icon": 'qc/logo_Tran.png',
                "click_action": '%%YOUR URL%%',
                "body": messageBody,
                "title": messageTitle
            }
        }) ,
        success : function(response) {
            console.log(response);
        },
        error : function(xhr, status, error) {
            console.log(xhr.error);
        }
    });
}
</code>```

Body:
I have integrate FCM using a NodeJS app server and am able to successfully send Push Notifications using below code. I am using Service Worker on client side to handle the Push notifications in a PWA

fetch(firebase_url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `key=${firebase_auth}`
    },
    body: JSON.stringify({
        "to" : recieverToken,
        "data" : {
            "text": "Hello world"
        },
        "notification": {
            "title": "Portugal vs. Denmark",
            "body": "5 to 1"
        }
    })
})

The problem I have is that the payload data is null as shown and I couldn't find the reason behind it


问:
Making a multiple field search in Django
I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. Here is my code below:

models.py

```<code>class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
</code>```

views.py

```<code>def search_Schedule(request):
    context_dict = {}
    if request.method == 'POST':
        query1 = request.POST['course_name_search']
        query2 = request.POST['start_date_search']
        query3 = request.POST['instructor_search']
        if query1:
            results = Schedules.objects.filter(course_name__icontains=query1)
            if query2:
                results = results.filter(start_time=query2)
                if query3:
                    results = results.filter(instructor__icontains=query3)
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
                else:
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + " and " + query2
            elif query3:
                results = results.filter(start_time__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1
        elif query2:
            results = Schedules.objects.filter(start_time=query2)
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2
        elif query3:
            results = Schedules.objects.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query3
    return render(request, "schedule/search_schedule.html", context_dict)
</code>```

search_schedule.html

```<code>{% block main_content %}
    <form method="post" action="">
        {% csrf_token %}
        <label for="course_name_search">Course Name:</label>
        <input type="text" name="course_name_search" id="course_name_search">

        <label for="start_date_search">Start Date:</label>
        <input type="datetime" name="start_date_search" id="start_date_search">

        <label for="instructor_search">Instructor:</label>
        <input type="text" name="instructor_search" id="instructor_search"><br>
        <input type="submit" name="submit">
    </form>
    <div id="result_panel">
        {% if table %}
            {% render_table table %}
        {% else %}
            {% if no_results %}
                No results returned for <q>{{ no_results }}</q>
            {% else %}
                Please enter a search
            {% endif %}
        {% endif %}
{% endblock %}
</code>```

For some reason, the search will work if I type in the course name field OR the instructor field, but won't work if I type in more than one field. And for some reason, the start date field will not work period, no matter how I type the date. Can somebody possibly help me with the correct way to type the code? Thank you.

答:
You could try a drill-down method for your filtering to minimize your if statements:

```<code>course_name_search = request.POST.get('course_name_search', None)
start_date_search = request.POST.get('start_date_search', None)
instructor_search = request.POST.get('instructor_search', None)

queryset = Schedules.objects.all()

if course_name_search:
    queryset = queryset.filter(course_name__icontains=course_name_search)
if start_date_search:
    queryset = queryset.filter(start_date=start_date_search)
if instructor_search:
    queryset = queryset.filter(instructor__icontains=instructor_search)

# if none of the search params were filled in then return none
if not course_name_search and not start_date_search and not instructor_search:
    queryset = Schedules.objects.none()
</code>```

But a few caveats here, and something to help your issue with the start dates, since you are reading the POST data directly you'll need to convert your start_date_search into an actual date before you query.

The other thing that will help you is it might be better to use a GET instead of a POST, which you can then read in the template to fill in the chosen values that you now fill into the 'no_results'.

Body:
I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. Here is my code below:

models.py

class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')

views.py

def search_Schedule(request):
    context_dict = {}
    if request.method == 'POST':
        query1 = request.POST['course_name_search']
        query2 = request.POST['start_date_search']
        query3 = request.POST['instructor_search']
        if query1:
            results = Schedules.objects.filter(course_name__icontains=query1)
            if query2:
                results = results.filter(start_time=query2)
                if query3:
                    results = results.filter(instructor__icontains=query3)
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
                else:
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + " and " + query2
            elif query3:
                results = results.filter(start_time__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1
        elif query2:
            results = Schedules.objects.filter(start_time=query2)
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2
        elif query3:
            results = Schedules.objects.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query3
    return render(request, "schedule/search_schedule.html", context_dict)

search_schedule.html

{% block main_content %}
    <form method="post" action="">
        {% csrf_token %}
        Course Name:
        <input type="text" name="course_name_search" id="course_name_search">

        Start Date:
        <input type="datetime" name="start_date_search" id="start_date_search">

        Instructor:
        <input type="text" name="instructor_search" id="instructor_search">

        <input type="submit" name="submit">
    </form>

        {% if table %}
            {% render_table table %}
        {% else %}
            {% if no_results %}
                No results returned for <q>{{ no_results }}</q>
            {% else %}
                Please enter a search
            {% endif %}
        {% endif %}
{% endblock %}

For some reason, the search will work if I type in the course name field OR the instructor field, but won't work if I type in more than one field. And for some reason, the start date field will not work period, no matter how I type the date. Can somebody possibly help me with the correct way to type the code? Thank you.

Body:
You could try a drill-down method for your filtering to minimize your if statements:

course_name_search = request.POST.get('course_name_search', None)
start_date_search = request.POST.get('start_date_search', None)
instructor_search = request.POST.get('instructor_search', None)

queryset = Schedules.objects.all()

if course_name_search:
    queryset = queryset.filter(course_name__icontains=course_name_search)
if start_date_search:
    queryset = queryset.filter(start_date=start_date_search)
if instructor_search:
    queryset = queryset.filter(instructor__icontains=instructor_search)

# if none of the search params were filled in then return none
if not course_name_search and not start_date_search and not instructor_search:
    queryset = Schedules.objects.none()

But a few caveats here, and something to help your issue with the start dates, since you are reading the POST data directly you'll need to convert your start_date_search into an actual date before you query.

The other thing that will help you is it might be better to use a GET instead of a POST, which you can then read in the template to fill in the chosen values that you now fill into the 'no_results'.


问:
How to show pop up in Xamarin forms. i should not use third party plugins
How to show pop up in Xamarin Forms, without using third party plugins such as Rg plugin or x-labs plugin?
See attached images.enter image description here</p>

答:
There is an official guide on the Xamarin site to get simpel popups:

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/navigation/pop-ups/

I suggest reading it all, you can also make your own popups like rg.plugins by checking out their code and writing it yourself


问:
5 if statement formula
I recently created an IF formula to run inside a macro for only 2 statements but I need to add 3 more to it.

This is for altering a filename. So I use the LEN to determine what type of file it is then run the appropriate formula to trim out what I don't want.

Examples:

173d0221.pdf = S-173-D022 Description.pdf
 =CHAR(83)&CHAR(45)&LEFT(B11,LEN(B11)-9)&CHAR(45)&UPPER(MID(B11,4,LEN(B11)-8))&CHAR(32)&D11&E11

173d02210.pdf = S-173-D022 Description.pdf =CHAR(83)&CHAR(45)&LEFT(B12,LEN(B12)-10)&CHAR(45)&UPPER(MID(B12,4,LEN(B12)-9))&CHAR(32)&D12&E12

173d170c141.pdf = SD-170-C14 Description.pdf
 =CHAR(83)&CHAR(68)&CHAR(45)&UPPER(MID(B13,5,LEN(B13)-12))&CHAR(45)&UPPER(MID(B13,8,LEN(B13)-12)&CHAR(32)&D13&E13)

REF-173d0221.pdf = REF-173-D022 Description.pdf
 =LEFT(B14,LEN(B14)-9)&CHAR(45)&UPPER(MID(B14,8,LEN(B14)-12))&CHAR(32)&D14&E14

REF-173d02210.pdf = REF-173-D022 Description.pdf
 =LEFT(B15,LEN(B15)-10)&CHAR(45)&UPPER(MID(B15,8,LEN(B15)-13))&CHAR(32)&D15&E15

I am having trouble linking them together to get it to apply the right formula based on the length of the cell.

Notes: I am using CHAR(83)&CHAR(45) instead of "S-" because VBA wasn't liking the text. I will update the "B12" cell tag with " & aCell & " once everything is working smoothly.

My vba code looks like:

```<code>.Range("C2:C" & LastRow).Formula = "=IF(LEN(" & aCell & ")=12,CHAR(83)&CHAR(45)&LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",4,LEN(" & aCell & ")-8))&CHAR(32)&" & dCell & "&" & eCell & ",LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",8,LEN(" & aCell & ")-12))&CHAR(32)&" & dCell & "&" & eCell & ")"
</code>```

答:
This seems to work for the first three example formula.

I'll leave it to you to translate the remaining 2 formula to VBA, which you should be able to do following my examples :)

```<code>Option Explicit

Sub foo()
Dim rng As Range, aCell As Range
Dim val As String
Set rng = Range("B1:B5")  '## Modify the input range as needed.
For Each aCell In rng.Cells
    Select Case Len(aCell)
        Case 12
            val = "S-" & Left(aCell, Len(aCell) - 9) & "-" & Mid(aCell, 4, Len(aCell) - 8)
        Case 13
            val = "S-" & Left(aCell, Len(aCell) - 10) & "-" & Mid(aCell, 4, Len(aCell) - 9)
        Case 15
            val = "SD-" & Mid(aCell, 5, Len(aCell) - 12) & "-" & Mid(aCell, 8, Len(aCell) - 12)
        Case 16
            val = "REF-" '## Modify as needed
        Case 17
            val = "REF-" '## Modify as needed
        Case Else
            'maybe warn the user this input is not anticipated...
            MsgBox "Unsupported length!", vbInformation
    End Select
    val = UCase(val)
    '## Append the values from column D,E:
    val = val & " " & aCell.Offset(, 2) & aCell.Offset(, 3)
    '## Write out to the workbook in column F, modify the "5" to specify a different location if needed e.g., "-1" would put it in column A, "0" would put in same column B, etc.
    aCell.Offset(, 4).Value = val
Next
End Sub
</code>```

Title: 5 if statement formula

Body:
I recently created an IF formula to run inside a macro for only 2 statements but I need to add 3 more to it.

This is for altering a filename. So I use the LEN to determine what type of file it is then run the appropriate formula to trim out what I don't want.

Examples:

173d0221.pdf = S-173-D022 Description.pdf
 =CHAR(83)&CHAR(45)&LEFT(B11,LEN(B11)-9)&CHAR(45)&UPPER(MID(B11,4,LEN(B11)-8))&CHAR(32)&D11&E11

173d02210.pdf = S-173-D022 Description.pdf =CHAR(83)&CHAR(45)&LEFT(B12,LEN(B12)-10)&CHAR(45)&UPPER(MID(B12,4,LEN(B12)-9))&CHAR(32)&D12&E12

173d170c141.pdf = SD-170-C14 Description.pdf
 =CHAR(83)&CHAR(68)&CHAR(45)&UPPER(MID(B13,5,LEN(B13)-12))&CHAR(45)&UPPER(MID(B13,8,LEN(B13)-12)&CHAR(32)&D13&E13)

REF-173d0221.pdf = REF-173-D022 Description.pdf
 =LEFT(B14,LEN(B14)-9)&CHAR(45)&UPPER(MID(B14,8,LEN(B14)-12))&CHAR(32)&D14&E14

REF-173d02210.pdf = REF-173-D022 Description.pdf
 =LEFT(B15,LEN(B15)-10)&CHAR(45)&UPPER(MID(B15,8,LEN(B15)-13))&CHAR(32)&D15&E15

I am having trouble linking them together to get it to apply the right formula based on the length of the cell.

Notes: I am using CHAR(83)&CHAR(45) instead of "S-" because VBA wasn't liking the text. I will update the "B12" cell tag with " & aCell & " once everything is working smoothly.

My vba code looks like:

.Range("C2:C" & LastRow).Formula = "=IF(LEN(" & aCell & ")=12,CHAR(83)&CHAR(45)&LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",4,LEN(" & aCell & ")-8))&CHAR(32)&" & dCell & "&" & eCell & ",LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",8,LEN(" & aCell & ")-12))&CHAR(32)&" & dCell & "&" & eCell & ")"

Body:
This seems to work for the first three example formula.

I'll leave it to you to translate the remaining 2 formula to VBA, which you should be able to do following my examples :)

Option Explicit

Sub foo()
Dim rng As Range, aCell As Range
Dim val As String
Set rng = Range("B1:B5")  '## Modify the input range as needed.
For Each aCell In rng.Cells
    Select Case Len(aCell)
        Case 12
            val = "S-" & Left(aCell, Len(aCell) - 9) & "-" & Mid(aCell, 4, Len(aCell) - 8)
        Case 13
            val = "S-" & Left(aCell, Len(aCell) - 10) & "-" & Mid(aCell, 4, Len(aCell) - 9)
        Case 15
            val = "SD-" & Mid(aCell, 5, Len(aCell) - 12) & "-" & Mid(aCell, 8, Len(aCell) - 12)
        Case 16
            val = "REF-" '## Modify as needed
        Case 17
            val = "REF-" '## Modify as needed
        Case Else
            'maybe warn the user this input is not anticipated...
            MsgBox "Unsupported length!", vbInformation
    End Select
    val = UCase(val)
    '## Append the values from column D,E:
    val = val & " " & aCell.Offset(, 2) & aCell.Offset(, 3)
    '## Write out to the workbook in column F, modify the "5" to specify a different location if needed e.g., "-1" would put it in column A, "0" would put in same column B, etc.
    aCell.Offset(, 4).Value = val
Next
End Sub


问:
If state is immutable, is the whole state replaced on any change?
If state is immutable wouldn't the whole state need to be replaced on any change? Otherwise, you're mutating the state. Are top-level keys held as separate immutable objects?

By definition wouldn't any change need to replace the whole thing? How is this handled by Redux? Wouldn't replacing the full state break PureComponents?

Thanks for any clarification.

答:
Redux never says that the state is immutable. It says the reducers which constitute the store or state of the application should be immutable and should be pure functions.

Yes the top level keys are seperately considered to be immutable.

So on any change or in Redux terms any action is done we trigger a reducer on each action which causes the state change.


问:
How to convert float to varchar in SQL Server
I have a float column with numbers of different length and I'm trying to convert them to varchar.

Some values exceed bigint max size, so I can't do something like this

```<code>cast(cast(float_field as bigint) as varchar(100))
</code>```

I've tried using decimal, but numbers aren't of the same size, so this doesn't help too

```<code>CONVERT(varchar(100), Cast(float_field as decimal(38, 0)))
</code>```

Any help is appreciated.

UPDATE:

Sample value is 2.2000012095022E+26.

答:
Try this one, should work:</p>

```<code>cast((convert(bigint,b.tax_id)) as varchar(20))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a float column with numbers of different length and I'm trying to convert them to varchar.

Some values exceed bigint max size, so I can't do something like this

cast(cast(float_field as bigint) as varchar(100))

I've tried using decimal, but numbers aren't of the same size, so this doesn't help too

CONVERT(varchar(100), Cast(float_field as decimal(38, 0)))

Any help is appreciated.

UPDATE:

Sample value is 2.2000012095022E+26.

Body:
Try this one, should work:

cast((convert(bigint,b.tax_id)) as varchar(20))


问:
Use existing PEM private key to sign data on iOS
I need to import an existing key into my app to use it with RSA encryption, I don't want to generate a new key.
I've read the apple documentation http://developer.apple.com/library/ios/#documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html
But it doesn't seem to provide a way to import an existing PEM private key, it talks about creating them, but not about how to use an existing key.

Is this actually possible? Are there any API or Lib to do this? I don't need this for appstore, so don't be shy with responses if they are against the appstore rules.

答:
Ok I ended up using a version of OpenSSL compiled for iPhone:
https://github.com/x2on/OpenSSL-for-iPhone</p>


问:
Changing routes after successfully saga
I'm trying to figure out what the proper way to go about this is.

Lets say we have a store of items. These items can be edited, deleted and created. When editing or adding an item the route changes to /item/add or /item/edit/{id}.

After an item has been added or edited successfully by saga we want to send them back to the base route. What's the proper way to go about this?

I've seen two ways, one where you inject a history object into a  and then include the history object in the saga's as well. Another to keep a "status" ("", "failed", "success") in the item store using  in the components and resetting that status when the component unmounts since add and edit both need to use the status.

Which is the proper way to go about this problem though?

答:
In the past, I've used react-router v3 with react-router-redux integration to dispatch actions that change the route.

React router 4 has a react-router-redux package, which is still in alpha stage. Although it's alpha, this functionality works fine for me, but you should check it for yourself.

In your saga, you can use the put effect to dispatch the action:

```<code>import { push } from 'react-router-redux';

yield put(push('/route'));
</code>```

Title: Changing routes after successfully saga

Body:
In the past, I've used react-router v3 with react-router-redux integration to dispatch actions that change the route.

React router 4 has a react-router-redux package, which is still in alpha stage. Although it's alpha, this functionality works fine for me, but you should check it for yourself.

In your saga, you can use the put effect to dispatch the action:

import { push } from 'react-router-redux';

yield put(push('/route'));


问:
Get string from a list contain Unicode in JavaScript
I have a list of Unicode values [65, 66, 67] and I want the corresponding string "ABC". I looked into the documentation and found the function String.fromCharCode()that does what I need to do. The only problem is that the arguments needs to be a sequence of numbers.

So if I use String.fromCharCode([65, 66, 67]) it gives me " ".

Is there a way that allows the list to be treated as a sequence for a function?

答:
/* You can map over the list and the value you need will be output to anoter list */
var charCodes = [65, 66, 67],
    stringsFromCharCodes = charCodes.map(item => String.fromCharCode(item));

console.log('new list: ', stringsFromCharCodes);```