问:
My script returns the first item only
I'm coding with asp.net/ c# and i'm trying to get the id and the quantity of a product using ajax. The problem is  that my code only recognize the first item otherwise if i tried to enter the quantity of the third product i get an error saying that I haven't provided any quantity.

here's my code :

```<code>      <script type="text/javascript">
$(function() {
    $('.Sendparams').click(function (e) {
  e.preventDefault();
    debugger;
//  var  id = $(this).attr('id');
    var quant = $("#quant").val();
var id = $("#id").val();

    $.ajax({
        type: 'GET',
        url: '/ShoppingCart/AddToCart',
        data:{ "id": id , "quant": quant },
    success: function (response) {
            $("#mainContainerCenter").html(response); } });});
  });
</script>
  <section class="content">
  <!-- Small boxes (Stat box) -->
    <div class="row">

   @foreach (var album in Model.Produits)
  {

            <div class="col-lg-3 col-xs-6">
                @Html.Hidden("id", album.ProduitId, new { @id = "id" })<br/>

              @album.Nom_Produit<br />
             @album.Categorie.Nom_categorie<br />
               @String.Format("{0:F}", album.Prix)<br />
               @Html.TextBox("quant", null, new { id = "quant" })<br />
                @Html.ActionLink("voila", "AddToCart", "ShoppingCart", new { id = album.ProduitId }, new { @class = "Sendparams" })<br />

            </div>
    }

     </div>
</code>```

答:
id attribute would be the uniq value. In your case the id is not the uniq, you using the "quant" value for all items (id="quant"). If i correctly understand what you try to do this is code can help: https://jsfiddle.net/9usvg6wv/

$(".item").submit(function( event ) {
  $('#clickedid').text(
   $(this).find('input[name="id"]').val()
  );
  $('#clickedquant').text(
   $(this).find('input[name="quant"]').val()
  );
  console.log($(this).find('input[name="quant"]').val());
  event.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <form action="" class="item" >
      <input type="hidden" name="id" value="1" />
      <input type="text" name="quant" value="100" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="2" />
      <input type="text" name="quant" value="200" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="3" />
      <input type="text" name="quant" value="300" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="4" />
      <input type="text" name="quant" value="400" />
      <input type="submit" class="" >
    </form>
</div>

<div>
Clicked id:<span id="clickedid"></span>; quant:<span id="clickedquant"></span>
</div></code>```

Title: My script returns the first item only

Body:
I'm coding with asp.net/ c# and i'm trying to get the id and the quantity of a product using ajax. The problem is  that my code only recognize the first item otherwise if i tried to enter the quantity of the third product i get an error saying that I haven't provided any quantity.

here's my code :

   @foreach (var album in Model.Produits)
  {

                @Html.Hidden("id", album.ProduitId, new { @id = "id" })

              @album.Nom_Produit

             @album.Categorie.Nom_categorie

               @String.Format("{0:F}", album.Prix)

               @Html.TextBox("quant", null, new { id = "quant" })

                @Html.ActionLink("voila", "AddToCart", "ShoppingCart", new { id = album.ProduitId }, new { @class = "Sendparams" })

    }

Body:
id attribute would be the uniq value. In your case the id is not the uniq, you using the "quant" value for all items (id="quant"). If i correctly understand what you try to do this is code can help: https://jsfiddle.net/9usvg6wv/

$(".item").submit(function( event ) {
  $('#clickedid').text(
   $(this).find('input[name="id"]').val()
  );
  $('#clickedquant').text(
   $(this).find('input[name="quant"]').val()
  );
  console.log($(this).find('input[name="quant"]').val());
  event.preventDefault();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <form action="" class="item" >
      <input type="hidden" name="id" value="1" />
      <input type="text" name="quant" value="100" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="2" />
      <input type="text" name="quant" value="200" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="3" />
      <input type="text" name="quant" value="300" />
      <input type="submit" class="" >
    </form>

    <form action="" class="item" >
      <input type="hidden" name="id" value="4" />
      <input type="text" name="quant" value="400" />
      <input type="submit" class="" >
    </form>
</div>

<div>
Clicked id:<span id="clickedid"></span>; quant:<span id="clickedquant"></span>
</div>


来源: stackexchange

问:
Javascript: Regular expression to allow negative and positive floating point numbers?
I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this

```<code>/^-|[0-9\ ]+$/
</code>```

However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.

At the moment i'm using this

```<code>/^-|[0-9][0-9\ ]+$/
</code>```

This fixes the first problem but this will match something like "-4g" and that is also incorrect.

What expression can I use to match negative and positive floating points?

答:
Try this...

I am sure, it's work in javascript.

var pattern = new RegExp("^-?[0-9.]*$");

if (pattern.test(valueToValidate))
{

```<code>   return true;
</code>```

}
else
 {

```<code> return false;
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this

/^-|[0-9\ ]+$/

However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.

At the moment i'm using this

/^-|[0-9][0-9\ ]+$/

This fixes the first problem but this will match something like "-4g" and that is also incorrect.

What expression can I use to match negative and positive floating points?

Body:
Try this...

I am sure, it's work in javascript.

var pattern = new RegExp("^-?[0-9.]*$");

if (pattern.test(valueToValidate))
{

   return true;

}
else
 {

 return false;

}


问:
count 2 fields combined in qlikview
I have two fields in my Qlikview Data - Procedures and 2nd Element

They both contain data that is duplicated between them;

eg Procedures field has: "This", "That", "The other" whilst 2nd Element Field has: "This", "That", "Something else"

I want to create a bar chart that can show the combined totals of the two fields:

eg "This" = 2, "That" = 2, "The other" = 1, "something else" = 1

No matter what expression i put in though i can't get it to work properly.

Has anyone got any suggestions?

Thanks.

答:
I would try to solve this using a script approach. You'll need :

Make sure that every row in you table has an unique id (for instance using RowNo() as RecordId in the Load statement)

After loading the table (let's call it DataTable), do a first resident Load like this LOAD RecordId, Procedures as NewColumn resident DataTable.

Do the same thing for the second column : LOAD RecordId, 2ndElement as NewColumn resident DataTable.

You'll end up with a new table that combines both columns in one. On the chart you'll need to use NewColumn as the dimension and Count(RecordId) as the expression.

Title: count 2 fields combined in qlikview


问:
Download file using ASP.NET Core
I´m trying to download a excel file after the file is created and I´m having the following error:

UnauthorizedAccessException: Access to the path 'C:\Users\user_name\Documents\Visual Studio 2015\Projects\Project_Name\src\Project_Name\wwwroot' is denied.

The file is created successfully, the problem is in the download method.

I already try to solve this error doing the following actions:

Open VS as Admin

Add IIS_IUSR user to the project folder

Here´s the code:

```<code>    private readonly IHostingEnvironment _hostingEnvironment;
    public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    public void createFile()
    {
        string wwwrootPath = _hostingEnvironment.WebRootPath;
        string fileName = @"Employees.xlsx";
        FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));

        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(wwwrootPath, fileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save();
            downloadFile(wwwrootPath);

        }

}
    public FileResult downloadFile(string filePath)
    {
        var mimeType = "application/vnd.ms-excel";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        return File(fileStream, mimeType, "Employees.xlsx");
    }
</code>```

Note: I didn´t make the deploy of the project in IIS.

Best Regards

答:
I test your code and the error is gone, but the file is not being downloaded. Here is the code:

```<code>public FileResult downloadFile(string filePath, string fileName)
{
        IFileProvider provider = new PhysicalFileProvider(filePath);
        IFileInfo fileInfo = provider.GetFileInfo(fileName);
        var readStream = fileInfo.CreateReadStream();
        var mimeType = "application/vnd.ms-excel";
        return File(readStream, mimeType, fileName);
}
</code>```

Best Regards

Title: Download file using ASP.NET Core

Body:
I´m trying to download a excel file after the file is created and I´m having the following error:

UnauthorizedAccessException: Access to the path 'C:\Users\user_name\Documents\Visual Studio 2015\Projects\Project_Name\src\Project_Name\wwwroot' is denied.

The file is created successfully, the problem is in the download method.

I already try to solve this error doing the following actions:

Open VS as Admin

Add IIS_IUSR user to the project folder

Here´s the code:

    private readonly IHostingEnvironment _hostingEnvironment;
    public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    public void createFile()
    {
        string wwwrootPath = _hostingEnvironment.WebRootPath;
        string fileName = @"Employees.xlsx";
        FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));

        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(wwwrootPath, fileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save();
            downloadFile(wwwrootPath);

        }

}
    public FileResult downloadFile(string filePath)
    {
        var mimeType = "application/vnd.ms-excel";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        return File(fileStream, mimeType, "Employees.xlsx");
    }

Note: I didn´t make the deploy of the project in IIS.

Best Regards

Body:
I test your code and the error is gone, but the file is not being downloaded. Here is the code:

public FileResult downloadFile(string filePath, string fileName)
{
        IFileProvider provider = new PhysicalFileProvider(filePath);
        IFileInfo fileInfo = provider.GetFileInfo(fileName);
        var readStream = fileInfo.CreateReadStream();
        var mimeType = "application/vnd.ms-excel";
        return File(readStream, mimeType, fileName);
}

Best Regards


问:
Doctrine Raw SQL not calling custom function
I'm having an issue calling an custom defined function in my database from Doctrine when using the Raw SQL.

Here is an example SQL Query that is being run

```<code> SELECT unicodeDecoder(answer) from answers;
</code>```

unicodeDecoder is a custom defined function in my database and runs perfectly fine when I run the SQL statement directly on the database.

However when I run the query using raw sql, as follows:

```<code>$sql = "SELECT unicodeDecoder(answer) from answers";
$stmt = $this->getEntitityManager()->getConnection()->prepare($sql);
$stmt->execute();
</code>```

I get the following error:

```<code>SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION unicodeDecoder does not exist
</code>```

Do I need to create a custom ORM mapping when using custom functions or could this be some form of caching issue?

Any help would be massively appreciated.

Thanks in advance

答:
Try to prefix the function with database name: </p>

```<code>$sql = "SELECT my_db.unicodeDecoder(answer) from answers";
</code>```

Body:
I'm having an issue calling an custom defined function in my database from Doctrine when using the Raw SQL.

Here is an example SQL Query that is being run

 SELECT unicodeDecoder(answer) from answers;

unicodeDecoder is a custom defined function in my database and runs perfectly fine when I run the SQL statement directly on the database.

However when I run the query using raw sql, as follows:

$sql = "SELECT unicodeDecoder(answer) from answers";
$stmt = $this->getEntitityManager()->getConnection()->prepare($sql);
$stmt->execute();

I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION unicodeDecoder does not exist

Do I need to create a custom ORM mapping when using custom functions or could this be some form of caching issue?

Any help would be massively appreciated.

Thanks in advance

Body:
Try to prefix the function with database name:

$sql = "SELECT my_db.unicodeDecoder(answer) from answers";


问:
Java convert String of byte array to byte array
I got a byte array sent from javascript by ajax looking like this:

```<code>"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."
</code>```

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

```<code>    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }
</code>```

答:
You can try this

```<code>String response ="89,50,47,00,00,00,49,48,44,52,00,00,01,98,00,00,00,08";

List<Byte> byteList = Arrays.stream(response.split(","))
   .map(Byte::parseByte)
   .collect(Collectors.toList());
</code>```

same as previous but with stream xD

but your example throws NumberFormatException on 4e, 0d and so on

Body:
I got a byte array sent from javascript by ajax looking like this:

"89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00 ..."

I would like to convert this string to a byte array.
Pretty similar to this question, but using Java instead: Convert String[] to byte[] array

Edit:
This seems to work - but not sure if i am doing it right

    String[] byteData ="89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,01,98,00,00,00,e4,08,06,00";
    byte[] b = new byte[byteData.length];
    for (int i = 0; i < byteData.length; i++) {
        BigInteger bla = BigInteger.valueOf(Integer.parseInt(byteData[i].trim(), 16) - 128);
        b[i] = bla.toByteArray()[0];
    }

Body:
You can try this

String response ="89,50,47,00,00,00,49,48,44,52,00,00,01,98,00,00,00,08";

List<Byte> byteList = Arrays.stream(response.split(","))
   .map(Byte::parseByte)
   .collect(Collectors.toList());

same as previous but with stream xD

but your example throws NumberFormatException on 4e, 0d and so on


问:
Switch Rows and Columns 2d Array
I want to swap Columns and Rows in a 2D array.

My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.

Id like to know how I can save the Variable oldField independent

```<code>public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
                                            // a Field
    int[][] oldField = pField.clone();
    int[][] newField = pField.clone();
    for (int i = 0; i < newField.length; i++) {
        for (int j = (newField.length - 1); j >= 0; j--) {
            newField[i][(newField.length - 1) - j] = oldField[j][i];
        }
    }
    return newField;

}
</code>```

答:
this code solves your problem:</p>

```<code>public class SwapRowsAndColumns {

    public static void main(String[] args) {

        int[][] someMatrix = new int[2][3];

        someMatrix[0][0] = 1;
        someMatrix[0][1] = 2;
        someMatrix[0][2] = 3;

        someMatrix[1][0] = 4;
        someMatrix[1][1] = 5;
        someMatrix[1][2] = 6;

        printMatrix(someMatrix);
        int[][] invertedMatrix = swapMatrix(someMatrix);
        printMatrix(invertedMatrix);

    }

    private static int[][] swapMatrix(int[][] pField) {

        int originalTotalRows = pField.length;
        int originalTotalColumns = pField[0].length;

        int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];

        for(int i=0; i< originalTotalRows; i++){
            for(int j=0; j < originalTotalColumns; j++){
                newMatrix[j][i] = pField[i][j];
            }
        }
        return newMatrix;
    }

    private static void printMatrix(int[][] matrix){
        int totalRows = matrix.length;
        int totalColumns = matrix[0].length;

        for(int i=0; i< totalRows; i++){
            for(int j=0; j< totalColumns; j++){
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println("");
        }
    }
}
</code>```

Title: Switch Rows and Columns 2d Array

Body:
I want to swap Columns and Rows in a 2D array.

My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.

Id like to know how I can save the Variable oldField independent

public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
                                            // a Field
    int[][] oldField = pField.clone();
    int[][] newField = pField.clone();
    for (int i = 0; i < newField.length; i++) {
        for (int j = (newField.length - 1); j >= 0; j--) {
            newField[i][(newField.length - 1) - j] = oldField[j][i];
        }
    }
    return newField;

}

