问:
Trim string fetched from a Google Spreadsheet range and return the largest value
I am building a small script and, on it, I need to "read" the largest value in a range of cells. The cells look like this: "a-10", "a-3", "a-4" and so on, but their real values are 10, 3 and 4 respectively. I cannot remove the "a-" from the cells.

What I have so far is this:

Code:

function getLargestValue() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=['Sheet1','Sheet2','Sheet3'];
  var values=[];
  for(var i=0;i<sheets.length;i++)
  {
    var sht=ss.getSheetByName(sheets[i]);
    var rng=sht.getDataRange();
    var rngA=rng.getValues();
    for(var j=1;j<rngA.length;j++)
    {
      rngA[j][0] = substring(2, rngA[j][0]);
      values.push(rngA[j][0]);
    }
  }
  values.sort(function(a, b) {return a - b;});
  var max = values[values.length-1];
  SpreadsheetApp.getUi().alert('The max is ' + max); //Just checking to be sure it works
  return max;
  // must show the largest value on "Max" sheet
}```

Link to spreadsheet:

https://docs.google.com/spreadsheets/d/16WrsztYlOV7qDOMBqGYU8az26Bw9NoqdQ4Imk_hZM90/edit?usp=sharing

I still need to trim the strings and insert the largest value in a different sheet. How could I do that?

Thank you.

答:
Before your sort function I would try something like

```<code>// Use a regex to get any numbers from the cell value and make
// a new array
var numbers = values.map(function(el) { return /[0-9]+/.exec(el) }
</code>```

and then at the end before returning

```<code>// Put the 'max' value in 'MAX' sheet in cell 'A1'
ss.getSheetByName('MAX').getRange("A1").setValue(max)
</code>```

Side note: You can also get a maximum number like this:

```<code>var max = Math.max(1,2,3,4,5)
</code>```

OR

```<code>var max = Math.max.apply(null,ARRAY_OF_NUMBERS)
</code>```

Body:
I am building a small script and, on it, I need to "read" the largest value in a range of cells. The cells look like this: "a-10", "a-3", "a-4" and so on, but their real values are 10, 3 and 4 respectively. I cannot remove the "a-" from the cells.

What I have so far is this:

Code:

function getLargestValue() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=['Sheet1','Sheet2','Sheet3'];
  var values=[];
  for(var i=0;i<sheets.length;i++)
  {
    var sht=ss.getSheetByName(sheets[i]);
    var rng=sht.getDataRange();
    var rngA=rng.getValues();
    for(var j=1;j<rngA.length;j++)
    {
      rngA[j][0] = substring(2, rngA[j][0]);
      values.push(rngA[j][0]);
    }
  }
  values.sort(function(a, b) {return a - b;});
  var max = values[values.length-1];
  SpreadsheetApp.getUi().alert('The max is ' + max); //Just checking to be sure it works
  return max;
  // must show the largest value on "Max" sheet
}

Link to spreadsheet:

https://docs.google.com/spreadsheets/d/16WrsztYlOV7qDOMBqGYU8az26Bw9NoqdQ4Imk_hZM90/edit?usp=sharing

I still need to trim the strings and insert the largest value in a different sheet. How could I do that?

Thank you.

Body:
Before your sort function I would try something like

// Use a regex to get any numbers from the cell value and make
// a new array
var numbers = values.map(function(el) { return /[0-9]+/.exec(el) }

and then at the end before returning

// Put the 'max' value in 'MAX' sheet in cell 'A1'
ss.getSheetByName('MAX').getRange("A1").setValue(max)

Side note: You can also get a maximum number like this:

var max = Math.max(1,2,3,4,5)

OR

var max = Math.max.apply(null,ARRAY_OF_NUMBERS)


来源: stackexchange

问:
Auto Populate CTE in SQL Server
How can I auto populate a CTE to contain the first day of every month
Eg:

1-1-2010

2-1-2010

3-1-2010

4-1-2010

and so on. I looking for a query to do so, rather than using UNION operator.

答:
Have a look at something like

```<code>DECLARE @StartDate DATETIME,
        @EndDate DATETIME

SELECT  @StartDate = '01 Jan 2010',
        @EndDate = '01 Jan 2011'

;WITH Dates AS (
        SELECT  @StartDate StartOfMonth
        UNION ALL
        SELECT DATEADD(month,1,StartOfMonth) StartOfMonth
        FROM    Dates
        WHERE   DATEADD(month,1,StartOfMonth) <= @EndDate
)
SELECT  *
FROM    Dates
</code>```

OUTPUT

```<code>StartOfMonth
-----------------------
2010-01-01 00:00:00.000
2010-02-01 00:00:00.000
2010-03-01 00:00:00.000
2010-04-01 00:00:00.000
2010-05-01 00:00:00.000
2010-06-01 00:00:00.000
2010-07-01 00:00:00.000
2010-08-01 00:00:00.000
2010-09-01 00:00:00.000
2010-10-01 00:00:00.000
2010-11-01 00:00:00.000
2010-12-01 00:00:00.000
2011-01-01 00:00:00.000
</code>```

EDIT

With column name supplied

```<code>DECLARE @StartDate DATETIME,
        @EndDate DATETIME

SELECT  @StartDate = '01 Jan 2010',
        @EndDate = '01 Jan 2011'

;WITH Dates (dt) AS (
        SELECT  @StartDate dt
        UNION ALL
        SELECT DATEADD(month,1,dt) dt
        FROM    Dates
        WHERE   DATEADD(month,1,dt) <= @EndDate
)
SELECT  *
FROM    Dates
</code>```

ContentLicense: CC BY-SA 2.5

Title: Auto Populate CTE in SQL Server

Body:
Have a look at something like

DECLARE @StartDate DATETIME,
        @EndDate DATETIME

SELECT  @StartDate = '01 Jan 2010',
        @EndDate = '01 Jan 2011'

;WITH Dates AS (
        SELECT  @StartDate StartOfMonth
        UNION ALL
        SELECT DATEADD(month,1,StartOfMonth) StartOfMonth
        FROM    Dates
        WHERE   DATEADD(month,1,StartOfMonth) <= @EndDate
)
SELECT  *
FROM    Dates

OUTPUT

StartOfMonth
-----------------------
2010-01-01 00:00:00.000
2010-02-01 00:00:00.000
2010-03-01 00:00:00.000
2010-04-01 00:00:00.000
2010-05-01 00:00:00.000
2010-06-01 00:00:00.000
2010-07-01 00:00:00.000
2010-08-01 00:00:00.000
2010-09-01 00:00:00.000
2010-10-01 00:00:00.000
2010-11-01 00:00:00.000
2010-12-01 00:00:00.000
2011-01-01 00:00:00.000

EDIT

With column name supplied

DECLARE @StartDate DATETIME,
        @EndDate DATETIME

SELECT  @StartDate = '01 Jan 2010',
        @EndDate = '01 Jan 2011'

;WITH Dates (dt) AS (
        SELECT  @StartDate dt
        UNION ALL
        SELECT DATEADD(month,1,dt) dt
        FROM    Dates
        WHERE   DATEADD(month,1,dt) <= @EndDate
)
SELECT  *
FROM    Dates


问:
Transform PySpark DataFrame into a nested structure
I'm learning PySpark. I load a CSV file into a Spark DataFrame. After that I do some data transformation. Finally, I want some set of columns to be put into a nested structure and then save it in JSON format.

This is the sample code that I have:

```<code>df = spark.createDataFrame([("Bilbo Baggins",  50), ("Gandalf", 32), ("Thorin", 19),
                                ("Balin", 18), ("Kili", 37),("Dwalin", 19), ("Oin", 46),
                                ("Gloin", 28), ("Fili", 22)], ["name", "age"])

mod_df = df.select(struct([col(x) for x in df.columns[:]]).alias("PersonalDetails"))
</code>```

When I save this as a JSON file, it looks like:

```<code>{
        "PersonalDetails" :
                {
                        "name" : "Balin",
                        "age" : 18
                }
}
{
        "PersonalDetails" :
                {
                        "name" : "Gloin",
                        "age" : 28
                }
}
</code>```

As you can see, they come up as separate documents. However I want them to come up in a single document with array format, like:

```<code>{
        "PersonalDetails" :[
                {
                        "name" : "Balin",
                        "age" : 18
                },
                {
                        "name" : "Gloin",
                        "age" : 28
                }
        ]
}
</code>```

Can you guys help me in where I'm doing it wrong? Thank you :)

答:
from pyspark.sql import functions as F

mod_df = df.select(
    F.struct(df.columns).alias('PersonalDetails')
).select(
    F.collect_list('PersonalDetails').alias('PersonalDetails')
)
```

ContentLicense: CC BY-SA 3.0

Body:
I'm learning PySpark. I load a CSV file into a Spark DataFrame. After that I do some data transformation. Finally, I want some set of columns to be put into a nested structure and then save it in JSON format.

This is the sample code that I have:

df = spark.createDataFrame([("Bilbo Baggins",  50), ("Gandalf", 32), ("Thorin", 19),
                                ("Balin", 18), ("Kili", 37),("Dwalin", 19), ("Oin", 46),
                                ("Gloin", 28), ("Fili", 22)], ["name", "age"])

mod_df = df.select(struct([col(x) for x in df.columns[:]]).alias("PersonalDetails"))

When I save this as a JSON file, it looks like:

{
        "PersonalDetails" :
                {
                        "name" : "Balin",
                        "age" : 18
                }
}
{
        "PersonalDetails" :
                {
                        "name" : "Gloin",
                        "age" : 28
                }
}

As you can see, they come up as separate documents. However I want them to come up in a single document with array format, like:

{
        "PersonalDetails" :[
                {
                        "name" : "Balin",
                        "age" : 18
                },
                {
                        "name" : "Gloin",
                        "age" : 28
                }
        ]
}

Can you guys help me in where I'm doing it wrong? Thank you :)

ContentLicense: CC BY-SA 4.0


问:
Why I cannot render data correctly although I can receive data (angularjs with flask-restapi/jinja2)
I tried to debug around 2 hours, but no luck.

This is my error:

jinja2.exceptions.UndefinedError
  jinja2.exceptions.UndefinedError: 'item' is undefined

I can receive the data ($scope.questions) correctly.

My index.html:

```<code><html>

<head>
</head>

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

    <div ng-app="myApp" ng-controller="myCtrl">
        <div ng-repeat="item in questions">
            {{item.question}}
        </div>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope, $http) {
            $http({
                method: "GET",
                url: "http://127.0.0.1:5000/questions"
            }).then(function mySuccess(response) {
                $scope.questions = response.data;
            }, function myError(response) {
                $scope.myWelcome = response.statusText;
            });
        });
    </script>
</body>

</html>
</code>```

My server side:

```<code>import os

from flask import Flask, request, render_template, Response
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

question_id_serial = 2
questions = {
    1: {
        'id': 1,
        'question': 'Is this hard?',
    },
    2: {
        'id': 2,
        'question': 'Who is going to win the SuperBowl in 2017?',
    }
}

answer_id_serial = 6
answers = {
    1: {
        'id': 1,
        'question_id': 1,
        'answer': 'Yes',
        'count': 0
    },
    2: {
        'id': 2,
        'question_id': 1,
        'answer': 'No',
        'count': 0
    },
    3: {
        'id': 3,
        'question_id': 2,
        'answer': 'Eagles',
        'count': 0
    },
    4: {
        'id': 4,
        'question_id': 2,
        'answer': 'Patriots',
        'count': 0
    },
    5: {
        'id': 5,
        'question_id': 2,
        'answer': 'Seahawks',
        'count': 0
    },
    6: {
        'id': 6,
        'question_id': 2,
        'answer': 'Broncos'
    }
}

class Answer(Resource):
    def get(self, answer_id):
        return answers[answer_id]

    def put(self, answer_id):
        answer = answers[answer_id]
        data = request.get_json()
        values = {k: data.get(k, v) for k, v in answer.items()}
        answers[answer_id].update(values)
        return values

    def delete(self, answer_id):
        values = answers[answer_id]
        del answers[answer_id]
        return values

class Answers(Resource):
    def get(self):
        return answers.values()

    def post(self):
        global answer_id_serial
        answer_id_serial += 1
        data = request.get_json()
        values = {
            'id': answer_id_serial,
            'answer': data['answer'],
            'count': data.get('count', 0),
            'question_id': data['question_id']
        }

        answers[answer_id_serial] = values
        return values

class Question(Resource):
    def get(self, question_id):
        data = questions[question_id].copy()
        data['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return data

    def put(self, question_id):
        question = questions[question_id]
        data = request.get_json()
        data.pop('answers', [])
        values = {k: data.get(k, v) for k, v in question.items()}
        questions[question_id].update(values)
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

    def delete(self, question_id):
        values = questions[question_id]
        del questions[question_id]
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

class Questions(Resource):
    def get(self):
        output = []
        for question in  questions.values():
            question = question.copy()
            question['answers'] = [ans for ans in answers.values() if ans['question_id'] == question['id']]
            output.append(question)
        return output

    def post(self):
        global question_id_serial
        question_id_serial += 1
        data = request.get_json()
        values = {
            'id': question_id_serial,
            'question': data['question']
        }
        questions[question_id_serial] = values
        return values

api.add_resource(Questions, '/questions')
api.add_resource(Question,  '/questions/<int:question_id>')
api.add_resource(Answers,   '/answers')
api.add_resource(Answer,    '/answers/<int:answer_id>')

@app.route('/')
def show_page():
    return render_template('index.html')

@app.route('/assets/<path:path>')
def get_resource(path):
    mimetypes = {
        '.css': 'text/css',
        '.html': 'text/html',
        '.js': 'application/javascript'
    }

    content = open(path).read()
    return Response(content, mimetype=mimetypes[os.path.splitext(path)[1]])

if __name__ == '__main__':
    app.run(debug=True)
</code>```

答:
Is that html from the render_template('index.html')?

If that so, you can't render the template with Flask and then try to render it again with Angular.

Basically your ng-repeat is not working, Flask can't recognize {{ item }}, hence the error.

Body:
I tried to debug around 2 hours, but no luck.

This is my error:

jinja2.exceptions.UndefinedError
  jinja2.exceptions.UndefinedError: 'item' is undefined

I can receive the data ($scope.questions) correctly.

My index.html:

            {{item.question}}

My server side:

import os

from flask import Flask, request, render_template, Response
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

question_id_serial = 2
questions = {
    1: {
        'id': 1,
        'question': 'Is this hard?',
    },
    2: {
        'id': 2,
        'question': 'Who is going to win the SuperBowl in 2017?',
    }
}

answer_id_serial = 6
answers = {
    1: {
        'id': 1,
        'question_id': 1,
        'answer': 'Yes',
        'count': 0
    },
    2: {
        'id': 2,
        'question_id': 1,
        'answer': 'No',
        'count': 0
    },
    3: {
        'id': 3,
        'question_id': 2,
        'answer': 'Eagles',
        'count': 0
    },
    4: {
        'id': 4,
        'question_id': 2,
        'answer': 'Patriots',
        'count': 0
    },
    5: {
        'id': 5,
        'question_id': 2,
        'answer': 'Seahawks',
        'count': 0
    },
    6: {
        'id': 6,
        'question_id': 2,
        'answer': 'Broncos'
    }
}

class Answer(Resource):
    def get(self, answer_id):
        return answers[answer_id]

    def put(self, answer_id):
        answer = answers[answer_id]
        data = request.get_json()
        values = {k: data.get(k, v) for k, v in answer.items()}
        answers[answer_id].update(values)
        return values

    def delete(self, answer_id):
        values = answers[answer_id]
        del answers[answer_id]
        return values

class Answers(Resource):
    def get(self):
        return answers.values()

    def post(self):
        global answer_id_serial
        answer_id_serial += 1
        data = request.get_json()
        values = {
            'id': answer_id_serial,
            'answer': data['answer'],
            'count': data.get('count', 0),
            'question_id': data['question_id']
        }

        answers[answer_id_serial] = values
        return values

class Question(Resource):
    def get(self, question_id):
        data = questions[question_id].copy()
        data['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return data

    def put(self, question_id):
        question = questions[question_id]
        data = request.get_json()
        data.pop('answers', [])
        values = {k: data.get(k, v) for k, v in question.items()}
        questions[question_id].update(values)
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

    def delete(self, question_id):
        values = questions[question_id]
        del questions[question_id]
        values['answers'] = [ans for ans in answers.values() if ans['question_id'] == question_id]
        return values

class Questions(Resource):
    def get(self):
        output = []
        for question in  questions.values():
            question = question.copy()
            question['answers'] = [ans for ans in answers.values() if ans['question_id'] == question['id']]
            output.append(question)
        return output

    def post(self):
        global question_id_serial
        question_id_serial += 1
        data = request.get_json()
        values = {
            'id': question_id_serial,
            'question': data['question']
        }
        questions[question_id_serial] = values
        return values

api.add_resource(Questions, '/questions')
api.add_resource(Question,  '/questions/<int:question_id>')
api.add_resource(Answers,   '/answers')
api.add_resource(Answer,    '/answers/<int:answer_id>')

@app.route('/')
def show_page():
    return render_template('index.html')

@app.route('/assets/<path:path>')
def get_resource(path):
    mimetypes = {
        '.css': 'text/css',
        '.html': 'text/html',
        '.js': 'application/javascript'
    }

    content = open(path).read()
    return Response(content, mimetype=mimetypes[os.path.splitext(path)[1]])

if __name__ == '__main__':
    app.run(debug=True)


问:
Beginner Python Objective Specific Explanation
```<code>A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]

x = 0
for i in range(2):
    x = x + A[i][i]
    print(x)
print(x)
</code>```

The answer/output is:

```<code>1,3,3
</code>```

How does that happen? Explain everything in detail

答:
when you say

```<code>A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]
</code>```

A is a list of lists. So,

A[0] gives you [1,2,3]
  A[1] gives you [2,2,3]

A[0][0] is nothing but the 0th index of [1,2,3] which is 1.

and similarly, A[1][1] is the 1st index is [2,2,3] which is 2(the 2nd 2)

Now going back the program,

range(2) returns a list from 0 to 2, not including 2, so thats

```<code>[0,1]
</code>```

so your looping through your program twice with i value being 0 and 1.

For the first line in the loop,

```<code>x = x + A[i][i]
</code>```

becomes

```<code>x = 0 + A[0][0]
</code>```

which is

```<code>x = 0 + 1
</code>```

That explains your first print.

When you enter the loop again, you get this :

x = 1 + A[1][1] (because i is 1 and x was set to 1 in the previous loop.

which evaluates to

```<code>x = 1 + 2
</code>```

Now the value of x is 3 and that explains your 2nd print statement.

The print outside the loop prints the current value of x, which is 3 and
thats why you get

```<code>1,3,3
</code>```

Body:
A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]

x = 0
for i in range(2):
    x = x + A[i][i]
    print(x)
print(x)

The answer/output is:

1,3,3

How does that happen? Explain everything in detail

Body:
when you say

A = [ [1, 1, 2], [2, 2, 3], [3, 3, 4] ]

A is a list of lists. So,

A[0] gives you [1,2,3]
  A[1] gives you [2,2,3]

A[0][0] is nothing but the 0th index of [1,2,3] which is 1.

and similarly, A[1][1] is the 1st index is [2,2,3] which is 2(the 2nd 2)

Now going back the program,

range(2) returns a list from 0 to 2, not including 2, so thats

[0,1]

so your looping through your program twice with i value being 0 and 1.

For the first line in the loop,

x = x + A[i][i]

becomes

x = 0 + A[0][0]

which is

x = 0 + 1

That explains your first print.

When you enter the loop again, you get this :

x = 1 + A[1][1] (because i is 1 and x was set to 1 in the previous loop.

which evaluates to

x = 1 + 2

Now the value of x is 3 and that explains your 2nd print statement.

The print outside the loop prints the current value of x, which is 3 and
thats why you get

1,3,3


问:
Access-Control-Allow-Origin: * in tomcat
I want to set a default http header in my tomcat container -

Access-Control-Allow-Origin: *

From various different links on stackoverslow and from google, most have pointed to a resource. This again says same on how to do it. I have replicated the same, but still the header is not shown.
This is what I have done:
1) Copied cors.jar file in /lib folder of tomcat
2) Inserted this text in web.xml

```<code><filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
     <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
     <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
     <param-name>cors.supportedHeaders</param-name>
        <param-value>Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposedHeaders</param-name>
        <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

It doesn't work and I am helpless. My tomcat version is -6.0.6. Please help.

答:
Try this.

1.write a custom filter

```<code>    package com.dtd.util;

    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    public class CORSFilter implements Filter {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.addHeader("Access-Control-Allow-Origin", "*");
            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
</code>```

2.add to web.xml

```<code><filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.dtd.util.CORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>
</code>```

Body:
I want to set a default http header in my tomcat container -

Access-Control-Allow-Origin: *

From various different links on stackoverslow and from google, most have pointed to a resource. This again says same on how to do it. I have replicated the same, but still the header is not shown.
This is what I have done:
1) Copied cors.jar file in /lib folder of tomcat
2) Inserted this text in web.xml

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
     <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
     <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
     <param-name>cors.supportedHeaders</param-name>
        <param-value>Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposedHeaders</param-name>
        <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

It doesn't work and I am helpless. My tomcat version is -6.0.6. Please help.

Body:
Try this.

1.write a custom filter

    package com.dtd.util;

    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    public class CORSFilter implements Filter {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.addHeader("Access-Control-Allow-Origin", "*");
            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    }

2.add to web.xml

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.dtd.util.CORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>


问:
why does an array with a property cause an undefined error in JS
This syntax works fine:

```<code>var foo = [];
foo[0] = "do";
foo[1] = "re";
</code>```

I'm trying to do the same using properties, like so.

```<code>var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";
</code>```

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

```<code>foo[i] = i
</code>```

but when using an array element with a property, like

```<code>foo[i].note = i
</code>```

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?

答:
You can add object dynamically but only one level at a time.
Hence when you say foo[1] = 're' you are dynamically creating slot 1 and assigning it the value of 're'. But foo[1].note = 're' is trying to create slot 1 and a property note that does not work. You could do foo[1] = {note: 're'};that will create slot 1 dynamically and separately an object to assign to it.

Body:
This syntax works fine:

var foo = [];
foo[0] = "do";
foo[1] = "re";

I'm trying to do the same using properties, like so.

var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

foo[i] = i

but when using an array element with a property, like

foo[i].note = i

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?


问:
using spring boot profiles with liquibase changeset context attribute to manage changset scope
I am trying to do a proof of concept application with spring boot and liquibase. I basically want to create a spring boot app that can manage liquibase changesets by utilizing the changeset attribute called context, so that changesets with no context can be applied to any spring boot profile, whereas changesets with specific context (e.g context="dev" ) will only be applied if spring boot profiles of that type, is active (e.g spring.profiles.active=dev).

In my app, i have the following spring profiles -> dev, prod (each specified correctly in the application yaml file with the relavant profile db credentials also specified under the profile). What do I need to do to make this work. below is my application.yaml

```<code>spring:
  application:
    name: liquibase-spring-jpa-postgres-example
liquibase:
  change-log: db.changelog/db.changelog-master.xml

spring:
  profiles: dev
  datasource:
    url: jdbc:postgresql://localhost:5432/dev
    username: postgres
    password: password
    driver-class-name: org.postgresql.Driver

spring:
  profiles: ci
  datasource:
      url: jdbc:postgresql://localhost:5432/ci
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver

spring:
  profiles: qa
  datasource:
      url: jdbc:postgresql://localhost:5432/qa
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver

spring:
  profiles: production
  datasource:
      url: jdbc:postgresql://localhost:5432/prod
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver
</code>```

and below is the current databaseChangeLog file (the second change set shouldn't run if my spring profile is prod).

```<code><changeSet id="20161016_my_first_change" author="fike" context="dev, qa, ci, production">
    <sql>
        CREATE TABLE customer
        (
        id BIGSERIAL PRIMARY KEY,
        firstname character varying NOT NULL,
        lastname character varying NOT NULL
        );
    </sql>
    <rollback>
        drop table customer;
    </rollback>
</changeSet>

<changeSet id="20161016_my_first_change2" author="krudland" context="dev">
    <sql>
        insert into customer (firstname, lastname) values ('Franklin','Ike');
    </sql>
    <rollback>
        delete from customer where firstname = 'Franklin' and lastname = 'Ike';
    </rollback>
</changeSet>
</code>```

I basically need to be able to manage my liquibase context, using my spring profile. Is this possible?

答:
You need to define 'liquibase.contexts' property into your yaml file. Something like below.

```<code>spring:
  profiles: dev
  datasource:
    url: jdbc:postgresql://localhost:5432/dev
    username: postgres
    password: password
    driver-class-name: org.postgresql.Driver
liquibase:
   contexts: dev
</code>```

After adding this the below change set will only execute when your local profile is 'dev' (i.e. spring-boot:run -Dspring.profiles.active=dev)

```<code><changeSet id="20161016_my_first_change2" author="krudland" context="dev">
    <sql>
        insert into customer (firstname, lastname) values ('Franklin','Ike');
    </sql>
    <rollback>
        delete from customer where firstname = 'Franklin' and lastname = 'Ike';
    </rollback>
</changeSet>
</code>```

Body:
I am trying to do a proof of concept application with spring boot and liquibase. I basically want to create a spring boot app that can manage liquibase changesets by utilizing the changeset attribute called context, so that changesets with no context can be applied to any spring boot profile, whereas changesets with specific context (e.g context="dev" ) will only be applied if spring boot profiles of that type, is active (e.g spring.profiles.active=dev).

In my app, i have the following spring profiles -> dev, prod (each specified correctly in the application yaml file with the relavant profile db credentials also specified under the profile). What do I need to do to make this work. below is my application.yaml

spring:
  application:
    name: liquibase-spring-jpa-postgres-example
liquibase:
  change-log: db.changelog/db.changelog-master.xml

spring:
  profiles: dev
  datasource:
    url: jdbc:postgresql://localhost:5432/dev
    username: postgres
    password: password
    driver-class-name: org.postgresql.Driver

spring:
  profiles: ci
  datasource:
      url: jdbc:postgresql://localhost:5432/ci
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver

spring:
  profiles: qa
  datasource:
      url: jdbc:postgresql://localhost:5432/qa
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver

spring:
  profiles: production
  datasource:
      url: jdbc:postgresql://localhost:5432/prod
      username: postgres
      password: password
      driver-class-name: org.postgresql.Driver

and below is the current databaseChangeLog file (the second change set shouldn't run if my spring profile is prod).

<changeSet id="20161016_my_first_change" author="fike" context="dev, qa, ci, production">
    <sql>
        CREATE TABLE customer
        (
        id BIGSERIAL PRIMARY KEY,
        firstname character varying NOT NULL,
        lastname character varying NOT NULL
        );
    </sql>
    <rollback>
        drop table customer;
    </rollback>
</changeSet>

<changeSet id="20161016_my_first_change2" author="krudland" context="dev">
    <sql>
        insert into customer (firstname, lastname) values ('Franklin','Ike');
    </sql>
    <rollback>
        delete from customer where firstname = 'Franklin' and lastname = 'Ike';
    </rollback>
</changeSet>

I basically need to be able to manage my liquibase context, using my spring profile. Is this possible?

Body:
You need to define 'liquibase.contexts' property into your yaml file. Something like below.

spring:
  profiles: dev
  datasource:
    url: jdbc:postgresql://localhost:5432/dev
    username: postgres
    password: password
    driver-class-name: org.postgresql.Driver
liquibase:
   contexts: dev

After adding this the below change set will only execute when your local profile is 'dev' (i.e. spring-boot:run -Dspring.profiles.active=dev)

<changeSet id="20161016_my_first_change2" author="krudland" context="dev">
    <sql>
        insert into customer (firstname, lastname) values ('Franklin','Ike');
    </sql>
    <rollback>
        delete from customer where firstname = 'Franklin' and lastname = 'Ike';
    </rollback>
</changeSet>


答:
you get undefined because foo[1] is undefined, it does not exists, doing something like this foo[1].note does not make sense because undefined is not an object

 var foo = [{
    note: "",
}];

foo[0].note = "do";

Object.assign(foo[1] = {}, { note: "re" });

console.log(foo[1].note);```

Object.assign copies the members of an object into another object, in the above code foo[1] was set to an object, before coping {note: "re"} to foo[1]

Title: why does an array with a property cause an undefined error in JS

Body:
you get undefined because foo[1] is undefined, it does not exists, doing something like this foo[1].note does not make sense because undefined is not an object

 var foo = [{
    note: "",
}];

foo[0].note = "do";

Object.assign(foo[1] = {}, { note: "re" });

console.log(foo[1].note);

Object.assign copies the members of an object into another object, in the above code foo[1] was set to an object, before coping {note: "re"} to foo[1]


问:
Breaking the callback chain - Node
I am wondering if it's possible to assign the value of callback to a variable. I recently ran into a problem with MongoClient's connect method, where I want to get the db object and pass it on to my class methods. Is there a way I can I assign hello world to var b.

```<code>function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  return str;
})

console.log(b) //undefined
</code>```

答:
As the event is async, you need to follow the async code flow. So The only way to "get the return" is inside your callback function, i.e.:

```<code>function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  // this executes async, when testCB finishes running
  console.log(str) // will print STR
  return str;
})
// this code executes BEFORE testCB finish running,
// so it is imposible to get the value of str here.
</code>```

If you want a more fluid code, you can try using promises with async and await which are available on node 7+

Title: Breaking the callback chain - Node

Body:
I am wondering if it's possible to assign the value of callback to a variable. I recently ran into a problem with MongoClient's connect method, where I want to get the db object and pass it on to my class methods. Is there a way I can I assign hello world to var b.

function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  return str;
})