Body:
this code solves your problem:

public class SwapRowsAndColumns {

    public static void main(String[] args) {

        int[][] someMatrix = new int[2][3];

        someMatrix[0][0] = 1;
        someMatrix[0][1] = 2;
        someMatrix[0][2] = 3;

        someMatrix[1][0] = 4;
        someMatrix[1][1] = 5;
        someMatrix[1][2] = 6;

        printMatrix(someMatrix);
        int[][] invertedMatrix = swapMatrix(someMatrix);
        printMatrix(invertedMatrix);

    }

    private static int[][] swapMatrix(int[][] pField) {

        int originalTotalRows = pField.length;
        int originalTotalColumns = pField[0].length;

        int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];

        for(int i=0; i< originalTotalRows; i++){
            for(int j=0; j < originalTotalColumns; j++){
                newMatrix[j][i] = pField[i][j];
            }
        }
        return newMatrix;
    }

    private static void printMatrix(int[][] matrix){
        int totalRows = matrix.length;
        int totalColumns = matrix[0].length;

        for(int i=0; i< totalRows; i++){
            for(int j=0; j< totalColumns; j++){
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println("");
        }
    }
}


问:
BLOB Storage - 100+ GB, MySQL, SQLite, or PostgreSQL + Python
I have an idea for a simple application which will monitor a group of folders, index any files it finds. A gui will allow me quickly tag new files and move them into a single database for storage and also provide an easy mechanism for querying the db by tag, name, file type and date. At the moment I have about 100+ GB of files on a couple removable hard drives, the database will be at least that big. If possible I would like to support full text search of the embedded binary and text documents. This will be a single user application.

Not trying to start a DB war, but what open source DB is going to work best for me? I am pretty sure SQLLite is off the table but I could be wrong.

答: I'm still researching this option for one of my own projects, but CouchDB may be worth a look.</p>

OwnerDisplayName: Ethan Post

LastEditorDisplayName: Eddie

OwnerDisplayName: Ryan Duffield

ContentLicense: CC BY-SA 2.5


问:
How do you Manage Infragistics WebGrid Data from JavaScript/Ajax code?
I am working on a project that I need to use the Infragistics WebGrid control for some lists of data. I am loading the data on the client-side using JavaScript for display on a Map, and then I need to display that same data within multiple WebGrids. All the data available will be displayed in the WebGrids, but only a subset of the data (only that which is currently within view) will be plotted on the Map at any given time. Since I am loading the data using JavaScript/Ajax, I would like to only load it once, and use the same mechanism to populate the WebGrid control with data too.

Does anyone have any tips/pointers on working with the WebGrid completely from within client-side JavaScript/Ajax code?

答:
The Infragistics webgrids expose a very complex client side object model that you will be able to use to populate your data client side.

The first thing you will want to do is get a look at the full CSOM for the webgrid control, you can find the current doc version at: http://help.infragistics.com/NetAdvantage/NET/2008.3/CLR2.0/

To make a short example, you will need to grab a refence to your grid(s) and then add some rows and data. It would probably be easier to setup the column definitions for your grids at design time, rather than try to do it all in the javascript.

First: get a refrence to your grid:

```<code>var grid = igtbl_getGridById('dataGridControlID');
</code>```

Then add a new row:

```<code>var newRow = grid.Rows.addNew()
</code>```

After thats done you can loop the columns of your row to fill the data:

```<code>var oCols = newRow.Band.Columns;
for(var i=0; i < oCols.length; i++) {
    newRow.getCell[i].setValue(yourValue)
}
</code>```

or address each one by key to populate its data:

```<code>newRow.getCellFromKey(colKey).setValue(yourValue,fireEvents);
</code>```

OwnerDisplayName: Chris Pietschmann

Body:
The Infragistics webgrids expose a very complex client side object model that you will be able to use to populate your data client side.

The first thing you will want to do is get a look at the full CSOM for the webgrid control, you can find the current doc version at: http://help.infragistics.com/NetAdvantage/NET/2008.3/CLR2.0/

To make a short example, you will need to grab a refence to your grid(s) and then add some rows and data. It would probably be easier to setup the column definitions for your grids at design time, rather than try to do it all in the javascript.

First: get a refrence to your grid:

var grid = igtbl_getGridById('dataGridControlID');

Then add a new row:

var newRow = grid.Rows.addNew()

After thats done you can loop the columns of your row to fill the data:

var oCols = newRow.Band.Columns;
for(var i=0; i < oCols.length; i++) {
    newRow.getCell[i].setValue(yourValue)
}

or address each one by key to populate its data:

newRow.getCellFromKey(colKey).setValue(yourValue,fireEvents);


问:
Info.plist Utility Error: "Info.plist couldn't be opened because there is no such file"
I'm running into what seems to be common error, in that Xcode can't seem to find my 'Info.plist' file.

I've checked the answers to these two StackOverflow questions (Could not read from Info.plist and Objective C/Xcode error: The file “Info.plist” couldn’t be opened because there is no such file)...I am using a relative path, and the plist file is in the correct absolute location. The type and location are correct as shown in the image below:

My biggest concern is that this is now happening on multiple projects, including one I ran successfully just a few hours ago! Does anyone know how to solve this???

EDIT I've also tried reinstalling XCODE and replacing the plist file. Xcode still can't find 'info.plist'.