console.log(b) //undefined

Body:
As the event is async, you need to follow the async code flow. So The only way to "get the return" is inside your callback function, i.e.:

function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  // this executes async, when testCB finishes running
  console.log(str) // will print STR
  return str;
})
// this code executes BEFORE testCB finish running,
// so it is imposible to get the value of str here.

If you want a more fluid code, you can try using promises with async and await which are available on node 7+


问:
Monitor Kafka using Opensource tools
Any Opensource tool to monitor confluent Kafka? Most of the opensource tools available are specific to Apache Kafka but not for Confluent Kafka.

we want to monitor atleast the connectors, streams and cluster health

答: You should be able to use kafka-monitor for monitoring your cluster's health as well as Burrow and KafkaOffsetMonitor for monitoring your consumer application lag. Also, you should definitely use something like jmxtrans for collecting your Kafka broker metrics. </p>

Title: Monitor Kafka using Opensource tools


问:
Using Safari web inspector to debug memory leak?
FYI, we are debugging our mobile hybrid app which was develop using angularJS 1.4.2 and ionic framework 1.2.4 with WKWebView.

The multiple snapshots below is to show the events before and after. Based on webkit memory debugging article, the snapshot will show the live JavaScript objects which has not yet been GC.

Snapshot 2 showing the default state of page A and controller A.