NOTE I wanted to add that this was for Xcode 6.2.X (I can't remember which version number exactly, but it was pre-Xcode 6.3.X).

答:
Search "info.plist" using ctrl+sht+f in your project.

Tap on the results and you will find it as a field under Build Settings.

Ensure that it contains the correct path to your info.plist file as in the project hierarchy.


问:
How to define a sub-module in Python?
Python has a module named "os". It also has some other module named "os.path" which is categorized under the "os".

I can use "os.path" methods even if only import the "os" module.

```<code>import os

print(os.path.join("sdfs","x"))
</code>```

I wonder how can I define a sub-module like this?

答:
That's the __init__.py 'magic' of the os module - it imports its submodule path to its namespace, essentially giving you a way to access the latter even if you only import os.

```<code>os
|- path
   |- __init.__.py    # 2
|- __init__.py        # 1
</code>```

The first __init__.py (#1) essentially has import .path so whenever you import just os, it imports path in its namespace, and therefore you can access it as os.path.

(NOTE: This is not exactly the case with the os module, but that's how to essentially achieve it)

Title: How to define a sub-module in Python?

Body:
Python has a module named "os". It also has some other module named "os.path" which is categorized under the "os".

I can use "os.path" methods even if only import the "os" module.

import os

print(os.path.join("sdfs","x"))

I wonder how can I define a sub-module like this?

Body:
That's the __init__.py 'magic' of the os module - it imports its submodule path to its namespace, essentially giving you a way to access the latter even if you only import os.

os
|- path
   |- __init.__.py    # 2
|- __init__.py        # 1

The first __init__.py (#1) essentially has import .path so whenever you import just os, it imports path in its namespace, and therefore you can access it as os.path.

(NOTE: This is not exactly the case with the os module, but that's how to essentially achieve it)


问:
Redux - Define new state in reducer switch statement with new variable each time?
My reducer looks like this:

```<code>switch (action.type) {
      case "UPDATE_CURRENT_USER":
        let newState = {...state, ...action.payload };
        return newState;
      case "GET_CURRENT_USER":
        return state;
      case "UPDATE_USERNAME":
        newState = {...state, name: action.payload.name};
        return state;
  }
</code>```

Now, the second time I am using newState I am not defining it again. I am simply using the variable I have defined above. Is this ok?
I wanted to define it anew, but got an error. But I am not sure whether this way will still give me the correct result - although everything seems to be working fine?

答:
Use curly braces {} to create new block scope inside of the case statement:

```<code>switch (action.type) {
  case "UPDATE_CURRENT_USER": {
    let newState = {...state, ...action.payload };
    return newState;
  }
  case "GET_CURRENT_USER":
    return state;
  case "UPDATE_USERNAME": {
    let newState = {...state, name: action.payload.name};
    return newState;
  }
}
</code>```

Since let and const are block scoped local variables, they are visible only in the current block.

I your code you are using undeclared newState variable:

```<code>switch (action.type) {
  case "UPDATE_CURRENT_USER":
    // (conditionaly) declaring block scoped variable newState
    let newState = {...state, ...action.payload };
    return newState;
  case "UPDATE_USERNAME":
    // here you cannot declare newState variable because it might be declared before
    // however the variable is not declared since we are in other case
    // so that here you are using global window variable window.newState
    newState = {...state, name: action.payload.name};
    return state;
}
</code>```

Body:
My reducer looks like this:

switch (action.type) {
      case "UPDATE_CURRENT_USER":
        let newState = {...state, ...action.payload };
        return newState;
      case "GET_CURRENT_USER":
        return state;
      case "UPDATE_USERNAME":
        newState = {...state, name: action.payload.name};
        return state;
  }

Now, the second time I am using newState I am not defining it again. I am simply using the variable I have defined above. Is this ok?
I wanted to define it anew, but got an error. But I am not sure whether this way will still give me the correct result - although everything seems to be working fine?

Body:
Use curly braces {} to create new block scope inside of the case statement:

switch (action.type) {
  case "UPDATE_CURRENT_USER": {
    let newState = {...state, ...action.payload };
    return newState;
  }
  case "GET_CURRENT_USER":
    return state;
  case "UPDATE_USERNAME": {
    let newState = {...state, name: action.payload.name};
    return newState;
  }
}

Since let and const are block scoped local variables, they are visible only in the current block.

I your code you are using undeclared newState variable:

switch (action.type) {
  case "UPDATE_CURRENT_USER":
    // (conditionaly) declaring block scoped variable newState
    let newState = {...state, ...action.payload };
    return newState;
  case "UPDATE_USERNAME":
    // here you cannot declare newState variable because it might be declared before
    // however the variable is not declared since we are in other case
    // so that here you are using global window variable window.newState
    newState = {...state, name: action.payload.name};
    return state;
}


问:
Heroku don't create table on postgresql
I have problem with creating table on database, when start app I get this exception

```<code>There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
</code>```

and after that I check my database with heroku pg:info and see that I don't have tables

```<code>Plan:        Hobby-dev
Status:      Available
Connections: 10/20
PG Version:  9.6.2
Created:     2017-05-31 10:35 UTC
Data Size:   7.2 MB
Tables:      0
Rows:        0/10000 (In compliance)
Fork/Follow: Unsupported
Rollback:    Unsupported
</code>```

I use Spring Boot and my application.properties

```<code>spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.maxActive=10
spring.datasource.maxIdle=5
spring.datasource.minIdle=2
spring.datasource.initialSize=5
spring.datasource.removeAbandoned=true
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
</code>```

I am using ORM, and one of my class look like:

```<code>@Entity
@Table(name = "MINUSUSER")
public class User extends AbstractBaseEntity {

    @NotNull
    @Column(name = "USERNAME", unique = true)
    private String username;

    @NotNull
    @Column(name = "PASSWORD")
    private String password;

    @NotNull
    @Column(name = "EMAIL", unique = true)
    private String email;

    @NotNull
    @Column(name = "FIRSTNAME")
    private String firstname;

    @NotNull
    @Column(name = "LASTNAME")
    private String lastname;

    @Column(name = "IMAGE")
    private String image;

    //get
    //set
}
</code>```

pom.xml

```<code><packaging>jar</packaging>

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4.1208</version>
</dependency>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.heroku.sdk</groupId>
            <artifactId>heroku-maven-plugin</artifactId>
            <version>1.0.0</version>
        </plugin>
    </plugins>
</build>
</code>```

When I run app on local everything work ok.

答: I start application in eclipse with database params and create tables, after that I deploy my app to heroku.</p>

Title: Heroku don't create table on postgresql

Body:
I have problem with creating table on database, when start app I get this exception

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet

and after that I check my database with heroku pg:info and see that I don't have tables

Plan:        Hobby-dev
Status:      Available
Connections: 10/20
PG Version:  9.6.2
Created:     2017-05-31 10:35 UTC
Data Size:   7.2 MB
Tables:      0
Rows:        0/10000 (In compliance)
Fork/Follow: Unsupported
Rollback:    Unsupported

I use Spring Boot and my application.properties

spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.maxActive=10
spring.datasource.maxIdle=5
spring.datasource.minIdle=2
spring.datasource.initialSize=5
spring.datasource.removeAbandoned=true
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

I am using ORM, and one of my class look like:

@Entity
@Table(name = "MINUSUSER")
public class User extends AbstractBaseEntity {

    @NotNull
    @Column(name = "USERNAME", unique = true)
    private String username;

    @NotNull
    @Column(name = "PASSWORD")
    private String password;

    @NotNull
    @Column(name = "EMAIL", unique = true)
    private String email;

    @NotNull
    @Column(name = "FIRSTNAME")
    private String firstname;

    @NotNull
    @Column(name = "LASTNAME")
    private String lastname;

    @Column(name = "IMAGE")
    private String image;

    //get
    //set
}

pom.xml

<packaging>jar</packaging>

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4.1208</version>
</dependency>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.heroku.sdk</groupId>
            <artifactId>heroku-maven-plugin</artifactId>
            <version>1.0.0</version>
        </plugin>
    </plugins>
</build>

When I run app on local everything work ok.


问:
How can I render these Bootstrap 3 panels inline?
Here's the Bootply

How can i render these panels tp be inline? I don't see what I'm missing here, i have a container, I have a row, I have the col-md-4 nested within the row?

For context, each of those panels is written in a '_quotes.html.erb' partial, which is rendered by a Quotes.all.each block within the  'index.html.erb' view.

index.html.erb

```<code><div class="container">
<div class="row">
        <% @quotes.each do |quote| %>
          <%= render :partial => "quote", locals: {quote: quote} %>
        <% end %>
</div>
</code>```

_quote.html.erb

```<code>    <% @quote = local_assigns[:quote] %>
<%= link_to quote_path(@quote) do %>
    <section id="quotes">
        <!-- <div class="container"> -->
        <div class="col-md-4 col-md-4 col-md-4 text-center">
            <div class="panel panel-success panel-quote link-panel">
            <div class="panel-heading">
              <strong>GLA</strong>
            </div>
            <div class="panel-body">
               <p><strong>Quote ID; <%= @quote.id %></strong></p>
            </div>

            <table class="table table-bordered">
              <tr>
                <td>Company name</td>
                <td><%= @quote.co_name %></td>
              </tr>
              <tr>
                <td>Company number</td>
                <td><%= @quote.co_number %></td>
              </tr>
              <tr>
                <td>Office postcode</td>
                <td><%= @quote.postcode %></td>
              </tr>
              <tr>
                <td>Industry</td>
                <td><%= @quote.industry %></td>
              </tr>
              <tr>
                <td>Previous cover</td>
                <td><%= @quote.prev_cover %></td>
              </tr>
              <tr>
                <td>Lives overseas</td>
                <td><%= @quote.lives_overseas %></td>
              </tr>
              <tr>
                <td>Scheme start date</td>
                <td><%= @quote.scheme_start_date %></td>
              </tr>
              <tr>
                <td>Payment frequency</td>
                <td><%= @quote.payment_frequency %></td>
              </tr>
              <tr>
                <td>Commission level</td>
                <td><%= @quote.commission_level %></td>
              </tr>
            </table>
          </div>
        </div>
      <!-- </div> -->
    </section>
  </div>
<% end %>
</code>```

答:
There's a couple of mistakes

You have only a single col-md-4 which means all children will fit to that single column.

You have another container div inside your col-md-4 which basicly resets the whole thing and again a single col-md-4 in there.

Edited Bootply

Body:
Here's the Bootply

How can i render these panels tp be inline? I don't see what I'm missing here, i have a container, I have a row, I have the col-md-4 nested within the row?

For context, each of those panels is written in a '_quotes.html.erb' partial, which is rendered by a Quotes.all.each block within the  'index.html.erb' view.

index.html.erb

        <% @quotes.each do |quote| %>
          <%= render :partial => "quote", locals: {quote: quote} %>
        <% end %>

_quote.html.erb

    <% @quote = local_assigns[:quote] %>
<%= link_to quote_path(@quote) do %>

              GLA

Quote ID; <%= @quote.id %>

                Company name
                <%= @quote.co_name %>

                Company number
                <%= @quote.co_number %>

                Office postcode
                <%= @quote.postcode %>

                Industry
                <%= @quote.industry %>

                Previous cover
                <%= @quote.prev_cover %>

                Lives overseas
                <%= @quote.lives_overseas %>

                Scheme start date
                <%= @quote.scheme_start_date %>

                Payment frequency
                <%= @quote.payment_frequency %>

                Commission level
                <%= @quote.commission_level %>

<% end %>


问:
Sending an array as a server tag's property
I am wondering if it's possible to send an array of strings to a tag's property

```<code><SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>
</code>```

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

答:
You may have to add attributes to your property but you should be able to continue using the xml side to perform the assignment:

```<code><SampleTag:Form
  runat="server"
  ID="sampleform1">

    <Items ID="item1">item1</Items>
    <Items ID="item2">item2</Items>
    <Items ID="item3">item3</Items>
    <Items ID="item4">item4</Items>

</SampleTag>
</code>```

This article might provide some extra insight: http://msdn.microsoft.com/en-us/library/aa478964.aspx

Body:
I am wondering if it's possible to send an array of strings to a tag's property

<SampleTag:Form
  runat="server"
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.

Body:
You may have to add attributes to your property but you should be able to continue using the xml side to perform the assignment:

<SampleTag:Form
  runat="server"
  ID="sampleform1">

    <Items ID="item1">item1</Items>
    <Items ID="item2">item2</Items>
    <Items ID="item3">item3</Items>
    <Items ID="item4">item4</Items>

</SampleTag>

This article might provide some extra insight: http://msdn.microsoft.com/en-us/library/aa478964.aspx


问:
i want to search using invoice number
I'd like to search using invoice number but it's give an error in Invoice no how to solve it. here is my filter method & error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase(java.util.Locale)' on a null object reference

```<code>public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
billmod.clear();
if (charText.length() == 0) {
    billmod.addAll(arraylist);

} else {
    for (BillModel st : arraylist) {
        if (st.getBill_tableno().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);

        }
        else if(st.getBill_date().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);

        } else if(st.getBill_amount().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);
        }
        else if(st.getIncvoice_no().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);
        }

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

答:
It seems some Strings are null, probably in your locale reference to BillModel in the for loop.

Make sure the data inside this variable is not null before doing any operations on it.

Title: i want to search using invoice number

Body:
I'd like to search using invoice number but it's give an error in Invoice no how to solve it. here is my filter method & error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase(java.util.Locale)' on a null object reference

public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
billmod.clear();
if (charText.length() == 0) {
    billmod.addAll(arraylist);

} else {
    for (BillModel st : arraylist) {
        if (st.getBill_tableno().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);

        }
        else if(st.getBill_date().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);

        } else if(st.getBill_amount().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);
        }
        else if(st.getIncvoice_no().toLowerCase(Locale.getDefault()).contains(charText)) {
            billmod.add(st);
        }

    }
}
notifyDataSetChanged();
}


问:
How does this program work. Im rookie in programming so please explain it in simplified way
please explain to me how program output</p>

```
a noise
annoy
an oyester
```

```<code>while ( x < 4 ) {
    System.out.print("a");
    if ( x < 1 ) {
        System.out.print(" ");
    }
    System.out.print("n");
    if (x> 1 ) {
        System.out.print(" oyster");
        x = x + 2;
    }
    if ( x == 1 ) {
        System.out.print("noys");
    }
    if ( x < 1 ) {
        System.out.print("oise");
    }
    System.out.println("");
    x = x + 1;
</code>```

答:
So, the first line is a while-loop it keeps evaluating the statements in between the {} brackets if the condition x<4 is fulfilled.

```<code>   while ( x < 4 ) {
</code>```

Let's assume x = 0

x<4 is a true statement so we enter the brackets:

System.out.print("a"); will print 'a'

the next line if ( x < 1 ) {  is an if statement, it will evaluate the code in the brackets once if the condition (x < 1) is fulfilled. Because x is 0 at this point the condition is true.

`System.out.print(" "); this will print a space

System.out.print("n"); this line in not in the brackets of the if-statement so it will also print.

if (x> 1 ) { x is 0 at this point so the condition is false and the program will skip everything in between these brackets

if ( x == 1 ) { this condition is also false because x is 0 so the program will skip everything in between these brackets

if ( x < 1 ) { this condition is true and `System.out.print("oise")`` prints "oise"

System.out.println(""); starts a new line

x = x + 1; the x variable is incremented by one: new x = 0 + 1 = 1

So the first iteration of the while statement yields:

a noise

For the second iteration of the while loop:

x is 1 and we follow the logic sequence again:

while ( x < 4 ) { this is true so we enter the brackets

System.out.print("a"); a is printed

if ( x < 1 ) { this statement is false, so next line is skipped

System.out.print("n"); n is printed

if ( x < 1 ) { this statement is false, so next line is skipped

if (x> 1 ) { this statement is false, so next two lines are skipped

if ( x == 1 ) { this is true

System.out.print("noys"); noys is printed

the next if-statement is also false

System.out.println(""); a new line is started

x = x + 1; and x is incremented

So the second iteration of the while-statement yields:

annoy

I think it is a good exercise now for you to try and figure out what happens in the next iteration of the while-loop.

Body:
please explain to me how program output

a noise
annoy
an oyester

while ( x < 4 ) {
    System.out.print("a");
    if ( x < 1 ) {
        System.out.print(" ");
    }
    System.out.print("n");
    if (x> 1 ) {
        System.out.print(" oyster");
        x = x + 2;
    }
    if ( x == 1 ) {
        System.out.print("noys");
    }
    if ( x < 1 ) {
        System.out.print("oise");
    }
    System.out.println("");
    x = x + 1;

Body:
So, the first line is a while-loop it keeps evaluating the statements in between the {} brackets if the condition x<4 is fulfilled.

   while ( x < 4 ) {

Let's assume x = 0

x<4 is a true statement so we enter the brackets:

System.out.print("a"); will print 'a'

the next line if ( x < 1 ) {  is an if statement, it will evaluate the code in the brackets once if the condition (x < 1) is fulfilled. Because x is 0 at this point the condition is true.

`System.out.print(" "); this will print a space

System.out.print("n"); this line in not in the brackets of the if-statement so it will also print.

if (x> 1 ) { x is 0 at this point so the condition is false and the program will skip everything in between these brackets

if ( x == 1 ) { this condition is also false because x is 0 so the program will skip everything in between these brackets

if ( x < 1 ) { this condition is true and `System.out.print("oise")`` prints "oise"

System.out.println(""); starts a new line

x = x + 1; the x variable is incremented by one: new x = 0 + 1 = 1

So the first iteration of the while statement yields:

a noise

For the second iteration of the while loop:

x is 1 and we follow the logic sequence again:

while ( x < 4 ) { this is true so we enter the brackets

System.out.print("a"); a is printed

if ( x < 1 ) { this statement is false, so next line is skipped

System.out.print("n"); n is printed

if ( x < 1 ) { this statement is false, so next line is skipped

if (x> 1 ) { this statement is false, so next two lines are skipped

if ( x == 1 ) { this is true

System.out.print("noys"); noys is printed

the next if-statement is also false

System.out.println(""); a new line is started

x = x + 1; and x is incremented

So the second iteration of the while-statement yields:

annoy

I think it is a good exercise now for you to try and figure out what happens in the next iteration of the while-loop.


问:
Issues running Airflow DAG
I have been working on Apache Airflow for a while now to schedule my workflow. I seem to be having issues scheduling my DAG. I have been using this SO question for reference : Airflow not scheduling Correctly Python

```<code>from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
from datetime import timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
'start_date': datetime.now() - timedelta(minutes=5),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}

 dag = DAG('dag_mkdir_folder', default_args=default_args,
      schedule_interval=timedelta(minutes=5))

 task_hello = BashOperator(task_id='print_hello',
                      bash_command='mkdir test_airflow', dag=dag)
</code>```

I'm trying to run the task using the following list of commands :

```<code> airflow scheduler
 airflow trigger_dag dag_mkdir_folder
</code>```

I keep getting this as an error :

```
[2017-05-15 13:49:06,688] {models.py:322} DagFileProcessor406 INFO -      Finding 'running' jobs without a recent heartbeat
[2017-05-15 13:49:06,689] {models.py:328} DagFileProcessor406 INFO -   Failing jobs without heartbeat after 2017-05-15 13:44:06.689284
```

The bash command is just supposed to create a new directory. The test version works fine.

答:
Run the scheduler on a different terminal and then trigger your dag in another terminal

also try providing your full path where you want to make the directory.
For example creating folder in the airflow directory:

```<code>task_hello = BashOperator(task_id='print_hello',
                  bash_command="mkdir ~/airflow/test_airflow", dag=dag)
</code>```

This should create test_airflow folder inside airflow

Title: Issues running Airflow DAG

Body:
I have been working on Apache Airflow for a while now to schedule my workflow. I seem to be having issues scheduling my DAG. I have been using this SO question for reference : Airflow not scheduling Correctly Python

from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
from datetime import timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
'start_date': datetime.now() - timedelta(minutes=5),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}

 dag = DAG('dag_mkdir_folder', default_args=default_args,
      schedule_interval=timedelta(minutes=5))

 task_hello = BashOperator(task_id='print_hello',
                      bash_command='mkdir test_airflow', dag=dag)

I'm trying to run the task using the following list of commands :

 airflow scheduler
 airflow trigger_dag dag_mkdir_folder

I keep getting this as an error :

[2017-05-15 13:49:06,688] {models.py:322} DagFileProcessor406 INFO -      Finding 'running' jobs without a recent heartbeat
[2017-05-15 13:49:06,689] {models.py:328} DagFileProcessor406 INFO -   Failing jobs without heartbeat after 2017-05-15 13:44:06.689284

The bash command is just supposed to create a new directory. The test version works fine.

Body:
Run the scheduler on a different terminal and then trigger your dag in another terminal

also try providing your full path where you want to make the directory.
For example creating folder in the airflow directory:

task_hello = BashOperator(task_id='print_hello',
                  bash_command="mkdir ~/airflow/test_airflow", dag=dag)

This should create test_airflow folder inside airflow


问:
Circle line-segment collision detection algorithm?
I have a line from A to B and a circle positioned at C with the radius R.

What is a good algorithm to use to check whether the line intersects the circle? And at what coordinate along the circles edge it occurred?

答:
Here is good solution in JavaScript (with all required mathematics and live illustration)
https://bl.ocks.org/milkbread/11000965

Though is_on function in that solution needs modifications:

function is_on(a, b, c) {
    return Math.abs(distance(a,c) + distance(c,b) - distance(a,b))<0.000001;
}```


问:
How to use UnitOfWorkAwareProxyFactory in Dropwizard v1.1.0
I need to call DAO methods outside resource in dropwizard.
Looking at the manual Im unclear how to use it. The manual says

```<code>SessionDao dao = new SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new
    UnitOfWorkAwareProxyFactory(hibernateBundle)
           .create(ExampleAuthenticator.class, SessionDao.class, dao);
</code>```

Can anyone show me the usage of exampleAuthenticator methods which call DAO.

Thanks, Kedar

答:
Working solution

```<code>/** initializing proxy dao for authorization */
AuthenticatorDAOProxy authenticatorDAOProxy = new UnitOfWorkAwareProxyFactory(hibernateBundle)
            .create(AuthenticatorDAOProxy.class, DeviceDAO.class, deviceDAO);
</code>```

We can now use authenticatorDAOProxy outside jersey resources

One thing to note., AuthenticatorDAOProxy should have a constructor accepting DeviceDAO

Now your proxyDao will look like

```<code>public class AuthenticatorDAOProxy {

  private DeviceDAO deviceDAO;

  public AuthenticatorDAOProxy(DeviceDAO deviceDAO) {
    this.deviceDAO = deviceDAO;
  }

  @UnitOfWork
  public Boolean checkIsDeviceValid(String deviceId, User user) {
    Device device = deviceDAO.getByDeviceIdAndUser(deviceId, user);
    if (device != null && device.getIsActive() == true) {
        return true;
    }
    return false;
  }
}
</code>```

Body:
I need to call DAO methods outside resource in dropwizard.
Looking at the manual Im unclear how to use it. The manual says

SessionDao dao = new SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new
    UnitOfWorkAwareProxyFactory(hibernateBundle)
           .create(ExampleAuthenticator.class, SessionDao.class, dao);

Can anyone show me the usage of exampleAuthenticator methods which call DAO.

Thanks, Kedar

Body:
Working solution

/** initializing proxy dao for authorization */
AuthenticatorDAOProxy authenticatorDAOProxy = new UnitOfWorkAwareProxyFactory(hibernateBundle)
            .create(AuthenticatorDAOProxy.class, DeviceDAO.class, deviceDAO);

We can now use authenticatorDAOProxy outside jersey resources

One thing to note., AuthenticatorDAOProxy should have a constructor accepting DeviceDAO

Now your proxyDao will look like

public class AuthenticatorDAOProxy {

  private DeviceDAO deviceDAO;

  public AuthenticatorDAOProxy(DeviceDAO deviceDAO) {
    this.deviceDAO = deviceDAO;
  }

  @UnitOfWork
  public Boolean checkIsDeviceValid(String deviceId, User user) {
    Device device = deviceDAO.getByDeviceIdAndUser(deviceId, user);
    if (device != null && device.getIsActive() == true) {
        return true;
    }
    return false;
  }
}


问:
How do I get one column with one row and one column with two rows nested in HTML/CSS
I'm looking for the easiest way to get a icon on the left vertical aligned with the two lines of text on the right.

What I'm struggling with is the way I have to organize my HTML. I can functionally build this, but I think it's not efficient/clean the way I do this (too much code). So any advice on how this problem can be tackled is highly appreciated :). A screenshot from what I want to achieve is below. I'm using Font Awesome and Bootstrap 3 for development.

Screenshot of what I want to achieve

答:
.box{padding:10px; background:#7cc5ef;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container">
<h1>Contact Address</h1><br>
 <div class="row text-center">

  <table class="col-sm-3 col-xs-6 box">
          <tr >
             <th class="glyphicon glyphicon-earphone" style="font-size:30px;"></th>
             <td> <b>Phone</b></td>
             </tr>
             <tr>
             <td></td>
             <td> +01-009940-998569></td>
         </tr>

               <tr >
             <th class="glyphicon glyphicon-home" style="font-size:30px;"></th>
             <td> <b>Location</b></td>
             </tr>
             <tr>
             <td></td>
             <td> 6th Sun Road</td>
         </tr>
               <tr >
             <th class="glyphicon glyphicon-send" style="font-size:30px;"></th>
             <td> <b>E-mail</b></td>
             </tr>
             <tr>
             <td></td>
             <td> info@sun.com</td>
         </tr>
               <tr >
             <th class="glyphicon glyphicon-leaf" style="font-size:30px;"></th>
             <td> <b>Web</b></td>
             </tr>
             <tr>
             <td></td>
             <td> me@me.com</td>
         </tr>

        </table>
        </div>
</div></code>```

Body:
.box{padding:10px; background:#7cc5ef;}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container">
<h1>Contact Address</h1><br>
 <div class="row text-center">

  <table class="col-sm-3 col-xs-6 box">
          <tr >
             <th class="glyphicon glyphicon-earphone" style="font-size:30px;"></th>
             <td> <b>Phone</b></td>
             </tr>
             <tr>
             <td></td>
             <td> +01-009940-998569></td>
         </tr>

               <tr >
             <th class="glyphicon glyphicon-home" style="font-size:30px;"></th>
             <td> <b>Location</b></td>
             </tr>
             <tr>
             <td></td>
             <td> 6th Sun Road</td>
         </tr>
               <tr >
             <th class="glyphicon glyphicon-send" style="font-size:30px;"></th>
             <td> <b>E-mail</b></td>
             </tr>
             <tr>
             <td></td>
             <td> info@sun.com</td>
         </tr>
               <tr >
             <th class="glyphicon glyphicon-leaf" style="font-size:30px;"></th>
             <td> <b>Web</b></td>
             </tr>
             <tr>
             <td></td>
             <td> me@me.com</td>
         </tr>

        </table>
        </div>
</div>


问:
Remove Specific LineGeometry in a Path
My application consists of a canvas with some user drag-droppable UIelements which can be further connected using lines.

To connect two UIelements I have used a Path consisting a GeometryGroup, which further contains LineGeometry as its childs. Check this screenshot.

So as in the picture, the three items are connected via a Path which consists of 2 LineGeometry. I'm trying to implement 'Remove Link' option but all i can do is remove the whole Path, which would remove both the LineGeometry. How can i specifically select that particular line segment and remove it?

答:
There is a solution without implementing math for hit testing. For example if you want to remove a line by mouse down:

```<code><Canvas Mouse.MouseDown="Canvas_MouseDown">
</code>```

where Canvas_MouseDown should be implemented like this:

```<code>private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    var canvas = sender as Canvas;
    if (canvas == null)
        return;

    // 1. Find a Path containing links

    HitTestResult hitTestResult = VisualTreeHelper.HitTest(canvas, e.GetPosition(canvas));
    var path = hitTestResult.VisualHit as Path;
    if (path == null)
        return;

    // 2. Iterate through geometries of the Path and hit test each one
    //    to find a line to delete

    var geometryGroup = path.Data as GeometryGroup;
    if (geometryGroup == null)
        return;

    GeometryCollection geometries = geometryGroup.Children;
    Point point = e.GetPosition(path);
    var pen = new Pen(path.Stroke, path.StrokeThickness);

    var lineToDelete = geometries.OfType<LineGeometry>()
                                 .FirstOrDefault(l => l.StrokeContains(pen, point));

    // 3. Delete link

    if (lineToDelete != null)
        geometries.Remove(lineToDelete);
}
</code>```

Title: Remove Specific LineGeometry in a Path

Body:
There is a solution without implementing math for hit testing. For example if you want to remove a line by mouse down:

<Canvas Mouse.MouseDown="Canvas_MouseDown">

where Canvas_MouseDown should be implemented like this:

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    var canvas = sender as Canvas;
    if (canvas == null)
        return;

    // 1. Find a Path containing links

    HitTestResult hitTestResult = VisualTreeHelper.HitTest(canvas, e.GetPosition(canvas));
    var path = hitTestResult.VisualHit as Path;
    if (path == null)
        return;

    // 2. Iterate through geometries of the Path and hit test each one
    //    to find a line to delete

    var geometryGroup = path.Data as GeometryGroup;
    if (geometryGroup == null)
        return;

    GeometryCollection geometries = geometryGroup.Children;
    Point point = e.GetPosition(path);
    var pen = new Pen(path.Stroke, path.StrokeThickness);

    var lineToDelete = geometries.OfType<LineGeometry>()
                                 .FirstOrDefault(l => l.StrokeContains(pen, point));

    // 3. Delete link

    if (lineToDelete != null)
        geometries.Remove(lineToDelete);
}


问:
QProgressbar shows also busy mode while percentage is showing?
QProgressBar works either as busy mode or percentage mode.

But i want to show the both!

In my application sometimes(not always) it takes too long time for just a 1 percent change.

So i want to show some kind of busy indicator effect while showing percentage.

how can i do this? do you have any idea?

答:
you can change your mouse cursor using :

```<code>QApplication::setOverrideCursor(Qt::WaitCursor);
</code>```

but don't forget to restore the old one, once you're done

```<code>QApplication::restoreOverrideCursor();
</code>```

or you can add a second progressbar with more precision

Body:
you can change your mouse cursor using :

QApplication::setOverrideCursor(Qt::WaitCursor);

but don't forget to restore the old one, once you're done

QApplication::restoreOverrideCursor();

or you can add a second progressbar with more precision


问:
Send raw ZPL to Zebra printer via USB
Typically, when I plug in my Zebra LP 2844-Z to the USB port, the computer sees it as a printer and I can print to it from notepad like any other generic printer. However, my application has some bar code features. My application parses some input and generates an in-memory string of ZPL. How would I send this ZPL data to my USB device?</p>

答:
You haven't mentioned a language, so I'm going to give you some some hints how to do it with the straight Windows API in C.

First, open a connection to the printer with OpenPrinter. Next, start a document with StartDocPrinter having the pDatatype field of the DOC_INFO_1 structure set to "RAW" - this tells the printer driver not to encode anything going to the printer, but to pass it along unchanged. Use StartPagePrinter to indicate the first page, WritePrinter to send the data to the printer, and close it with EndPagePrinter, EndDocPrinter and ClosePrinter when done.

Title: Send raw ZPL to Zebra printer via USB


问:
Excel VBA - loop over files in folder, copy range, paste in this workbook
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

```<code>Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub
</code>```

答:
I see you already added a long variable for this, so do a lookup on the last row before you paste. Also, paste in a single cell in case of varying amounts of data.

I altered your script as follows.

```<code>Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

 'Just add this line:
  lastrow = sht1.Range("b1").End(xlDown).Row + 1
 'And alter this one as follows:
  sht1.Range("B" & lastrow).PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub
</code>```

Body:
I have 500 excel files with data. I would merge all this data into one file.

Task list to achieve this:

I want to loop over all the files in a folder

open the file,

copy this range "B3:I102"

paste it into the 1st sheet of the active workbook

repeat but paste new data underneath

I've done task 1-4 but i need help with task 5, last bit - pasting the data under the existing data and making it dynamic. I've highlighted this bit with '#### in my code.

Here is my code which I've put together from other people's question :)

Any suggestions on how to do this?

Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

  '################################
  'NEED HELP HERE. I GET A ERROR HERE. NEEDS TO BE MORE DYNAMIC.
  sht1.Range("b1:i100").PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub

Body:
I see you already added a long variable for this, so do a lookup on the last row before you paste. Also, paste in a single cell in case of varying amounts of data.

I altered your script as follows.

Sub LoopThroughFiles()
Dim MyObj As Object,
MySource As Object,
file As Variant
Dim wbThis                  As Workbook     'workbook where the data is to be pasted, aka Master file
Dim wbTarget                As Workbook     'workbook from where the data is to be copied from, aka Overnights file
Dim LastRow As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

'set to the current active workbook (the source book, the Master!)
Set wbThis = ActiveWorkbook
Set sht1 = wbThis.Sheets("Sheet1")

Folder = "\\dne\ldc\research-dept\3 CEEMEA\15. EMB\Turkey\TLC Overnight & Weekly Reports\weekly (majeed)\"
Fname = Dir(Folder)

While (Fname <> "")

  Set wbTarget = Workbooks.Open(Filename:=Folder & Fname)
  wbTarget.Activate
  Range("b3:i102").Copy

  wbThis.Activate

 'Just add this line:
  lastrow = sht1.Range("b1").End(xlDown).Row + 1
 'And alter this one as follows:
  sht1.Range("B" & lastrow).PasteSpecial

 Fname = Dir

 'close the overnight's file
  wbTarget.Close
 Wend

End Sub


问:
create a display alert function globally and call it from any view controller
```<code>func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())
</code>```

<p>it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is. </p>

答:
Swift 4

Create an extension of UIViewController with your function to display alert with required parameter arguments

```<code>extension UIViewController {

      func displayalert(title:String, message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

            alert.dismiss(animated: true, completion: nil)

        })))

        self.present(alert, animated: true, completion: nil)

      }
}
</code>```

Now call this function from your view controller:

```<code>class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.displayalert(title: <String>, message: <String>)
    }
}
</code>```

Body:
func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)

}

this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())

it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is.

Body:
Swift 4

Create an extension of UIViewController with your function to display alert with required parameter arguments

extension UIViewController {

      func displayalert(title:String, message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

            alert.dismiss(animated: true, completion: nil)

        })))

        self.present(alert, animated: true, completion: nil)

      }
}

Now call this function from your view controller:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.displayalert(title: <String>, message: <String>)
    }
}


问:
How can I get the Last Successful Build time and Last Failed Build time Jenkins
Using the XML API, how can I construct the query string parameters to get the Last Successful Build time and Last Failed Build time for all jobs?

I have "/api/xml?tree=jobs[name,color]" but need these 2 additional field so I can get an overall status of all jobs on the server.

答:
you can get it by calling Jenkins server with path:</p>

```<code>/job/[job name]/lastSuccessfulBuild/

/job/[job name]/lastFailedBuild/
</code>```

Body:
you can get it by calling Jenkins server with path:

/job/[job name]/lastSuccessfulBuild/

/job/[job name]/lastFailedBuild/


问:
How to disable top left arrow '<-' on Android Wi-Fi settings screen?
I open the WiFi settings page from my Android application with:

startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));

Here I want to disable the left arrow at the top of the WiFi settings to avoid, that the user could enter all the other settings. It would be even better if the arrow could be used to finish the settings page.

Is this possible?

Thanks!

答:
I think that this is what you need:

startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

On my Xiaomi phone there is back navigation button in WIFI settings but that opens your application again not all settings menu.


问:
Haskel ghci.exe error (0xc0000142)
I tried all versions of haskell from their website and installed them on my windows 10 computer but when i run ghc.exe i get the following error shown in the image:

I have tried several troubleshooting techniques but i cannot find the problem. Note that i have installed the files inside c:/ path

答: Run the program named "WinGHCi", not "GHCi".</p>

Title: Haskel ghci.exe error (0xc0000142)


问:
Why is Scala promoting List[Any] to List[Long]?
In the following code:

```<code>def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))
</code>```

here is the output (Scala 2.8.1):

```<code>0: java.lang.Long
1: java.lang.Long
2: java.lang.Long
</code>```

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?

答:
```<code>List[Any](0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short])
</code>```

Body:
In the following code:

def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))

here is the output (Scala 2.8.1):

0: java.lang.Long
1: java.lang.Long
2: java.lang.Long

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?


问:
Bootstrap accordion with arrow glyphs Changing bg color and arrow color after click
I have my accordion and I would like to:

after click in the arrow:

change the bg color of the panel from grey to red.
change the color of the arrow from grey to blue.

if not clicked  the panel the colour should back to the normal one: grey.

jsfiddle: https://jsfiddle.net/4x7y14wj/1/

css:

```<code>.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}
</code>```

html:

```<code><div class="container">

  <div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
  </div>

</div>
<!-- end container -->

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</code>```

答:
hi add the following css code -- pure css way to achive

```<code>.panel-heading
{
  padding:0px;
}
.panel-title a
{
  padding:10px;
  display:block;
}
.panel-title a[aria-expanded='true']
{
  background-color: red;
  color:#fff;
}
.panel-title a[aria-expanded='true']::after
{
  color:blue;
}
</code>```

hope it works..

Body:
I have my accordion and I would like to:

after click in the arrow:

change the bg color of the panel from grey to red.
change the color of the arrow from grey to blue.

if not clicked  the panel the colour should back to the normal one: grey.

jsfiddle: https://jsfiddle.net/4x7y14wj/1/

css:

.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}

html:

          Collapsible Group Item #1

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #2

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #3

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Body:
hi add the following css code -- pure css way to achive

.panel-heading
{
  padding:0px;
}
.panel-title a
{
  padding:10px;
  display:block;
}
.panel-title a[aria-expanded='true']
{
  background-color: red;
  color:#fff;
}
.panel-title a[aria-expanded='true']::after
{
  color:blue;
}

hope it works..


问:
osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0)))
I have generated this project with maven

```<code>mvn archetype:generate
-DarchetypeGroupId=org.apache.servicemix.tooling
-DarchetypeArtifactId=servicemix-cxf-code-first-osgi-bundle
-DarchetypeVersion=2012.01.0.redhat-60024
-DgroupId=org.fusesource.example
-DartifactId=cxf-basic
-Dversion=1.0-SNAPSHOT
</code>```

created the boundle and trying to install and start it to Jboss Fuse I getting the Error

```<code>Error executing command: Error installing bundles:
Unable to start bundle mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT: Unresolved constraint in bundle cxf-basic [363]: Unable to resolve 363.0: missing requirement [363.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0)))
</code>```

I have already tried to change the version of

```<code><plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.3.7</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                    <Import-Package>
                        javax.jws,
                        javax.wsdl,
                        javax.xml.bind,
                        javax.xml.bind.annotation,
                        javax.xml.namespace,
                        javax.xml.ws,
                        org.apache.cxf.bus,
                        org.apache.cxf.bus.spring,
                        org.apache.cxf.bus.resource,
                        org.apache.cxf.configuration.spring,
                        org.apache.cxf.resource,
                        org.apache.cxf.jaxws,
                        org.apache.cxf.transport.http,
                        org.springframework.beans.factory.config
                    </Import-Package>
                    <Private-Package>
                        !org.fusesource.example.client,
                        org.fusesource.example,
                        org.fusesource.example.types
                    </Private-Package>
                    <Require-Bundle>org.apache.cxf.bundle</Require-Bundle>
                    <!--
                        <DynamicImport-Package>*</DynamicImport-Package>
                    -->
                </instructions>
            </configuration>
        </plugin>