Snapshot 5 is still in the same page but after doing some calculation and generated a base64 string pdf from PDFTron to view it on UIWebview.

Snapshot 10 showing after exit page A and navigate to page C with controller C.

Comparison of snapshot 2 and snapshot 10, all the base64 string still remain there.

Questions:

Is it normal when the size of snapShot keep increasing without reduce, is it consider memory leak?

The snapshot size is representing all the live javascript objects only or it will show all the object that we visited whether it is live or not, just like some history objects in the app?

What is the different of snapshot size and snapshot live size?

AngularJS will help to destroy the scope when navigate to next controller, we also disable cache on ionic. So is these base64 string consider memory leak item also?

答:
Update

There was a new article released on the memory debugging. This article include a more detail steps and the procedure.

New memory debugging article

Answers

After going through few months of memory debugging on the apps, we have some addition finding on debugging the memory leaks.

The size of the snapshot will keep increasing as there may have some static object or variables when navigate between pages.

Like above, the snapshot size is represent the current active memory usage of the apps including the static objects, UI elements and other components that was active in this controller.

Instead of checking the snapshot size and snapshot live size, retained size and self size will have more information on the memory usage. Self size is the size of the current element while retained size is how much memory will be release after the current self element is destroyed.

The base64 string is consider memory leak item. Although proper scope destroy and variable clear is done in the controller side, but there are some leak because some addition services still referencing to this string. After cleaning up all the remaining referencing issue, the base64 string leak is gone now.

Memory debugging steps

Some suggestion here for those who might also want to use the memory debugging in the future.
Current steps for memory debugging:

Navigate from page A - page B, then from page B back to page A.

Do a snapshot.

Repeat step 1 and do another snapshot.

Compare the first snapshot with the second snapshot.

Repeat step 1 to step 4 if want to do another snapshot comparison.

*Remember always take the latest snapshot. Eg. use snapshot 5 and 6 instead of 1 and 2 because the earlier snapshot might have the chance to be GC and the result will not be accurate.

With this steps, it was better to find out and pin point the memory leaks section. Normally we will track the object, function and array count. If there were memory leaks, the number of count will be increase when comparing the snapshot. Some other memory leaks item will be the $$ inside the object count. This kind of object might cause memory leaks as the object is not in use anymore but is still reference by other parts of the application.


答:
It looks like you think that you are declaring an array of objects with a property note. You can't really do that in javascript, you can write it for future reference only as it is totally valid to override it with something completely different.

In your case foo[0] exists while foo[1] doesn't. You're trying to affect a value to an non existing property, hence the error.
When you do var foo = [{note:""}]; you actually have an array of length 1. You can access foo[0] but foo[1] is still undefined. You need to assign a value to it.

```<code>var foo = [{note: ""}]; // {note:""} is here for reference;
foo[0].note = "do"; // or foo[0] = {note: "do"};
foo[1] = {note: "re"};
</code>```

Body:
It looks like you think that you are declaring an array of objects with a property note. You can't really do that in javascript, you can write it for future reference only as it is totally valid to override it with something completely different.

In your case foo[0] exists while foo[1] doesn't. You're trying to affect a value to an non existing property, hence the error.
When you do var foo = [{note:""}]; you actually have an array of length 1. You can access foo[0] but foo[1] is still undefined. You need to assign a value to it.

var foo = [{note: ""}]; // {note:""} is here for reference;
foo[0].note = "do"; // or foo[0] = {note: "do"};
foo[1] = {note: "re"};


问:
Kendo ListView: switching to the edit template by selecting the desired item
I have this simple example illustrating the problem: http://dojo.telerik.com/AROMAZ

I want to select (click) an item to make it switch to its 'edit' template.
It works fine only if I click on the edited item's 'cancel' icon before selecting a new item.

If I select a new item without  manually deselecting the previous one, it stops working.

I don't what to rely nor have the 'cancel' button.

It should be easy.. Click the item you want to edit (to switch to its 'edit' template). Selecting one should deselect the previously selected item. i.e. edit one at at time.

I think the problem is I couldn't find a way to auto-select / un-edit an item (if there is any selected) before manually editing another one.

EDIT 1:

Placing this.cancel(); before this.edit(selected) doesn't work as expected.  Notice this code was commented out in the original dojo example.

When you select a new item, the previously selected item gets un-edited (this is fine). However, the newly selected item doesn't get edited (undesired behavior), and an exception is thrown (undesired behavior).

The exception is:

```<code>Uncaught TypeError: Cannot read property 'uid' of undefined
    at init.edit (kendo.all.js:53910)
    at init.change (VM1332 result:42)
    at init.trigger (kendo.all.js:124)
    at init.change (kendo.all.js:53707)
    at init.trigger (kendo.all.js:124)
    at init._notify (kendo.all.js:25836)
    at init.value (kendo.all.js:25811)
    at init._tap (kendo.all.js:25725)
    at init.d (jquery-1.12.4.min.js:2)
    at init.trigger (kendo.all.js:124)
</code>```

The addition of this.cancel(); is illustrated in this modified dojo: http://dojo.telerik.com/AROMAZ/7

Note: To see the exception, open the browser's Developer Tools (i.e. Shift+Ctr+I in Chrome)

EDIT 2:

Placing this.save(); before this.edit(selected) can throw exceptions too. Example: http://jsfiddle.net/horacioj/mkJTG/417/

答:
I think I got it working exactly as I want. See http://jsfiddle.net/horacioj/t45n0hdj/

It does a this.cancel(); before the this.edit().
If this.select(); fails (and therefore the .edit() would throw and exception), then it does the .select() searching the item by index (or id). This prevents the exception to happen.

A variable remembering the last item that was edited helps to prevent keeping an item edited if it was already selected (i.e. clicking the same item will toggle its state instead of keeping it in edit mode).

Basically:

```<code>var lastEditedIndex = -1;

$("#listView").kendoListView({
  ....
  ....
  change: function(e) {
    var index = this.select().index();
    this.cancel();
    var selected = this.select();
    if (selected.length === 1) {
      this.edit(selected);
      lastEditedIndex = index;
    } else {
      selectByIndex(index);
    }
  }

function selectByIndex(index) {
  if (lastEditedIndex === index) return;

  var listView = $('#listView').data('kendoListView');
  var itemWithID = listView.dataSource.at(index);
  listView.select(listView.element.children('[data-uid="' + itemWithID.uid + '"]').first());
  lastEditedIndex = index;
}
</code>```