</code>```

with a new one but when I do it the error change slightly in

```<code>Error executing command: Error installing bundles:
Unable to start bundle mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT: Unresolved constraint in bundle cxf-basic [362]: Unable to resolve 362.0: missing requirement [362.0] osgi.wiring.package; (&(osgi.wiring.package=javax.jws)(version>=2.0.0)(!(version>=3.0.0)))
</code>```

what am I doing wrong?

答:
The package javax.jws is missing. You have to install the lib in your container with the good version (2.0.0).
If it is already the case, and you want to use the version provided, try this: </p>

```<code>                    <Import-Package>
                        javax.jws;version="[1.0.0, 0)",
                        javax.wsdl,
                        javax.xml.bind,
                        javax.xml.bind.annotation,
                        javax.xml.namespace,
                        javax.xml.ws,
                        org.apache.cxf.bus,
                        org.apache.cxf.bus.spring,
                        org.apache.cxf.bus.resource,
                        org.apache.cxf.configuration.spring,
                        org.apache.cxf.resource,
                        org.apache.cxf.jaxws,
                        org.apache.cxf.transport.http,
                        org.springframework.beans.factory.config
                    </Import-Package>
</code>```

Body:
I have generated this project with maven

mvn archetype:generate
-DarchetypeGroupId=org.apache.servicemix.tooling
-DarchetypeArtifactId=servicemix-cxf-code-first-osgi-bundle
-DarchetypeVersion=2012.01.0.redhat-60024
-DgroupId=org.fusesource.example
-DartifactId=cxf-basic
-Dversion=1.0-SNAPSHOT

created the boundle and trying to install and start it to Jboss Fuse I getting the Error

Error executing command: Error installing bundles:
Unable to start bundle mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT: Unresolved constraint in bundle cxf-basic [363]: Unable to resolve 363.0: missing requirement [363.0] osgi.wiring.package; (&(osgi.wiring.package=META-INF.cxf)(version>=2.6.0)(!(version>=3.0.0)))

I have already tried to change the version of

<plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.3.7</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                    <Import-Package>
                        javax.jws,
                        javax.wsdl,
                        javax.xml.bind,
                        javax.xml.bind.annotation,
                        javax.xml.namespace,
                        javax.xml.ws,
                        org.apache.cxf.bus,
                        org.apache.cxf.bus.spring,
                        org.apache.cxf.bus.resource,
                        org.apache.cxf.configuration.spring,
                        org.apache.cxf.resource,
                        org.apache.cxf.jaxws,
                        org.apache.cxf.transport.http,
                        org.springframework.beans.factory.config
                    </Import-Package>
                    <Private-Package>
                        !org.fusesource.example.client,
                        org.fusesource.example,
                        org.fusesource.example.types
                    </Private-Package>
                    <Require-Bundle>org.apache.cxf.bundle</Require-Bundle>

                </instructions>
            </configuration>
        </plugin>

with a new one but when I do it the error change slightly in

Error executing command: Error installing bundles:
Unable to start bundle mvn:org.fusesource.example/cxf-basic/1.0-SNAPSHOT: Unresolved constraint in bundle cxf-basic [362]: Unable to resolve 362.0: missing requirement [362.0] osgi.wiring.package; (&(osgi.wiring.package=javax.jws)(version>=2.0.0)(!(version>=3.0.0)))

what am I doing wrong?

Body:
The package javax.jws is missing. You have to install the lib in your container with the good version (2.0.0).
If it is already the case, and you want to use the version provided, try this:

                    <Import-Package>
                        javax.jws;version="[1.0.0, 0)",
                        javax.wsdl,
                        javax.xml.bind,
                        javax.xml.bind.annotation,
                        javax.xml.namespace,
                        javax.xml.ws,
                        org.apache.cxf.bus,
                        org.apache.cxf.bus.spring,
                        org.apache.cxf.bus.resource,
                        org.apache.cxf.configuration.spring,
                        org.apache.cxf.resource,
                        org.apache.cxf.jaxws,
                        org.apache.cxf.transport.http,
                        org.springframework.beans.factory.config
                    </Import-Package>


问:
SFTP SSHLibrary Unable to Connect
Im unable to connect to SFTP with below script, any ideas why?

```<code>*** Variables ***
${HOST} =  mysite.com
${USERNAME} =  username
${PASSWORD} =  password
${PORT} =  22222
${keyfile} =  /Users/victor/.ssh/