Body:
I have this simple example illustrating the problem: http://dojo.telerik.com/AROMAZ

I want to select (click) an item to make it switch to its 'edit' template.
It works fine only if I click on the edited item's 'cancel' icon before selecting a new item.

If I select a new item without  manually deselecting the previous one, it stops working.

I don't what to rely nor have the 'cancel' button.

It should be easy.. Click the item you want to edit (to switch to its 'edit' template). Selecting one should deselect the previously selected item. i.e. edit one at at time.

I think the problem is I couldn't find a way to auto-select / un-edit an item (if there is any selected) before manually editing another one.

EDIT 1:

Placing this.cancel(); before this.edit(selected) doesn't work as expected.  Notice this code was commented out in the original dojo example.

When you select a new item, the previously selected item gets un-edited (this is fine). However, the newly selected item doesn't get edited (undesired behavior), and an exception is thrown (undesired behavior).

The exception is:

Uncaught TypeError: Cannot read property 'uid' of undefined
    at init.edit (kendo.all.js:53910)
    at init.change (VM1332 result:42)
    at init.trigger (kendo.all.js:124)
    at init.change (kendo.all.js:53707)
    at init.trigger (kendo.all.js:124)
    at init._notify (kendo.all.js:25836)
    at init.value (kendo.all.js:25811)
    at init._tap (kendo.all.js:25725)
    at init.d (jquery-1.12.4.min.js:2)
    at init.trigger (kendo.all.js:124)

The addition of this.cancel(); is illustrated in this modified dojo: http://dojo.telerik.com/AROMAZ/7

Note: To see the exception, open the browser's Developer Tools (i.e. Shift+Ctr+I in Chrome)

EDIT 2:

Placing this.save(); before this.edit(selected) can throw exceptions too. Example: http://jsfiddle.net/horacioj/mkJTG/417/

Body:
I think I got it working exactly as I want. See http://jsfiddle.net/horacioj/t45n0hdj/

It does a this.cancel(); before the this.edit().
If this.select(); fails (and therefore the .edit() would throw and exception), then it does the .select() searching the item by index (or id). This prevents the exception to happen.

A variable remembering the last item that was edited helps to prevent keeping an item edited if it was already selected (i.e. clicking the same item will toggle its state instead of keeping it in edit mode).

Basically:

var lastEditedIndex = -1;