*** Test Cases ***
Open Connec
   Open Connection    stage1.globalcashcard.com  alias=LaborReady  port=22222

Enter Credentials
   Login  ${USERNAME}  ${PASSWORD}
List Dir
    List Directory  /

Close ALL Conns
    Close All Connections
</code>```

Side NTOE:
I Even tried it with

```<code>Login with P. Key
       Login With Public Key  username  /Users/username/.ssh/known_hosts
</code>```

Results log

```<code>Status:
FAIL (critical)
Message:
SSHException: SSH session not active
00:00:00.004
KEYWORD SSHLibrary . List Directory /

Documentation:
Returns and logs items in the remote `path`, optionally filtered with `pattern`.
Start / End / Elapsed:
20170607 14:18:33.338 / 20170607 14:18:33.342 / 00:00:00.004
14:18:33.342
FAIL
SSHException: SSH session not active
</code>```

I'm able to login with Filezilla without any issues. On thing I did notice is that I cannot login via terminal with below command

```<code>ssh username@stg1.mysite.com -p 22222
</code>```

I get prompted to enter password when I enter then I get below message

```<code>shell request failed on channel 0
</code>```

I able able to connect via Terminal with below command

```<code>sftp -o "Port 22222" username@stg1.mysite.com
</code>```

Could this be the issue?

答:
SSH and SFTP are different protocols. That is what you validated with your experiences.

When you use SSHLibrary you can use similar functions you get in SFTP, but not the exact commands.

Title: SFTP SSHLibrary Unable to Connect

Body:
Im unable to connect to SFTP with below script, any ideas why?

*** Variables ***
${HOST} =  mysite.com
${USERNAME} =  username
${PASSWORD} =  password
${PORT} =  22222
${keyfile} =  /Users/victor/.ssh/

*** Test Cases ***
Open Connec
   Open Connection    stage1.globalcashcard.com  alias=LaborReady  port=22222

Enter Credentials
   Login  ${USERNAME}  ${PASSWORD}
List Dir
    List Directory  /

Close ALL Conns
    Close All Connections

Side NTOE:
I Even tried it with

Login with P. Key
       Login With Public Key  username  /Users/username/.ssh/known_hosts

Results log

Status:
FAIL (critical)
Message:
SSHException: SSH session not active
00:00:00.004
KEYWORD SSHLibrary . List Directory /

Documentation:
Returns and logs items in the remote `path`, optionally filtered with `pattern`.
Start / End / Elapsed:
20170607 14:18:33.338 / 20170607 14:18:33.342 / 00:00:00.004
14:18:33.342
FAIL
SSHException: SSH session not active

I'm able to login with Filezilla without any issues. On thing I did notice is that I cannot login via terminal with below command

ssh username@stg1.mysite.com -p 22222

I get prompted to enter password when I enter then I get below message

shell request failed on channel 0

I able able to connect via Terminal with below command

sftp -o "Port 22222" username@stg1.mysite.com

Could this be the issue?