$("#listView").kendoListView({
  ....
  ....
  change: function(e) {
    var index = this.select().index();
    this.cancel();
    var selected = this.select();
    if (selected.length === 1) {
      this.edit(selected);
      lastEditedIndex = index;
    } else {
      selectByIndex(index);
    }
  }

function selectByIndex(index) {
  if (lastEditedIndex === index) return;

  var listView = $('#listView').data('kendoListView');
  var itemWithID = listView.dataSource.at(index);
  listView.select(listView.element.children('[data-uid="' + itemWithID.uid + '"]').first());
  lastEditedIndex = index;
}


问:
If else in bash script for shell command
I have written a bash script that does not show any errors. However I would like to add conditional block list if success then show email success else show error message in email as shown in the code below.

```<code>scp -i id_rsa -r testuser@1.1.1.:/data1/scp ~/data/scp/files
success >> ~/data/scp/files/log.txt 2>&1
if success
then
| mail -s "Download
Successfull" abc@test.com <<< "Files Successfully Downloaded"
else
 | mail -s "Error: Download Failed" abc@test.com <<< "Error File download
 Failed!"
 fi
</code>```

Here is the working script without If else block

```<code>#!/module/for/bash
 scp -i id_rsa -r test@1.1.1.1:/data1/scp ~/data/scp/files
 echo success! >> ~/data/scp/files/log.txt 2>&1 | mail -s "Download
 Successfull" abc@test.com <<< "Files Successfully
 Downloaded" | mail -s "Error: Download Failed" abc@test.com <<<
 "Error:file download Failed!"
</code>```

答:
@Korthrun has already posted several ways to accomplish what I think you're trying to do; I'll take a look at what's going wrong in your current script. You seem to be confused about a couple of basic elements of shell scripting: pipes (|) and testing for command success/failure.

Pipes are used to pass the output of one command into the input of another (and possibly then chain the output of the second command into the input of a third command, etc). But when you use a pipe string like this:

```<code>echo success! >> ~/data/scp/files/log.txt 2>&1 |
mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded" |
mail -s "Error: Download Failed" abc@test.com <<< "Error:file download Failed!"
</code>```

the pipes aren't actually doing anything. The first pipe tries to take the output of echo and feed it to the input of mail, but the >> in the echo command sends its output to a file instead, so no actual data is sent to the mail command. Which is probably good, because the <<< on the mail command tells it to ignore the regular input (from the pipe) and feed a string as input instead! Similarly, the second pipe tries to feed the output from the first mail command (there isn't any) to the last mail command, but again it's ignored due to another <<< input string. The correct way to do this is simply to remove the pipes, and run each command separately:

```<code>echo success! >> ~/data/scp/files/log.txt 2>&1
mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded"
mail -s "Error: Download Failed" abc@test.com <<< "Error:file download Failed!"
</code>```

This is also causing a problem in the other version of your script, where you use:

```<code>if success
then
| mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded"
</code>```

Here, there's no command before the pipe, so it doesn't make any sense at all (and you get a shell syntax error). Just remove the pipe.

Now, about success/failure testing: you seem to be using success as a command, but it isn't one. You can either use the command you want to check the success of directly as the if conditional:

```<code>if scp ...; then
    echo "It worked!"
else
    echo "It failed!"
fi
</code>```

or use the shell variable $? which returns the exit status of the last command (success=0, failure=anything else):

```<code>scp ...
if [ $? -eq 0 ]; then
    ...
</code>```

There's a subtlety here that's easy to miss: the thing after if is a command, but in the second form it appears to be a logical expression (testing whether $? is equal to 0). The secret is that [ is actually a command that evaluates logical expressions and then exits with success or failure depending on whether the expression was true or false. Do not mistake [ ] for some sort of parentheses or other grouping operator, that's not what's going on here!

BTW, the [[ ]] form that Korthrun used is very similar to [ ], but isn't supported by more basic shells. It does avoid some nasty syntax oddities with [ ], though, so if you're using bash it's a good way to go.

Also, note that $? gives the status of the last command executed, so it gets reset by every single command that executes. For example, this won't work:

```<code>scp ...
echo "scp's exit status was $?"
if [ $? -eq 0 ]; then      # Don't do this!!!!
</code>```

...because the if is then looking at the exit status of the echo command, not scp! If you need to do something like this, store the status in a variable:

```<code>scp ...
scpstatus=$?
echo "scp's exit status was $scpstatus"
if [ $scpstatus -eq 0 ]; then
</code>```

Body:
I have written a bash script that does not show any errors. However I would like to add conditional block list if success then show email success else show error message in email as shown in the code below.

scp -i id_rsa -r testuser@1.1.1.:/data1/scp ~/data/scp/files
success >> ~/data/scp/files/log.txt 2>&1
if success
then
| mail -s "Download
Successfull" abc@test.com <<< "Files Successfully Downloaded"
else
 | mail -s "Error: Download Failed" abc@test.com <<< "Error File download
 Failed!"
 fi

Here is the working script without If else block

#!/module/for/bash
 scp -i id_rsa -r test@1.1.1.1:/data1/scp ~/data/scp/files
 echo success! >> ~/data/scp/files/log.txt 2>&1 | mail -s "Download
 Successfull" abc@test.com <<< "Files Successfully
 Downloaded" | mail -s "Error: Download Failed" abc@test.com <<<
 "Error:file download Failed!"

Body:
@Korthrun has already posted several ways to accomplish what I think you're trying to do; I'll take a look at what's going wrong in your current script. You seem to be confused about a couple of basic elements of shell scripting: pipes (|) and testing for command success/failure.

Pipes are used to pass the output of one command into the input of another (and possibly then chain the output of the second command into the input of a third command, etc). But when you use a pipe string like this:

echo success! >> ~/data/scp/files/log.txt 2>&1 |
mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded" |
mail -s "Error: Download Failed" abc@test.com <<< "Error:file download Failed!"

the pipes aren't actually doing anything. The first pipe tries to take the output of echo and feed it to the input of mail, but the >> in the echo command sends its output to a file instead, so no actual data is sent to the mail command. Which is probably good, because the <<< on the mail command tells it to ignore the regular input (from the pipe) and feed a string as input instead! Similarly, the second pipe tries to feed the output from the first mail command (there isn't any) to the last mail command, but again it's ignored due to another <<< input string. The correct way to do this is simply to remove the pipes, and run each command separately:

echo success! >> ~/data/scp/files/log.txt 2>&1
mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded"
mail -s "Error: Download Failed" abc@test.com <<< "Error:file download Failed!"

This is also causing a problem in the other version of your script, where you use:

if success
then
| mail -s "Download Successfull" abc@test.com <<< "Files Successfully Downloaded"

Here, there's no command before the pipe, so it doesn't make any sense at all (and you get a shell syntax error). Just remove the pipe.

Now, about success/failure testing: you seem to be using success as a command, but it isn't one. You can either use the command you want to check the success of directly as the if conditional:

if scp ...; then
    echo "It worked!"
else
    echo "It failed!"
fi

or use the shell variable $? which returns the exit status of the last command (success=0, failure=anything else):

scp ...
if [ $? -eq 0 ]; then
    ...

There's a subtlety here that's easy to miss: the thing after if is a command, but in the second form it appears to be a logical expression (testing whether $? is equal to 0). The secret is that [ is actually a command that evaluates logical expressions and then exits with success or failure depending on whether the expression was true or false. Do not mistake [ ] for some sort of parentheses or other grouping operator, that's not what's going on here!

BTW, the [[ ]] form that Korthrun used is very similar to [ ], but isn't supported by more basic shells. It does avoid some nasty syntax oddities with [ ], though, so if you're using bash it's a good way to go.

Also, note that $? gives the status of the last command executed, so it gets reset by every single command that executes. For example, this won't work:

scp ...
echo "scp's exit status was $?"
if [ $? -eq 0 ]; then      # Don't do this!!!!

...because the if is then looking at the exit status of the echo command, not scp! If you need to do something like this, store the status in a variable:

scp ...
scpstatus=$?
echo "scp's exit status was $scpstatus"
if [ $scpstatus -eq 0 ]; then


问:
imagemagick in iphone
i m using imagemagick in my mac os x version 10.6.4 and all cmd is working well in my os .
but i want to use imagemagick framework in my iphone project i have added imagemagick framework in my xcode but where can I use command in the xcode project for changing the image ......
if some body can help me thanks in advance!!!!</p>

答:
You can find ImageMagick compiled for use in iPhone projects here: Latest ImageMagick.

You can't use the command line version on the iPhone though, so you'll want to use the MagickWand API.

Title: imagemagick in iphone


问:
How to setup two different Github accounts for two different repositories through SSH?
Before start I should say I have read a lot of topics (listed at the end of this post) about this issue but none is working for me or maybe I am missing something trivial in here.

At first I did clone the repository using HTTPS but then I switched to SSH following the docs from here. I did generate each of the SSH key and add them to the ssh-agent following the docs from here.

In a few lines (fake data used, ~ means my home directory) this is what I've done:

$ ssh-keygen -t rsa -b 4096 -C "first@gmail.com"
Enter a file in which to save the key (~/.ssh/id_rsa): [Press enter]
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

$ ssh-keygen -t rsa -b 4096 -C "second@gmail.com"
Enter a file in which to save the key (~/.ssh/id_rsa_second): [Press enter]
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

$ eval "$(ssh-agent -s)"
Agent pid 12697

$ ssh-add ~/.ssh/id_rsa
Identity added: ~/.ssh/id_rsa (~/.ssh/id_rsa)

$ ssh-add ~/.ssh/id_rsa_second
Identity added: ~/.ssh/id_rsa_second (~/.ssh/id_rsa_second)

$ ssh-add -l
4096 SHA256:gb+Gn4SqiyAP5ABUsmX6Xz11RHTSvDsWgEE5P2R2VTE ~/.ssh/id_rsa (RSA)
4096 SHA256:yxWMompayDNtYjv5y+FfJl7OpQ5Qu90kPgdXXvx6DRA ~/.ssh/id_rsa_second (RSA)
```

<p>The next step was create the <code>~/.ssh/config</code> file with the following content:</p>

```#first account
Host github.com-first
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

#second account
Host github.com-second
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_second
```

<p>I stopped here and give this a try by adding the SSH pub key for <code>id_rsa_second</code> to the repository where I want to use it (this doesn't need explanation). Next <code>git pull</code>:</p>

<pre class="lang-bash prettyprint-override"><code>$ git pull
Bad owner or permissions on /home/rperez/.ssh/config
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Then I tried the following:

Change the .git/config file to the following:

```<code>[remote "origin"]
    url = git@github.com-second:repo/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

But it didn't work and by this I mean I got exactly the same error as before.

What I am doing wrong? What I am missing?

What I have read:

How to properly configure ssh keys to multiple remote accounts involving github and bitbucket?

GitHub: Multiple account setup

Multiple github accounts on the same computer?

Quick Tip: How to Work with GitHub and Multiple Accounts

Can't get Multiple SSH keys to work for multiple github accounts

Multiple SSH Keys settings for different github account

Note: The title may seem confusing but it is correct because it is what I want to achieve I am just talking about one example but at the end I should be able to setup more than one account pointing to different repositories.

答:
The reason it's not working is because of this error:

Bad owner or permissions on /home/rperez/.ssh/config

Ssh is picky (for security reasons) about the permissions of sensitive files.

man ssh says:

```<code>~/.ssh/config
        This is the per-user configuration file. The file format and configuration
        options are described in ssh_config(5). Because of the potential for abuse,
        this file must have strict permissions: read/write for the user, and not
        writable by others.
</code>```

So check the file permissions of /home/rperez/.ssh/config. They should be 0644 (-rw-r--r-).

Body:
Before start I should say I have read a lot of topics (listed at the end of this post) about this issue but none is working for me or maybe I am missing something trivial in here.

At first I did clone the repository using HTTPS but then I switched to SSH following the docs from here. I did generate each of the SSH key and add them to the ssh-agent following the docs from here.

In a few lines (fake data used, ~ means my home directory) this is what I've done:

$ ssh-keygen -t rsa -b 4096 -C "first@gmail.com"
Enter a file in which to save the key (~/.ssh/id_rsa): [Press enter]
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

$ ssh-keygen -t rsa -b 4096 -C "second@gmail.com"
Enter a file in which to save the key (~/.ssh/id_rsa_second): [Press enter]
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

$ eval "$(ssh-agent -s)"
Agent pid 12697

$ ssh-add ~/.ssh/id_rsa
Identity added: ~/.ssh/id_rsa (~/.ssh/id_rsa)

$ ssh-add ~/.ssh/id_rsa_second
Identity added: ~/.ssh/id_rsa_second (~/.ssh/id_rsa_second)

$ ssh-add -l
4096 SHA256:gb+Gn4SqiyAP5ABUsmX6Xz11RHTSvDsWgEE5P2R2VTE ~/.ssh/id_rsa (RSA)
4096 SHA256:yxWMompayDNtYjv5y+FfJl7OpQ5Qu90kPgdXXvx6DRA ~/.ssh/id_rsa_second (RSA)

The next step was create the ~/.ssh/config file with the following content:

#first account
Host github.com-first
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa

#second account
Host github.com-second
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_second

I stopped here and give this a try by adding the SSH pub key for id_rsa_second to the repository where I want to use it (this doesn't need explanation). Next git pull:

$ git pull
Bad owner or permissions on /home/rperez/.ssh/config
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Then I tried the following:

Change the .git/config file to the following:

[remote "origin"]
    url = git@github.com-second:repo/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*

But it didn't work and by this I mean I got exactly the same error as before.

What I am doing wrong? What I am missing?

What I have read:

How to properly configure ssh keys to multiple remote accounts involving github and bitbucket?

GitHub: Multiple account setup

Multiple github accounts on the same computer?

Quick Tip: How to Work with GitHub and Multiple Accounts

Can't get Multiple SSH keys to work for multiple github accounts

Multiple SSH Keys settings for different github account

Note: The title may seem confusing but it is correct because it is what I want to achieve I am just talking about one example but at the end I should be able to setup more than one account pointing to different repositories.

Body:
The reason it's not working is because of this error:

Bad owner or permissions on /home/rperez/.ssh/config

Ssh is picky (for security reasons) about the permissions of sensitive files.

man ssh says:

~/.ssh/config
        This is the per-user configuration file. The file format and configuration
        options are described in ssh_config(5). Because of the potential for abuse,
        this file must have strict permissions: read/write for the user, and not
        writable by others.

So check the file permissions of /home/rperez/.ssh/config. They should be 0644 (-rw-r--r-).


问:
knockout select option not working
I am working on a project in which data is fetched from the api and i am trying to make a drop down list, using select binding . I have declared my selected value object observable object in my data model but when i am trying to use the value binding in select option its giving me an error of value is not a function:

```<code>//....
    <h1 class="page-header">Kitchen</h1>
    <select data-bind="options:dataModel.options()[0]['Kitchen'], optionsText:'label', value: selectedValue">
    </select>
</div>`
</code>```

This is the HTML code where i made select:

```<code>var dataModel = {
    selectedValue : ko.observable()
};
</code>```

As i said earlier the data is fetched from json file .

This is how json looks like:

```<code>"options": {
    "Kitchen": [{
        "label": "Ivory",
        "data": "001-001"
    },
    {
        "label": "Chocolate",
        "data": "001-002"
    }]
}
</code>```

答:
The options from json is not an array (the array one is the Kitchen), so shouldn't it be dataModel.options()['Kitchen'] instead of dataModel.options()[0]['Kitchen']. Or maybe you can put dataModel.options().Kitchen
So the select is going to be look like:

```<code><select data-bind="options:dataModel.options().Kitchen, optionsText:'label', value: selectedValue">
</select>
</code>```

Title: knockout select option not working

Body:
I am working on a project in which data is fetched from the api and i am trying to make a drop down list, using select binding . I have declared my selected value object observable object in my data model but when i am trying to use the value binding in select option its giving me an error of value is not a function:

//....

Kitchen

    <select data-bind="options:dataModel.options()[0]['Kitchen'], optionsText:'label', value: selectedValue">
    </select>

`

This is the HTML code where i made select:

var dataModel = {
    selectedValue : ko.observable()
};

As i said earlier the data is fetched from json file .

This is how json looks like:

"options": {
    "Kitchen": [{
        "label": "Ivory",
        "data": "001-001"
    },
    {
        "label": "Chocolate",
        "data": "001-002"
    }]
}

Body:
The options from json is not an array (the array one is the Kitchen), so shouldn't it be dataModel.options()['Kitchen'] instead of dataModel.options()[0]['Kitchen']. Or maybe you can put dataModel.options().Kitchen
So the select is going to be look like:

<select data-bind="options:dataModel.options().Kitchen, optionsText:'label', value: selectedValue">
</select>


问:
In Tensorflow, what is the difference between sampled_softmax_loss and softmax_cross_entropy_with_logits
In tensorflow, there are methods called softmax_cross_entropy_with_logits and sampled_softmax_loss.

I read the tensorflow document and searched google for more information but I couldn't find the difference. It looks like to me both calculates the loss using softmax function.

Using sampled_softmax_loss to calculate the loss

```<code>loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(...))
</code>```

Using softmax_cross_entropy_with_logits to calculate the loss

```<code>loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(P, Q))
</code>```

To me, calculating softmax loss is same as calculating softmaxed cross entropy (e.g. cross_entropy(softmax(train_x)))

Could somebody tell me the why there is two different methods and which method should I use in which case?

答:
Sampled:

Sampled, in both cases means you don't calculate it for all of what's possible as an output (e.g.: if there are too many words in a dictionary to take all of them at each derivation, so we take just a few samples and learn on that for NLP problems).

softmax_cross_entropy_with_logits:

This is the cross entropy and receives logits as inputs and yields what can be used as a loss.

sampled_softmax_loss:

This is a sampled softmax_cross_entropy_with_logits, so it takes just a few samples before using the cross entropy rather than using the full cross entropy: https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/python/ops/nn_impl.py#L1269

Body:
In tensorflow, there are methods called softmax_cross_entropy_with_logits and sampled_softmax_loss.

I read the tensorflow document and searched google for more information but I couldn't find the difference. It looks like to me both calculates the loss using softmax function.

Using sampled_softmax_loss to calculate the loss

loss = tf.reduce_mean(tf.nn.sampled_softmax_loss(...))

Using softmax_cross_entropy_with_logits to calculate the loss

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(P, Q))

To me, calculating softmax loss is same as calculating softmaxed cross entropy (e.g. cross_entropy(softmax(train_x)))

Could somebody tell me the why there is two different methods and which method should I use in which case?


问:
Reverse-Mapping for String Enums
I wanted to use string enums in typescript but I can't see a support for reversed mapping in it.
I have an enum like this:

```<code>enum Mode {
    Silent = "Silent",
    Normal = "Normal",
    Deleted = "Deleted"
}
</code>```

and I need to use it like this:

```<code>let modeStr: string;
let mode: Mode = Mode[modeStr];
</code>```

and yes I don't know what is it there in modeStr string and I need it parsed to the enum or a fail at parsing in runtime if the string is not presented in the enum definition.
How can I do that as neat as it can be?
thanks in advance

答:
We can make the Mode to be a type and a value at the same type.

```<code>type Mode = string;
let Mode = {
    Silent: "Silent",
    Normal: "Normal",
    Deleted: "Deleted"
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = "Deleted"; // Deleted
mode = Mode["unknown"]; // undefined
mode = "invalid"; // "invalid"
</code>```

A more strict version:

```<code>type Mode = "Silent" | "Normal" | "Deleted";
const Mode = {
    get Silent(): Mode { return "Silent"; },
    get Normal(): Mode { return "Normal"; },
    get Deleted(): Mode { return "Deleted"; }
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = "Deleted"; // Deleted
mode = Mode["unknown"]; // undefined
//mode = "invalid"; // Error
</code>```

String Enum as this answer:

```<code>enum Mode {
    Silent = <any>"Silent",
    Normal = <any>"Normal",
    Deleted = <any>"Deleted"
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
//mode = "Deleted"; // Error
mode = Mode["unknown"]; // undefined
</code>```

Title: Reverse-Mapping for String Enums

Body:
I wanted to use string enums in typescript but I can't see a support for reversed mapping in it.
I have an enum like this:

enum Mode {
    Silent = "Silent",
    Normal = "Normal",
    Deleted = "Deleted"
}

and I need to use it like this:

let modeStr: string;
let mode: Mode = Mode[modeStr];

and yes I don't know what is it there in modeStr string and I need it parsed to the enum or a fail at parsing in runtime if the string is not presented in the enum definition.
How can I do that as neat as it can be?
thanks in advance

Body:
We can make the Mode to be a type and a value at the same type.

type Mode = string;
let Mode = {
    Silent: "Silent",
    Normal: "Normal",
    Deleted: "Deleted"
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = "Deleted"; // Deleted
mode = Mode["unknown"]; // undefined
mode = "invalid"; // "invalid"

A more strict version:

type Mode = "Silent" | "Normal" | "Deleted";
const Mode = {
    get Silent(): Mode { return "Silent"; },
    get Normal(): Mode { return "Normal"; },
    get Deleted(): Mode { return "Deleted"; }
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = "Deleted"; // Deleted
mode = Mode["unknown"]; // undefined
//mode = "invalid"; // Error

String Enum as this answer:

enum Mode {
    Silent = <any>"Silent",
    Normal = <any>"Normal",
    Deleted = <any>"Deleted"
}

let modeStr: string = "Silent";
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
//mode = "Deleted"; // Error
mode = Mode["unknown"]; // undefined


问:
WebStorm Webpack Alias
My import import {keyGen} from 'shared/utils/gen' says cannot resolve symbol 'keyGen'. NPM package loading works just fine. The webpack builds also succeed and run just fine with the alias.

Here is our alias:

```<code>resolve: {
  extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.styl'],

  alias: {
    shared: relativePath('./client/source/shared'),
    root: relativePath('./client/source'),
    config: relativePath('./')
  },

  modules: [relativePath('./node_modules')]
}
</code>```

I made sure the correct Webpack config file is selected in the project settings. How do I get WebStorm to correctly identify Webpack aliases?

答:
If your config file exists on the same level with other source code files, try this:

```<code>alias: {
    shared: path.resolve('client/source/shared'),
    ...
}
</code>```

Reference: https://webpack.js.org/configuration/resolve/

Title: WebStorm Webpack Alias

Body:
My import import {keyGen} from 'shared/utils/gen' says cannot resolve symbol 'keyGen'. NPM package loading works just fine. The webpack builds also succeed and run just fine with the alias.

Here is our alias:

resolve: {
  extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.styl'],

  alias: {
    shared: relativePath('./client/source/shared'),
    root: relativePath('./client/source'),
    config: relativePath('./')
  },

  modules: [relativePath('./node_modules')]
}

I made sure the correct Webpack config file is selected in the project settings. How do I get WebStorm to correctly identify Webpack aliases?

Body:
If your config file exists on the same level with other source code files, try this:

alias: {
    shared: path.resolve('client/source/shared'),
    ...
}

Reference: https://webpack.js.org/configuration/resolve/


问:
Mule SQLJDBC JavaKerberos authentication- classpath issue
I am Using SQLJDBC to connect to MS-SQL using JavaKerberos authentication . Unfortunately  when i set following values , SQLJDBC is not looking for the files in src/main/resources , instead it expects the files to be in root (which fails in cloudhub/stand alone but works fine in studio)

System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", "sqlserverJDBC.conf");
System.setProperty("java.security.krb5.conf", "krb5.conf");
Help needed !!

Thanks
Naveen H

答:
you will need to set the path (relative or absolute) to the conf file.

System.setProperty("java.security.krb5.conf", "src/main/resources/krb5.conf");

https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/KerberosReq.html


问:
Get value from multi tr of table
I have many table row, i want to get the value (it's a number) of each row to an array !

```<code><form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]" /></td>
        </tr>
    </tbody>
</table>
</code>```

Like this code, i want to get the value of each "pduct" !

答:
Add class attribute in the input tag. (e.g. class="abc")

Use Jquery.

```<code>$('.abc').each(function(i, obj) {
    //$(this).val(); << return value
});
</code>```

Title: Get value from multi tr of table

Body:
I have many table row, i want to get the value (it's a number) of each row to an array !

<form class="form-horizontal" id="form1" name="form1" method="post" action="url">

            Name
            Number

            A
            <input type="number" id="pduct1" class="product" name="pduct[]" />

            B
            <input type="number" id="pduct2" class="product" name="pduct[]" />

            C
            <input type="number" id="pduct3" class="product" name="pduct[]" />

            D
            <input type="number" id="pduct4" class="product" name="pduct[]" />

Like this code, i want to get the value of each "pduct" !

Body:
Add class attribute in the input tag. (e.g. class="abc")

Use Jquery.

$('.abc').each(function(i, obj) {
    //$(this).val(); << return value
});


问:
Examples of end-to-end GoLang build pipeline
There seems to be little information around examples and best practices when building an end-to-end pipeline for a Go Lang application that can:

Calculate next version (ala semantic-release)

Run all tests

Build for the different supported platforms ((Linux, FreeBSD, Mac OS X, Windows) * (amd64, 386, arm, s390x, ppc64le))

Tag and Release in a SCM (github | gitlab | bitbucket)

Optionally create packages (deb, rpm, snaps, flatpaks, brew taps, Inno Setup).

Run this integrated in (TravisCI | CircleCI | Jenkins | Bamboo | others)

Is there any documentation, example project at this regard? I've checked some of the more famous Go projects (kubernetes, hashicorp/* and others) and they all seem to leave this part outside of the project.

答:
I am not sure if this is what you need, but you can take a look at this one goreleaser.

GoReleaser builds Go binaries for several platforms, creates a GitHub
  release and then pushes a Homebrew formula to a repository. All that
  wrapped in your favorite CI.


问:
Howto detect when a file is released
General information: VS 2010, C#, net.framework 4.0.
brief: Howto detect when a file is released?

Long description

I convert a wav file with lame codec. That process takes some seconds (upto 30 seconds). After the wav file will be converted, I want to delete the source wav file. How to detect when the wav file is released by lame.exe and can be deleted? Please give a method, but without a timer that waiting for 30 seconds and trying to delete (it's bad idea).

答:
There are example code in MSDN, you can take a reference.

https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

```<code>// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
</code>```

Title: Howto detect when a file is released

Body:
There are example code in MSDN, you can take a reference.

https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);


问:
Adding a map of string vector and different datatype vector
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map<std::string, Spikes::data> get_data1(). I create a struct called data:

```<code>struct data {

            std::vector<Eigen::MatrixXd> samples;
            std::vector<std::string> sample_names;
            int index = -1;
        };
</code>```

and placed it in my namespace and out of the class FileReader.

My method looks like:

```<code>std::map<std::string, Spikes::data> FileReader::get_data1() {
    std::map<std::string, Spikes::data> content;

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> sample_names;

    for (auto i : list_dir()) {
        if (contains_number(i)) {
            samples.push_back(load_csv(location + "/" + i));
            sample_names.push_back(i);
        }
    }

    content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
    content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));

    return content;
</code>```

And in my main.cpp I am calling this method as:

```<code>for (auto i:a.get_data1()["samples"].samples){
        std::cout<<i;
    }
</code>```

But I get the following errors:

```<code>/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp: In member function 'std::map<std::basic_string<char>, Spikes::data> Spikes::FileReader::get_data1()':
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:154:69: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
                                                                     ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:155:79: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));
                                                                               ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
</code>```

I have no clue as to what is going on.

I have even tried doing:

```<code>content["samples"] = Spikes::data{samples,0};
content["sample_names"] = Spikes::data{sample_names,1};
</code>```

I still get the same error. Any help would be highly appreciated.

答:
When you use value initialization for a simple structure/aggregate/etc...:

```<code>Spikes::data{samples,0}
</code>```

You must initialize every member of this structure.

Your data class contains three members, the first two of them are vectors, and the third class member an int. Obviously initializing a std::vector of std::strings using a plain integer 0 is not going to go anywhere. This 0 will be interpreted as a value to initialize the second member of your struct, since it's the second value in the initialization list. The second member of your struct is a std::vector of std::strings, and the compiler will, essentially, attempt to initialize the second member accordingly, something like this:

```<code>std::vector<std::string> sample_names{0};
</code>```

This is what your attempt at initialization boils down to, and this is not going to go very far...

You cannot arbitrarily skip class members, when using value initialization. You must initialize every class member, in order. In this case, your likely intent is probably something along these lines:

```<code>Spikes::data{samples,{},0}
</code>```

Thusly initializing the second vector with an empty sub-initialization list. Similarly, your second attempt at initialization:

```<code>Spikes::data{sample_names,1}
</code>```

It suffers from the same problem. Your likely intentions here are probably:

```<code>Spikes::data{{}, sample_names,1}}
</code>```

i.e. initializing the first std::vector member with an empty initialization list, and then initializing the second std::vector accordingly.

Body:
As suggested in https://stackoverflow.com/a/44884240/3782963. I created a method of return type std::map<std::string, Spikes::data> get_data1(). I create a struct called data:

struct data {

            std::vector<Eigen::MatrixXd> samples;
            std::vector<std::string> sample_names;
            int index = -1;
        };

and placed it in my namespace and out of the class FileReader.

My method looks like:

std::map<std::string, Spikes::data> FileReader::get_data1() {
    std::map<std::string, Spikes::data> content;

    std::vector<Eigen::MatrixXd> samples;
    std::vector<std::string> sample_names;

    for (auto i : list_dir()) {
        if (contains_number(i)) {
            samples.push_back(load_csv(location + "/" + i));
            sample_names.push_back(i);
        }
    }

    content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
    content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));

    return content;

And in my main.cpp I am calling this method as:

for (auto i:a.get_data1()["samples"].samples){
        std::cout<<i;
    }

But I get the following errors:

/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp: In member function 'std::map<std::basic_string<char>, Spikes::data> Spikes::FileReader::get_data1()':
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:154:69: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("samples", Spikes::data{samples,0}));
                                                                     ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:155:79: error: no matching function for call to 'Spikes::data::data(<brace-enclosed initializer list>)'
     content.emplace(std::make_pair("sample_names", Spikes::data{sample_names,1}));
                                                                               ^
In file included from /cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.cpp:3:0:
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data()
     struct data {
            ^
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 0 arguments, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(const Spikes::data&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note: candidate: Spikes::data::data(Spikes::data&&)
/cygdrive/c/Users/aksha/Box Sync/MyDrive/Projects/Akshay-GitHub/libSpikes/libSpikes/src/Core/FileReader.h:13:12: note:   candidate expects 1 argument, 2 provided

I have no clue as to what is going on.

I have even tried doing:

content["samples"] = Spikes::data{samples,0};
content["sample_names"] = Spikes::data{sample_names,1};

I still get the same error. Any help would be highly appreciated.

Body:
When you use value initialization for a simple structure/aggregate/etc...:

Spikes::data{samples,0}

You must initialize every member of this structure.

Your data class contains three members, the first two of them are vectors, and the third class member an int. Obviously initializing a std::vector of std::strings using a plain integer 0 is not going to go anywhere. This 0 will be interpreted as a value to initialize the second member of your struct, since it's the second value in the initialization list. The second member of your struct is a std::vector of std::strings, and the compiler will, essentially, attempt to initialize the second member accordingly, something like this:

std::vector<std::string> sample_names{0};

This is what your attempt at initialization boils down to, and this is not going to go very far...

You cannot arbitrarily skip class members, when using value initialization. You must initialize every class member, in order. In this case, your likely intent is probably something along these lines:

Spikes::data{samples,{},0}

Thusly initializing the second vector with an empty sub-initialization list. Similarly, your second attempt at initialization:

Spikes::data{sample_names,1}

It suffers from the same problem. Your likely intentions here are probably:

Spikes::data{{}, sample_names,1}}

i.e. initializing the first std::vector member with an empty initialization list, and then initializing the second std::vector accordingly.


问:
BitTorrent peer_id encoded format, Invalid Request
I am trying to format a tracker request using BitTorrentSpecification but I don't get how to format the plan string peerID I am generating. A sample of both from my program is:

```<code>New Session ID generated: -MC0001-948902816289
Session ID URLEncoded: %-M%C0%00%1-%94%89%02%81%62%89
</code>```

Do I send that? I am getting Invalid request from the server... I have tested and my info_hash is valid. Sample request below.

```<code>http://tracker.tfile.me/announce?info_hash=%B5%E1%3F%36%35%09%62%85%A2%F4%B9%C8%9A%75%E9%F1%CC%BD%C3%CD&peer_id=%-M%C0%00%1-%94%89%02%81%62%89&port=6888&uploaded=0&downloaded=0&left=4018984971&compact=0
</code>```

答:
The URLencoding of the peer_id is not correctly done and it don't need to be URLencoded, as all the characters in it is URL-safe. Send it as: ...&peer_id=-MC0001-948902816289&...

Also, compact=1 is more or less obligatory today. Very few trackers support the legacy non compact reply. Change to ...&compact=1 and it will work.

There is also no event=started, it should be there if it's the first time the tracker is contacted.

Send:

```<code>http://tracker.tfile.me/announce?info_hash=%B5%E1%3F%36%35%09%62%85%A2%F4%B9%C8%9A%75%E9%F1%CC%BD%C3%CD&peer_id=-MC0001-948902816289&port=6888&uploaded=0&downloaded=0&left=4018984971&event=started&compact=1
</code>```

and the reply is:

```<code>d8:completei0e10:downloadedi0e10:incompletei1e8:intervali2988e12:min intervali1494e5:peers6:******
</code>```

Body:
I am trying to format a tracker request using BitTorrentSpecification but I don't get how to format the plan string peerID I am generating. A sample of both from my program is:

New Session ID generated: -MC0001-948902816289
Session ID URLEncoded: %-M%C0%00%1-%94%89%02%81%62%89

Do I send that? I am getting Invalid request from the server... I have tested and my info_hash is valid. Sample request below.

http://tracker.tfile.me/announce?info_hash=%B5%E1%3F%36%35%09%62%85%A2%F4%B9%C8%9A%75%E9%F1%CC%BD%C3%CD&peer_id=%-M%C0%00%1-%94%89%02%81%62%89&port=6888&uploaded=0&downloaded=0&left=4018984971&compact=0

Body:
The URLencoding of the peer_id is not correctly done and it don't need to be URLencoded, as all the characters in it is URL-safe. Send it as: ...&peer_id=-MC0001-948902816289&...

Also, compact=1 is more or less obligatory today. Very few trackers support the legacy non compact reply. Change to ...&compact=1 and it will work.

There is also no event=started, it should be there if it's the first time the tracker is contacted.

Send:

http://tracker.tfile.me/announce?info_hash=%B5%E1%3F%36%35%09%62%85%A2%F4%B9%C8%9A%75%E9%F1%CC%BD%C3%CD&peer_id=-MC0001-948902816289&port=6888&uploaded=0&downloaded=0&left=4018984971&event=started&compact=1

and the reply is:

d8:completei0e10:downloadedi0e10:incompletei1e8:intervali2988e12:min intervali1494e5:peers6:******