问:
Query Microsoft Azure by Entity Property Value
I want to query the table by property value.  So lets say I have the following table

I want to create a query where I give me all records where
PartitionKey = section3
FirstName = value3
Timestamp : last 12 hrs

I have the following code so far:

```<code>// Retrieve the storage account from the connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString"));

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Create the CloudTable object that represents the "asometrichub" table.
        CloudTable table = tableClient.GetTableReference("customer");

        TableQuery rangeQuery = new TableQuery().Where(
                  TableQuery.CombineFilters(
                      TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "section3"),
                      TableOperators.And,
                      TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.AddHours(-12))));
</code>```

Not sure how I filter on the FirstName=value3.  Thank you!

答:
TableQuery.CombineFilters() can be called in a nested way:

```<code>// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "asometrichub" table.
CloudTable table = tableClient.GetTableReference("customer");

string combinedFilter = TableQuery.CombineFilters(
    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "section3"),
    TableOperators.And,
    TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.AddHours(-12)));

combinedFilter = TableQuery.CombineFilters(
    combinedFilter,
    TableOperators.And,
    TableQuery.GenerateFilterCondition("FirstName", QueryComparisons.Equal, "value3"));

TableQuery rangeQuery = new TableQuery().Where(combinedFilter);
</code>```

Body:
I want to query the table by property value.  So lets say I have the following table

I want to create a query where I give me all records where
PartitionKey = section3
FirstName = value3
Timestamp : last 12 hrs

I have the following code so far:

// Retrieve the storage account from the connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString"));

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Create the CloudTable object that represents the "asometrichub" table.
        CloudTable table = tableClient.GetTableReference("customer");

        TableQuery rangeQuery = new TableQuery().Where(
                  TableQuery.CombineFilters(
                      TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "section3"),
                      TableOperators.And,
                      TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.AddHours(-12))));

Not sure how I filter on the FirstName=value3.  Thank you!

Body:
TableQuery.CombineFilters() can be called in a nested way:

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "asometrichub" table.
CloudTable table = tableClient.GetTableReference("customer");

string combinedFilter = TableQuery.CombineFilters(
    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "section3"),
    TableOperators.And,
    TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.AddHours(-12)));

combinedFilter = TableQuery.CombineFilters(
    combinedFilter,
    TableOperators.And,
    TableQuery.GenerateFilterCondition("FirstName", QueryComparisons.Equal, "value3"));

TableQuery rangeQuery = new TableQuery().Where(combinedFilter);


来源: stackexchange

问:
Android launcher icon has rough edges
So my tablet recently updated to Android 7.1.1, and I noticed that my app's icon looked like hot garbage with the new adaptive icon scheme.  I updated things via Android Studio's Image Asset Studio, and it's better, but I'm noticing the edges of the squared circle look kind of ragged/jagged/rough.  Here's how it looks compared to Twitter and Firefox.  Any suggestions as to how I can get the edges of mine to look as smooth as those?

EDIT: For what it's worth I still see the same rough edges if I use an image or plain color as the background, and they even show up with the stock ic_launcher icon.

答: So it turns out that the image asset tool in Android Studio is creating the problem - it leaves transparent edges around the generated icons.  And then when it's rendered on the device, Android rescales things as a result, which leads to the indistinct edges on the icons.  What worked for me was to go back in and fill in the transparent areas by hand so that the background extends all the way out to the edges of the .png files. </p>

ContentLicense: CC BY-SA 3.0

Title: Android launcher icon has rough edges


问:
Drawing to a BufferedImage sometimes, but consistently, yields wrong colors
I've written a program to modify images.

First, I get the image, and get its drawing context like this:

```<code>BufferedImage image;
try {
    image = ImageIO.read(inputFile);
} catch (IOException ioe) { /* exception handling ... */ }

Graphics g = image.createGraphics();
</code>```

And then I modify the image like this:

```<code>for (int x = 0; x < image.getWidth(); x++) {
    for (int y = 0; y < image.getHeight(); y++) {
        g.setColor( /* calculate color ... */ );
        g.fillRect(x, y, 1, 1);
    }
}
</code>```

After I've finished modifying the image, I save the image like this:

```<code>try {
    ImageIO.write(image, "PNG", save.getSelectedFile());
} catch (IOException ioe) { /* exception handling ... */ }
</code>```

Now most of the time this works just fine.

However, when I tried recoloring this texture

to this

I get this instead:

Inside the debugger, though, the Graphics's color is the shade of pink I want it to be.

The comments seem to suggest that the image the user opens might have some color limitations, and since I'm drawing to the same image I'm reading from, my program has to abide by these limitations. The example image seems to be pretty grayscale-y, and apparently its bit depth is 8 bit. So maybe the pink I'm drawing on it is converted to grayscale, because the image has to stay 8-bit?

答:
As suggested in the comments, the main problem here indeed is the wrong color model. When you load the original image, and print some information about it...

```<code>BufferedImage image = ImageIO.read(
    new URL("https://i.stack.imgur.com/pSUFR.png"));
System.out.println(image);
</code>```

it will say

```<code>BufferedImage@5419f379: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@7dc7cbad transparency = 1 transIndex   = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 128 height = 128 #numDataElements 1 dataOff[0] = 0
</code>```

The IndexColorModel does not necessarily support all the colors, but only a subset of them. (Basically, the image supports only the colors that it "needs", which allows for a more compact storage).

The solution here is to convert the image into one that has the appropriate color model. A generic method for this is shown in the following example:

```<code>import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class ImageColors
{
    public static void main(String[] args) throws IOException
    {
        BufferedImage image = ImageIO.read(
            new URL("https://i.stack.imgur.com/pSUFR.png"));

        // This will show that the image has an IndexColorModel.
        // This does not necessarily support all colors.
        System.out.println(image);

        // Convert the image to a generic ARGB image
        image = convertToARGB(image);

        // Now, the image has a DirectColorModel, supporting all colors
        System.out.println(image);

        Graphics2D g = image.createGraphics();
        g.setColor(Color.PINK);
        g.fillRect(50, 50, 50, 50);
        g.dispose();

        ImageIO.write(image, "PNG", new File("RightColors.png"));
    }

    public static BufferedImage convertToARGB(BufferedImage image)
    {
        BufferedImage newImage = new BufferedImage(
            image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = newImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return newImage;
    }
}
</code>```

Body:
I've written a program to modify images.

First, I get the image, and get its drawing context like this:

BufferedImage image;
try {
    image = ImageIO.read(inputFile);
} catch (IOException ioe) { /* exception handling ... */ }

Graphics g = image.createGraphics();

And then I modify the image like this:

for (int x = 0; x < image.getWidth(); x++) {
    for (int y = 0; y < image.getHeight(); y++) {
        g.setColor( /* calculate color ... */ );
        g.fillRect(x, y, 1, 1);
    }
}

After I've finished modifying the image, I save the image like this:

try {
    ImageIO.write(image, "PNG", save.getSelectedFile());
} catch (IOException ioe) { /* exception handling ... */ }

Now most of the time this works just fine.

However, when I tried recoloring this texture

to this

I get this instead:

Inside the debugger, though, the Graphics's color is the shade of pink I want it to be.

The comments seem to suggest that the image the user opens might have some color limitations, and since I'm drawing to the same image I'm reading from, my program has to abide by these limitations. The example image seems to be pretty grayscale-y, and apparently its bit depth is 8 bit. So maybe the pink I'm drawing on it is converted to grayscale, because the image has to stay 8-bit?

Body:
As suggested in the comments, the main problem here indeed is the wrong color model. When you load the original image, and print some information about it...

BufferedImage image = ImageIO.read(
    new URL("https://i.stack.imgur.com/pSUFR.png"));
System.out.println(image);

it will say

BufferedImage@5419f379: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@7dc7cbad transparency = 1 transIndex   = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 128 height = 128 #numDataElements 1 dataOff[0] = 0

The IndexColorModel does not necessarily support all the colors, but only a subset of them. (Basically, the image supports only the colors that it "needs", which allows for a more compact storage).

The solution here is to convert the image into one that has the appropriate color model. A generic method for this is shown in the following example:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class ImageColors
{
    public static void main(String[] args) throws IOException
    {
        BufferedImage image = ImageIO.read(
            new URL("https://i.stack.imgur.com/pSUFR.png"));

        // This will show that the image has an IndexColorModel.
        // This does not necessarily support all colors.
        System.out.println(image);

        // Convert the image to a generic ARGB image
        image = convertToARGB(image);

        // Now, the image has a DirectColorModel, supporting all colors
        System.out.println(image);

        Graphics2D g = image.createGraphics();
        g.setColor(Color.PINK);
        g.fillRect(50, 50, 50, 50);
        g.dispose();

        ImageIO.write(image, "PNG", new File("RightColors.png"));
    }

    public static BufferedImage convertToARGB(BufferedImage image)
    {
        BufferedImage newImage = new BufferedImage(
            image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = newImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return newImage;
    }
}


问:
Time sheet module - Gettimesheetdata subroutine
I have come a long way on this first Access project of mine but presently terribly stuck at this point for over two weeks!

This part is the timesheet module where there is a timesheetform and a timesheetsubform; on the header part of the form there is a combobox where the user picks the week ending (Friday) date. This week ending date is the main criteria for the whole timesheet. Everything till this point seems to be working fine thanks to one of Ms. Fennema’s codes which I was able to adapt.

Once the date is picked on the combobox, I must put a code in its afterupdate event (Gettimesheetdata subroutine), to first check the main table (tblTimeSheetData) if there are any workhours for the 5 weekdays of that week; (maybe through a query on the fly) and if there are, it should put them in the proper fields in the subform through the temp table so that the user can verify that that specific week's timesheet is already complete or make adjustments to it. If there are no records it would mean that this is a new timesheet! In the case that it’s a new timesheet, selecting the projects and entering the hours for the weekdays and save them to main table also seems to work (Writetimesheetdata subroutine below). As you enter the hours per day based on the project, it populates the temp table and a ‘Save the Worksheet’ command button converts the horizontal data to vertical on the main table. I would really appreciate any help to guide me in the right direction on the Gettimesheetdata subroutine.

Thank you.

Here is the code for the Writetimesheetdata subroutine:

```<code>Public Sub WriteTimesheetData()

     Set rstTime = CurrentDb.OpenRecordset("tblTimeSheetData", _
     dbOpenDynaset)
     Set rstTemp = CurrentDb.OpenRecordset("tblTimeSheetDataTemp")

With rstTemp
  .MoveLast
  .MoveFirst
  lngCount = .RecordCount
  Debug.Print lngCount & " records to write"

  If lngCount > 0 Then
     'Attempt to find matching record in tblTimeSheetData
     'Create or edit one record in tblTimeSheetData for each weekday
     'that has hours worked
     Do While Not .EOF
        lngProjectsID = Nz(![ProjectsID])
        lngActivityCode = Nz(![ActivityCode])

        dblWorkHours = Nz(![MondayWorkHours])

        If dblWorkHours > 0 Then
           dteWork = DateAdd("d", -4, _
              GetProperty("TimesheetWeekEnding", ""))

           If lngActivityCode <> 0 Then
              strSearch = "[ProjectsID] = " & lngProjectsID _
                 & " And [WorkDate] = " & Chr(35) & dteWork _
                 & Chr(35) & " And [ActivityCode] = " _
                 & lngActivityCode
           End If

           Debug.Print "Search string: " & strSearch
           rstTime.FindFirst strSearch

           If rstTime.NoMatch = False Then
              'Edit existing record
              rstTime.Edit
              rstTime![WorkHours] = dblWorkHours
              rstTime.Update

           Else
              'Add new record
              rstTime.AddNew
              rstTime![ProjectsID] = ![ProjectsID]
              rstTime![WorkDate] = dteWork
              rstTime![ActivityCode] = ![ActivityCode]
              rstTime![WorkHours] = dblWorkHours
              rstTime.Update
           End If

           'repeat same code for Tue, Wed, Thu and Fri

        End If

        .MoveNext
     Loop
  End If
 End With

ErrorHandlerExit:
Exit Sub

ErrorHandler:
MsgBox "Error No: " & Err.Number _
  & " in WriteTimesheetData procedure; " _
  & "Description: " & Err.Description
Resume ErrorHandlerExit

End Sub
</code>```

答:
Not sure how much of this will be useful to you but perhaps it will give you some ideas. I did some testing in my db to track Little League umpire assignments. First, created a temp table with the necessary fields.

A saved CROSSTAB query object with static filter criteria can be the source for an INSERT action but dynamic parameters in CROSSTAB query object cause error; however, VBA can deal with that.

```<code>Dim rsPos As DAO.Recordset, rsSource As DAO.Recordset, rsTemp As DAO.Recordset
Set rsPos = CurrentDb.OpenRecordset("SELECT DISTINCT Position FROM Rates;")
Set rsTemp = CurrentDb.OpenRecordset("SELECT * FROM temp1 WHERE 1=1;")
CurrentDb.Execute "DELETE FROM temp1"
While Not rsPos.EOF
    Set rsSource = CurrentDb.OpenRecordset("TRANSFORM First(Rates.Rate) AS FirstRate " & _
                    "SELECT Rates.Position FROM Rates " & _
                    "WHERE (((Rates.Position)='" & rsPos!Position & "')) " & _
                    "GROUP BY Rates.Position PIVOT Rates.RateLevel;")
    While Not rsSource.EOF
        rsTemp.AddNew
        rsTemp!Position = rsSource!Position
        rsTemp!Junior = rsSource!Junior
        rsTemp!Major = rsSource!Major
        rsTemp!Minor = rsSource!Minor
        rsTemp!MinorA = rsSource!MinorA
        rsSource.MoveNext
        rsTemp.Update
    Wend
    rsSource.Close
    rsPos.MoveNext
Wend
rsPos.Close
</code>```

Following code accomplishes the same output without CROSSTAB:

```<code>Dim rsPos As DAO.Recordset, rsSource As DAO.Recordset, rsTemp As DAO.Recordset, i As Integer
Set rsPos = CurrentDb.OpenRecordset("SELECT DISTINCT Position FROM Rates;")
Set rsTemp = CurrentDb.OpenRecordset("SELECT Position, Junior, Major, Minor, MinorA FROM temp1 WHERE 1=1;")
CurrentDb.Execute "Delete FROM temp1"
While Not rsPos.EOF
    Set rsSource = CurrentDb.OpenRecordset("SELECT Position, RateLevel, Rate FROM Rates WHERE Position = '" & rsPos!Position & "' ORDER BY RateLevel;")
    While Not rsSource.EOF
        rsTemp.AddNew
        rsTemp!Position = rsSource!Position
        For i = 1 To 4
            rsTemp.Fields(i) = rsSource!Rate
            rsSource.MoveNext
        Next
        rsTemp.Update
    Wend
    rsSource.Close
    rsPos.MoveNext
Wend
rsPos.Close
</code>```

Body:
I have come a long way on this first Access project of mine but presently terribly stuck at this point for over two weeks!

This part is the timesheet module where there is a timesheetform and a timesheetsubform; on the header part of the form there is a combobox where the user picks the week ending (Friday) date. This week ending date is the main criteria for the whole timesheet. Everything till this point seems to be working fine thanks to one of Ms. Fennema’s codes which I was able to adapt.

Once the date is picked on the combobox, I must put a code in its afterupdate event (Gettimesheetdata subroutine), to first check the main table (tblTimeSheetData) if there are any workhours for the 5 weekdays of that week; (maybe through a query on the fly) and if there are, it should put them in the proper fields in the subform through the temp table so that the user can verify that that specific week's timesheet is already complete or make adjustments to it. If there are no records it would mean that this is a new timesheet! In the case that it’s a new timesheet, selecting the projects and entering the hours for the weekdays and save them to main table also seems to work (Writetimesheetdata subroutine below). As you enter the hours per day based on the project, it populates the temp table and a ‘Save the Worksheet’ command button converts the horizontal data to vertical on the main table. I would really appreciate any help to guide me in the right direction on the Gettimesheetdata subroutine.

Thank you.

Here is the code for the Writetimesheetdata subroutine:

Public Sub WriteTimesheetData()

     Set rstTime = CurrentDb.OpenRecordset("tblTimeSheetData", _
     dbOpenDynaset)
     Set rstTemp = CurrentDb.OpenRecordset("tblTimeSheetDataTemp")

With rstTemp
  .MoveLast
  .MoveFirst
  lngCount = .RecordCount
  Debug.Print lngCount & " records to write"

  If lngCount > 0 Then
     'Attempt to find matching record in tblTimeSheetData
     'Create or edit one record in tblTimeSheetData for each weekday
     'that has hours worked
     Do While Not .EOF
        lngProjectsID = Nz(![ProjectsID])
        lngActivityCode = Nz(![ActivityCode])

        dblWorkHours = Nz(![MondayWorkHours])

        If dblWorkHours > 0 Then
           dteWork = DateAdd("d", -4, _
              GetProperty("TimesheetWeekEnding", ""))

           If lngActivityCode <> 0 Then
              strSearch = "[ProjectsID] = " & lngProjectsID _
                 & " And [WorkDate] = " & Chr(35) & dteWork _
                 & Chr(35) & " And [ActivityCode] = " _
                 & lngActivityCode
           End If

           Debug.Print "Search string: " & strSearch
           rstTime.FindFirst strSearch

           If rstTime.NoMatch = False Then
              'Edit existing record
              rstTime.Edit
              rstTime![WorkHours] = dblWorkHours
              rstTime.Update

           Else
              'Add new record
              rstTime.AddNew
              rstTime![ProjectsID] = ![ProjectsID]
              rstTime![WorkDate] = dteWork
              rstTime![ActivityCode] = ![ActivityCode]
              rstTime![WorkHours] = dblWorkHours
              rstTime.Update
           End If

           'repeat same code for Tue, Wed, Thu and Fri

        End If

        .MoveNext
     Loop
  End If
 End With

ErrorHandlerExit:
Exit Sub

ErrorHandler:
MsgBox "Error No: " & Err.Number _
  & " in WriteTimesheetData procedure; " _
  & "Description: " & Err.Description
Resume ErrorHandlerExit

End Sub

Body:
Not sure how much of this will be useful to you but perhaps it will give you some ideas. I did some testing in my db to track Little League umpire assignments. First, created a temp table with the necessary fields.

A saved CROSSTAB query object with static filter criteria can be the source for an INSERT action but dynamic parameters in CROSSTAB query object cause error; however, VBA can deal with that.

Dim rsPos As DAO.Recordset, rsSource As DAO.Recordset, rsTemp As DAO.Recordset
Set rsPos = CurrentDb.OpenRecordset("SELECT DISTINCT Position FROM Rates;")
Set rsTemp = CurrentDb.OpenRecordset("SELECT * FROM temp1 WHERE 1=1;")
CurrentDb.Execute "DELETE FROM temp1"
While Not rsPos.EOF
    Set rsSource = CurrentDb.OpenRecordset("TRANSFORM First(Rates.Rate) AS FirstRate " & _
                    "SELECT Rates.Position FROM Rates " & _
                    "WHERE (((Rates.Position)='" & rsPos!Position & "')) " & _
                    "GROUP BY Rates.Position PIVOT Rates.RateLevel;")
    While Not rsSource.EOF
        rsTemp.AddNew
        rsTemp!Position = rsSource!Position
        rsTemp!Junior = rsSource!Junior
        rsTemp!Major = rsSource!Major
        rsTemp!Minor = rsSource!Minor
        rsTemp!MinorA = rsSource!MinorA
        rsSource.MoveNext
        rsTemp.Update
    Wend
    rsSource.Close
    rsPos.MoveNext
Wend
rsPos.Close

Following code accomplishes the same output without CROSSTAB:

Dim rsPos As DAO.Recordset, rsSource As DAO.Recordset, rsTemp As DAO.Recordset, i As Integer
Set rsPos = CurrentDb.OpenRecordset("SELECT DISTINCT Position FROM Rates;")
Set rsTemp = CurrentDb.OpenRecordset("SELECT Position, Junior, Major, Minor, MinorA FROM temp1 WHERE 1=1;")
CurrentDb.Execute "Delete FROM temp1"
While Not rsPos.EOF
    Set rsSource = CurrentDb.OpenRecordset("SELECT Position, RateLevel, Rate FROM Rates WHERE Position = '" & rsPos!Position & "' ORDER BY RateLevel;")
    While Not rsSource.EOF
        rsTemp.AddNew
        rsTemp!Position = rsSource!Position
        For i = 1 To 4
            rsTemp.Fields(i) = rsSource!Rate
            rsSource.MoveNext
        Next
        rsTemp.Update
    Wend
    rsSource.Close
    rsPos.MoveNext
Wend
rsPos.Close


问:
JS: How to extract nested string of object?
I got an array with following data structure:

```<code>[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: {
      en: [{ content: 'foo', extended: 'bar' }, {...}],
      it: [{ content: 'any', extended: 'thing' }, {...}]
    },
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  },
  {...}
]
</code>```

I need to modify this array to get only string values for content by selecting the first element of a specific language.

So for the english language the result should be:

```<code>[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: 'foo',
    extended: bar,
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  }
]
</code>```

I know I could get the string with

```<code>const language = 'en'
array.forEach(doc => {
  console.log(doc.content[language][0].content)
  console.log(doc.content[language][0].extended)
})
</code>```

But how do I replace it to get my result?

答:
Here's how without having to list each property:

var array = [{
  _id: 'dgPMHw3ivRSp3wyWe',
  "content": {
    en: {
      content: 'foo',
      extended: 'bar'
    },
    it: {
      content: 'any',
      extended: 'thing'
    }
  },
  order: 1,
  parent: 'Dn59y87PGhkJXpaiZ'
}];

const language = "en";
array = array.map(doc => {
  doc = Object.assign(doc, doc.content[language]);
  return doc;
});
console.log(array);```

Body:
I got an array with following data structure:

[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: {
      en: [{ content: 'foo', extended: 'bar' }, {...}],
      it: [{ content: 'any', extended: 'thing' }, {...}]
    },
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  },
  {...}
]

I need to modify this array to get only string values for content by selecting the first element of a specific language.

So for the english language the result should be:

[
  {
    _id: 'dgPMHw3ivRSp3wyWe',
    content: 'foo',
    extended: bar,
    order: 1,
    parent: 'Dn59y87PGhkJXpaiZ'
  }
]

I know I could get the string with

const language = 'en'
array.forEach(doc => {
  console.log(doc.content[language][0].content)
  console.log(doc.content[language][0].extended)
})

But how do I replace it to get my result?


问:
convert string to int32 with LSB c#

I have binary string and Int32 array.

How to convert binary string (each 11 bit of string) to Int32 value(11 LSB) on int array?

I tried this:

```<code>for (int i = 0; i <(string.Length); i++) {
    if (count1 >= string.Length - 21)
        break;
    else
        string = string.Insert(count1, "000000000000000000000");
        count1 += 31;
}
int numOfBytes = string.Length / 32;
int[] ints = new int[numOfBytes];
for (int i = 0; i < numOfBytes; ++i) {
    ints[i] = Convert.ToInt32(string.Substring(32 * i, 32), 2);
}
</code>```

but it returns false values

答:
```<code>Int32[] BinaryStringToInt32Array(const string binaryString, const int bitCount)
{
    Int32[] results = new Int32[binaryString.Length/bitCount];
    for (int i = 0; i < results.Length; i++)
    {
        string str = binaryString.Substring(i * bitCount, bitCount);
        results[i] = Convert.ToInt32(str, 2);
    }

    return results;

}
</code>```

Take note this function will ignore all leftover bits if binaryString's length is not multiple of bitCount. In your case, bitCount is 11.

Title: convert string to int32 with LSB c#

Body:
I have binary string and Int32 array.

How to convert binary string (each 11 bit of string) to Int32 value(11 LSB) on int array?

I tried this:

for (int i = 0; i <(string.Length); i++) {
    if (count1 >= string.Length - 21)
        break;
    else
        string = string.Insert(count1, "000000000000000000000");
        count1 += 31;
}
int numOfBytes = string.Length / 32;
int[] ints = new int[numOfBytes];
for (int i = 0; i < numOfBytes; ++i) {
    ints[i] = Convert.ToInt32(string.Substring(32 * i, 32), 2);
}

but it returns false values

Body:
Int32[] BinaryStringToInt32Array(const string binaryString, const int bitCount)
{
    Int32[] results = new Int32[binaryString.Length/bitCount];
    for (int i = 0; i < results.Length; i++)
    {
        string str = binaryString.Substring(i * bitCount, bitCount);
        results[i] = Convert.ToInt32(str, 2);
    }

    return results;

}

Take note this function will ignore all leftover bits if binaryString's length is not multiple of bitCount. In your case, bitCount is 11.


问:
Creating new array from looping another array
I need to tidy up an array. And gather all similar information together.

This is going to be a huge order that I'm bringing to the table, however, it's well beyond my skill set and I've been trying to fix it for 3 days.

The message comes from a webservice, which i have absolutely no control over the output/response.

I need to be able to put all the info
But the following (i know its big sorry) is the SOAP object reply: (this has been reduced as well) eek.

```<code>                [0] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-12
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [1] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

                [4] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-13
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [5] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                                        [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )
</code>```

TL;DR

Each hotel has 2 rooms with ids. Each of these 2 id's are seperated by dates, but are in the different parts of the array :(

```<code>[Hotel A]
 HotelA RoomId = 01
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 01
 Date = 13-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 13-08-2011
</code>```

I want to be able to put them into an array as such:

```<code>[Hotel A]
 HotelA RoomId = 01
 Date 12-08-2011
 Date 13-08-2011
 HotelA RoomId = 02
 Date 12-08-2011
 Date 13-08-2011
</code>```

etc

Please help. I've been pulling my hair out :(

Here is an example of what ive tried:

```<code>$hotelinfo = array();
$k=0;
for($i = 0; $i < count($result->RoomInformation); $i++)
{
    $flag = false;
    $HotelObj    = $result->RoomInformation[$i];
    $HotelName   = $result->RoomInformation[$i]->RoomInformationExtend->RoomDetails->Description;
    $HotelId     = $result->RoomStays->RoomStay[$i]->RoomInformation->RoomDetails->RoomId;
    //$hotelinfo[$i][$HotelName] = array();
    $hotelinfo[count($hotelinfo)] = array();
    $hotelinfo[count($hotelinfo)][$HotelName] = array();
    for($c = 0; $c < count($result->RoomInformation); $c++)
    {
        $thishotelObj = $result->RRoomInformation[$c];
        $thisHotelName = $thishotelObj->RoomInformationExtend->RoomDetails->Description;
        $thisHotelId = $thishotelObj->TPA_Extensions->RoomDetails->RoomId;
        if($thisHotelName == $HotelName & $thisHotelId == $HotelId){
            $hotelinfo[$i][$HotelName][$c] = $HotelName;
            $hotelinfo[$i][$HotelName][$c] = $thisHotelName;
            $i++;
        }
    }
}
</code>```

was i even going in thr correct direction with this?

答:
When you do this...

```<code>$hotelinfo[count($hotelinfo)] = array();
$hotelinfo[count($hotelinfo)][$HotelName] = array();
</code>```

You're actually adding two elements to $hotelinfo. For instance, if there were 4 elements in it already, the first line would set index 4, which is a new index (the existing ones are 0, 1, 2, and 3), thus adding an element.

Now that the first line is done, the number of elements in $hotelinfo is 5, and thus the second line sets index 5 - but index 5 corresponds to the next empty slot, and thus a second element is added (for an end result of indices 0-5 being set, with 4 and 5 both new).

Judging from your code, I don't think this is what you intended.

Going the extra mile (or two)...

I think what you might want to do first is get the data into a more usable format - grouped first by hotel, and then by room ID. So, let's do that:

```<code>$hotelInfo = array();
foreach($result->RoomInformation as $roomInfo) {

    $hotelName = $roomInfo->RoomInformationExtend->RoomDetails->Description;

    if(!isset($hotelInfo[$hotelName])) {
        $hotelInfo[$hotelName] = array();
    }
    $thisHotel = $hotelInfo[$hotelName];

    $roomId = $roomInfo->RoomInformationExtend->RoomDetails->RoomId;

    if(!isset($thisHotel[$roomId])) {
        $thisHotel[$roomId] = array();
    }
    $thisRoom = $thisHotel[$roomId];
</code>```

Okay, so now we have a $thisRoom object that we can fill in info for. If a different item in the list we're going through already created an object for a particular hotel+room combination, we just get that already-created one instead of making a new one.

Now, we'll add any relevant information is the current item of data to our room object:

```<code>    if(isset($roomInfo->Details)) {
        if(isset($roomInfo->Details->EffectiveDate)) {
            // "$foo[] = bar" appends 'bar' to the array '$foo'
            $thisRoom[] = $roomInfo->Details->EffectiveDate;
        }

        if(isset($roomInfo->Details->RoomRate)) {
            if(isset($roomInfo->Details->RoomRate->EffectiveDate)) {
                $thisRoom[] = $roomInfo->Details->RoomRate->EffectiveDate;
            }
        }
    }
}
</code>```

After you've done this, you'll wind up with a structure in $hotelInfo that looks like this:

```<code>array(
    ['Hotel Alpha'] => array(
        [1860] => array('2011-08-12', '2011-08-13'),
        [1861] => array('2011-08-12', '2011-08-13')
    ),
    ['Hotel Beta'] => array(
        [1226] => array('2011-08-12', '2011-08-13'),
        [1227] => array('2011-08-12', '2011-08-13')
    )
)
</code>```

Which should be much easier to work with, and a lot closer to what you seem to be wanting.

ContentLicense: CC BY-SA 2.5

Body:
I need to tidy up an array. And gather all similar information together.

This is going to be a huge order that I'm bringing to the table, however, it's well beyond my skill set and I've been trying to fix it for 3 days.

The message comes from a webservice, which i have absolutely no control over the output/response.

I need to be able to put all the info
But the following (i know its big sorry) is the SOAP object reply: (this has been reduced as well) eek.

                [0] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-12
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [1] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-12
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

                [4] => RoomInformation Object
                    (
                       [Details] => DetailsType Object
                            (
                                [Total] => TotalType Object
                                    (
                                        [AmountAfterTax] => 1.00
                                    )
                                [EffectiveDate] => 2011-08-13
                                [AvailabilityStatus] => AvailableForSale
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1860
                                        [RoomNo] => THAH01
                                        [Description] => Hotel Alpha
                                    )
                            )
                    )

                [5] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (

                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [RoomId] => 1861
                                        [RoomNo] => THAH02
                                        [Description] => Hotel Alpha
                                    )
                           )
                    )
                                        [2] => RoomInformation Object
                    (

                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1226
                                        [RoomNo] => DENM01
                                        [Description] => Hotel Beta
                                    )
                            )

                    )

                [3] => RoomInformation Object
                    (
                        [Details] => DetailsType Object
                            (
                                [RoomRate] => RoomRateType Object
                                    (
                                        [Total] => TotalType Object
                                            (
                                                [AmountAfterTax] => 1.00
                                            )
                                        [EffectiveDate] => 2011-08-13
                                        [AvailabilityStatus] => AvailableForSale
                                    )
                                [MoreRatesExistInd] =>
                            )

                        [RoomInformationExtend] => TPA_ExtensionsType Object
                            (
                                [RoomDetails] => RoomDetails Object
                                    (
                                        [Amenities] => stdClass Object
                                            (
                                            )

                                        [Configurations] => stdClass Object
                                            (
                                            )

                                        [RoomId] => 1227
                                        [RoomNo] => DENM02
                                        [Description] => Hotel Beta
                                    )
                            )
                    )

TL;DR

Each hotel has 2 rooms with ids. Each of these 2 id's are seperated by dates, but are in the different parts of the array :(

[Hotel A]
 HotelA RoomId = 01
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 12-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 12-08-2011
[Hotel A]
 HotelA RoomId = 01
 Date = 13-08-2011
[Hotel A]
 HotelA RoomId = 02
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 01
 Date = 13-08-2011
[Hotel B]
 HotelB RoomId = 02
 Date = 13-08-2011

I want to be able to put them into an array as such:

[Hotel A]
 HotelA RoomId = 01
 Date 12-08-2011
 Date 13-08-2011
 HotelA RoomId = 02
 Date 12-08-2011
 Date 13-08-2011

etc

Please help. I've been pulling my hair out :(

Here is an example of what ive tried:

$hotelinfo = array();
$k=0;
for($i = 0; $i < count($result->RoomInformation); $i++)
{
    $flag = false;
    $HotelObj    = $result->RoomInformation[$i];
    $HotelName   = $result->RoomInformation[$i]->RoomInformationExtend->RoomDetails->Description;
    $HotelId     = $result->RoomStays->RoomStay[$i]->RoomInformation->RoomDetails->RoomId;
    //$hotelinfo[$i][$HotelName] = array();
    $hotelinfo[count($hotelinfo)] = array();
    $hotelinfo[count($hotelinfo)][$HotelName] = array();
    for($c = 0; $c < count($result->RoomInformation); $c++)
    {
        $thishotelObj = $result->RRoomInformation[$c];
        $thisHotelName = $thishotelObj->RoomInformationExtend->RoomDetails->Description;
        $thisHotelId = $thishotelObj->TPA_Extensions->RoomDetails->RoomId;
        if($thisHotelName == $HotelName & $thisHotelId == $HotelId){
            $hotelinfo[$i][$HotelName][$c] = $HotelName;
            $hotelinfo[$i][$HotelName][$c] = $thisHotelName;
            $i++;
        }
    }
}

was i even going in thr correct direction with this?

Body:
When you do this...

$hotelinfo[count($hotelinfo)] = array();
$hotelinfo[count($hotelinfo)][$HotelName] = array();

You're actually adding two elements to $hotelinfo. For instance, if there were 4 elements in it already, the first line would set index 4, which is a new index (the existing ones are 0, 1, 2, and 3), thus adding an element.

Now that the first line is done, the number of elements in $hotelinfo is 5, and thus the second line sets index 5 - but index 5 corresponds to the next empty slot, and thus a second element is added (for an end result of indices 0-5 being set, with 4 and 5 both new).

Judging from your code, I don't think this is what you intended.

Going the extra mile (or two)...

I think what you might want to do first is get the data into a more usable format - grouped first by hotel, and then by room ID. So, let's do that:

$hotelInfo = array();
foreach($result->RoomInformation as $roomInfo) {

    $hotelName = $roomInfo->RoomInformationExtend->RoomDetails->Description;

    if(!isset($hotelInfo[$hotelName])) {
        $hotelInfo[$hotelName] = array();
    }
    $thisHotel = $hotelInfo[$hotelName];

    $roomId = $roomInfo->RoomInformationExtend->RoomDetails->RoomId;

    if(!isset($thisHotel[$roomId])) {
        $thisHotel[$roomId] = array();
    }
    $thisRoom = $thisHotel[$roomId];

Okay, so now we have a $thisRoom object that we can fill in info for. If a different item in the list we're going through already created an object for a particular hotel+room combination, we just get that already-created one instead of making a new one.

Now, we'll add any relevant information is the current item of data to our room object:

    if(isset($roomInfo->Details)) {
        if(isset($roomInfo->Details->EffectiveDate)) {
            // "$foo[] = bar" appends 'bar' to the array '$foo'
            $thisRoom[] = $roomInfo->Details->EffectiveDate;
        }

        if(isset($roomInfo->Details->RoomRate)) {
            if(isset($roomInfo->Details->RoomRate->EffectiveDate)) {
                $thisRoom[] = $roomInfo->Details->RoomRate->EffectiveDate;
            }
        }
    }
}

After you've done this, you'll wind up with a structure in $hotelInfo that looks like this:

array(
    ['Hotel Alpha'] => array(
        [1860] => array('2011-08-12', '2011-08-13'),
        [1861] => array('2011-08-12', '2011-08-13')
    ),
    ['Hotel Beta'] => array(
        [1226] => array('2011-08-12', '2011-08-13'),
        [1227] => array('2011-08-12', '2011-08-13')
    )
)

Which should be much easier to work with, and a lot closer to what you seem to be wanting.


问:
Hibernate Java 9 Configuration File Error
I recently migrated to Java 9 and find the following error.

Initial SessionFactory creation failed.org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null

The content of my configuration file is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://localhost</property>
        <property name="hibernate.connection.databasename">ActiveDirectory</property>
        <property name="hibernate.connection.integratedsecurity">true</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.enable_lazy_load_no_trans">true</property>
        <property name="connection.pool_size">1000</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">1000</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">1000</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
    </session-factory>
</hibernate-configuration>
</code>```

The exception is throw when I run the .configure("hibernate.cfg.xml").
Do you have any idea of how should I face it?

答:
Error: Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

This happens because of Java 9.

Java 9 has deprecated java.xml.bind module and has removed it from the default classpath. That's why we get the class not found exception. The javax.xml.bind package is now a sub package of Module java.xml.bind.

So we simply have to add that module to the runtime configuration.

Solution:

Right-click your Java file, for example: CreateStudentDemo.java

Select Run As > Run Configurations ...

In the center panel, click the tab Arguments

In the section for VM Arguments, enter: --add-modules java.xml.bind

Click Run

Your application will run successfully.

Let me know your results.

:-)

Modules are a new feature of Java 9. You can get details on Java 9
modules here: https://blogs.oracle.com/java/modular-development

Body:
I recently migrated to Java 9 and find the following error.

Initial SessionFactory creation failed.org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null

The content of my configuration file is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="hibernate.connection.url">jdbc:sqlserver://localhost</property>
        <property name="hibernate.connection.databasename">ActiveDirectory</property>
        <property name="hibernate.connection.integratedsecurity">true</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.enable_lazy_load_no_trans">true</property>
        <property name="connection.pool_size">1000</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">1000</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">1000</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
    </session-factory>
</hibernate-configuration>

The exception is throw when I run the .configure("hibernate.cfg.xml").
Do you have any idea of how should I face it?


问:
how to pass magic mocked references to main method in python
I've tried to stub out classes constructed in the main function so that I can test against main and assert that classes are initialized with specific data. However main function still does not pick up the mocked instances. How can I pass along the mocked instance to main.

```<code>from unittest.mock import patch
from contextlib import contextmanager

@contextmanager
def use_mocked(method, cls, ret_value):

class MockedClass(cls):
    pass

def func(cls):
    return ret_value

def fullname(o):
    return o.__module__ + "." + o.__name__

setattr(MockedClass, method, classmethod(func))

with patch(fullname(cls), MockedClass):
    yield
</code>```

This is the patching utility to make sure main is passed the mocked reference. I may be confused on my understanding of how its functioning.

```<code>def test_main():
    magic_b = MagicMock(spec_set=Benchmark, wraps=Benchmark)
    with use_mocked("__new__", DataStream, magic_b):
        main.main()
        magic_b.assert_called_once_with() # fails
</code>```

in the main module, I have a main method defined as...

```<code>import benchmark.Benchmark
def main():
    b = benchmark.Benchmark() # <- this is not the mocked instance
    ...
</code>```

答:
I relied on the same patch utility in unittest.mock but instead just used it in the form of a decorator around my test. patch() now is passed in the Benchmark class which main imports (it is important to patch in main and not in benchmark modules it self ie. don't patch benchmark.Benchmark). Main module remains untouched and tests now pass.

```<code>import main

@patch("main.Benchmark")
# b here is a ref to MagicMock class mocking Benchmark;
# it is substituted into the execution of main module,
# patch provides it as a param so you can assert against it.
def test_main(b):
    main.main()
    b.assert_called_once_with()
</code>```

Body:
I've tried to stub out classes constructed in the main function so that I can test against main and assert that classes are initialized with specific data. However main function still does not pick up the mocked instances. How can I pass along the mocked instance to main.

from unittest.mock import patch
from contextlib import contextmanager

@contextmanager
def use_mocked(method, cls, ret_value):

class MockedClass(cls):
    pass

def func(cls):
    return ret_value

def fullname(o):
    return o.__module__ + "." + o.__name__

setattr(MockedClass, method, classmethod(func))

with patch(fullname(cls), MockedClass):
    yield

This is the patching utility to make sure main is passed the mocked reference. I may be confused on my understanding of how its functioning.

def test_main():
    magic_b = MagicMock(spec_set=Benchmark, wraps=Benchmark)
    with use_mocked("__new__", DataStream, magic_b):
        main.main()
        magic_b.assert_called_once_with() # fails

in the main module, I have a main method defined as...

import benchmark.Benchmark
def main():
    b = benchmark.Benchmark() # <- this is not the mocked instance
    ...

Body:
I relied on the same patch utility in unittest.mock but instead just used it in the form of a decorator around my test. patch() now is passed in the Benchmark class which main imports (it is important to patch in main and not in benchmark modules it self ie. don't patch benchmark.Benchmark). Main module remains untouched and tests now pass.

import main

@patch("main.Benchmark")
# b here is a ref to MagicMock class mocking Benchmark;
# it is substituted into the execution of main module,
# patch provides it as a param so you can assert against it.
def test_main(b):
    main.main()
    b.assert_called_once_with()


问:
TCL Error: can't set "::streamID(1,10,1)": variable isn't array
I have read the thread, Cant read variable, isnt array, and I think may be related somehow, but I can't figure out how.  In the following TCL snippet, a three dimensional array ::stream is tested and a value is read.  The array contains a scalar ID value.  The last line in the snippet creates an error that says </p>

```<code>can't set "::streamId(1,10,1)": variable isn't array
    while executing
"set ::streamId($chas,$card,$port) $nextId"
    (procedure "getNextStreamId" line 28)
</code>```

<p>I interpret this as meaning $nextId is something other than a scalar and it can't be put into a 3 dimensional array of scalars.  Is my interpretation of the error incorrect?  I was pretty confident that the array holds scalar values, so I started to think maybe there is some data safety issue here. </p>

```<code># get current streamId
if { [ catch {info exists $::streamId($chas,$card,$port)} ] == 0 } {
if {$::testEnv(verbose) >= $verbLevel} {
    logInfo [getProcName] "pre-existing streamId found for: \
        \n dutAndPort:  $dutAndPort \
        \n ixiaPort:    {$chas $card $port}\
        \n streamId:    $::streamId($chas,$card,$port) \
        \n incrementing to next one..."
}
set nextId [ mpexpr $::streamId($chas,$card,$port) + 1 ]
} else {
if {$::testEnv(verbose) >= 0} {
    logInfo [getProcName] "No pre-existing streamId found for: \
        \n\t dutAndPort:    $dutAndPort \
        \n\t ixiaPort:      {$chas $card $port}\
        \n\t setting to 1"
}
set nextId 1
}
set curId  [ mpexpr $nextId - 1 ]

set ::streamId($chas,$card,$port) $nextId
</code>```

答:
In your code, I guess you wanted to check if the array ::streamId has the index $chas,$card,$port

```<code>info exists $::streamId($chas,$card,$port)
</code>```

which is incorrect. You should use

```<code>info exists ::streamId($chas,$card,$port)
</code>```

i.e. without dollar sign. Then only the if loop can ensure the existence of the index $chas,$card,$port.

Then, at last you are trying to set the value of the index $chas,$card,$port to $nextId .

```<code>set ::streamId($chas,$card,$port) $nextId
</code>```

which is incoorect, because it kept outside the if loop of variable existence check of the index $chas,$card,$port.

Then the actual error message is referring the fact that there is a scalar  variable named streamId exists.

```<code>% set ::streamId 1
1
% set ::streamId(1,10,1) 20
can't set "::streamId(1,10,1)": variable isn't array
%
</code>```

Ensure you don't have the same variable names.

Body:
I have read the thread, Cant read variable, isnt array, and I think may be related somehow, but I can't figure out how.  In the following TCL snippet, a three dimensional array ::stream is tested and a value is read.  The array contains a scalar ID value.  The last line in the snippet creates an error that says

can't set "::streamId(1,10,1)": variable isn't array
    while executing
"set ::streamId($chas,$card,$port) $nextId"
    (procedure "getNextStreamId" line 28)

I interpret this as meaning $nextId is something other than a scalar and it can't be put into a 3 dimensional array of scalars.  Is my interpretation of the error incorrect?  I was pretty confident that the array holds scalar values, so I started to think maybe there is some data safety issue here.

# get current streamId
if { [ catch {info exists $::streamId($chas,$card,$port)} ] == 0 } {
if {$::testEnv(verbose) >= $verbLevel} {
    logInfo [getProcName] "pre-existing streamId found for: \
        \n dutAndPort:  $dutAndPort \
        \n ixiaPort:    {$chas $card $port}\
        \n streamId:    $::streamId($chas,$card,$port) \
        \n incrementing to next one..."
}
set nextId [ mpexpr $::streamId($chas,$card,$port) + 1 ]
} else {
if {$::testEnv(verbose) >= 0} {
    logInfo [getProcName] "No pre-existing streamId found for: \
        \n\t dutAndPort:    $dutAndPort \
        \n\t ixiaPort:      {$chas $card $port}\
        \n\t setting to 1"
}
set nextId 1
}
set curId  [ mpexpr $nextId - 1 ]

set ::streamId($chas,$card,$port) $nextId

Body:
In your code, I guess you wanted to check if the array ::streamId has the index $chas,$card,$port

info exists $::streamId($chas,$card,$port)

which is incorrect. You should use

info exists ::streamId($chas,$card,$port)

i.e. without dollar sign. Then only the if loop can ensure the existence of the index $chas,$card,$port.

Then, at last you are trying to set the value of the index $chas,$card,$port to $nextId .

set ::streamId($chas,$card,$port) $nextId

which is incoorect, because it kept outside the if loop of variable existence check of the index $chas,$card,$port.

Then the actual error message is referring the fact that there is a scalar  variable named streamId exists.

% set ::streamId 1
1
% set ::streamId(1,10,1) 20
can't set "::streamId(1,10,1)": variable isn't array
%

Ensure you don't have the same variable names.


问:
Decoding RTP G,711 A-Law Packet Problem , difference between c# & c++
first sorry for my English

by using c#
I'm  try to decoding RTP  A-Law Packet but it is gave me a noise,
i checked my code with wireshark code  which can gave me the voice without noise  , i can not get the difference between   wireshark  code (c++) and my code (c#) which because I can not Debugging  wireshark   , but i get the  difference Bytes  resulting from my code and wireshark  code

i will write the Bytes result  from two code and simple of my code and  wireshark

for example :

when the alaw_exp_table[data[i]] = -8

in my cod the bytes result  are            : 248 , 255

in wireshark  code the bytes result  are   :  255 , 248

are you see 248,255  :  255,248  i think it was a reflection but  the next example not

when the alaw_exp_table[data[i]] = 8

in my cod the bytes result  are :  8 , 0

in wireshark  code the bytes result  are  : 0 , 0

this wireshark

```<code> int
    decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)

    {

    guint8 *dataIn = (guint8 *)input;

    gint16 *dataOut = (gint16 *)output;

     int i;

    for (i=0; i<inputSizeBytes; i++)

     {

     dataOut[i] = alaw_exp_table[dataIn[i]];

    }

     *outputSizeBytes = inputSizeBytes * 2;

     return 0;

    }

   static  short[] alaw_exp_table= {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};
</code>```

and this is my code

```<code> public static void ALawDecode(byte data, out byte[] decoded)
        {
            int size = data.Length;
            decoded = new byte[size * 2];
            for (int i = 0; i < size; i++)
            {
                 //First byte is the less significant byte
                decoded[2 * i] = (byte)(alaw_exp_table[data[i]] & 0xff);
                //Second byte is the more significant byte
                decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] >> 8);
            }
        }
</code>```

the alaw_exp_table is same in my code and wireshark code

please tell me  what is the wrong in my code which do that noise ?

thanks in advance

答:
You are decoding eight bit A-law samples into 16 bit signed PCM, so it would make sense for you to use an array of shorts for the output. This is close to what the C code is doing.

If you don't have a particular reason for using a byte array as output, I would suggest just having the A-law lookup table be a short array an just move 16-bit signed values around instead of messing around with byte ordering.

If you really do care about bytes and byte ordering, you need to get the byte ordering right, as @leppie says. This will depend on what you actually do with the output.

Body:
first sorry for my English

by using c#
I'm  try to decoding RTP  A-Law Packet but it is gave me a noise,
i checked my code with wireshark code  which can gave me the voice without noise  , i can not get the difference between   wireshark  code (c++) and my code (c#) which because I can not Debugging  wireshark   , but i get the  difference Bytes  resulting from my code and wireshark  code

i will write the Bytes result  from two code and simple of my code and  wireshark

for example :

when the alaw_exp_table[data[i]] = -8

in my cod the bytes result  are            : 248 , 255

in wireshark  code the bytes result  are   :  255 , 248

are you see 248,255  :  255,248  i think it was a reflection but  the next example not

when the alaw_exp_table[data[i]] = 8

in my cod the bytes result  are :  8 , 0

in wireshark  code the bytes result  are  : 0 , 0

this wireshark

 int
    decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)

    {

    guint8 *dataIn = (guint8 *)input;

    gint16 *dataOut = (gint16 *)output;

     int i;

    for (i=0; i<inputSizeBytes; i++)

     {

     dataOut[i] = alaw_exp_table[dataIn[i]];

    }

     *outputSizeBytes = inputSizeBytes * 2;

     return 0;

    }

   static  short[] alaw_exp_table= {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};

and this is my code

 public static void ALawDecode(byte data, out byte[] decoded)
        {
            int size = data.Length;
            decoded = new byte[size * 2];
            for (int i = 0; i < size; i++)
            {
                 //First byte is the less significant byte
                decoded[2 * i] = (byte)(alaw_exp_table[data[i]] & 0xff);
                //Second byte is the more significant byte
                decoded[2 * i + 1] = (byte)(alaw_exp_table[data[i]] >> 8);
            }
        }

the alaw_exp_table is same in my code and wireshark code

please tell me  what is the wrong in my code which do that noise ?

thanks in advance


问:
C# Getting paths of all folders and subfolders, excluding folders with only other folders in them
I'm trying to obtain all of the folder paths that have files inside them, while excluding the folder paths that only have other folders in them. I'm using

```<code>Directory.GetDirectories(dirPath, "*", SearchOption.AllDirectories);
</code>```

Which does what I need it to, except that it returns the paths of folders that only have other folders in them.

答:
One way to do this would be to EnumerateFiles for the directory and all it's sub-directories, and get a Distinct() list of their directory names:

```<code>List<string> directoriesWithFiles = Directory
    .EnumerateFiles(rootDir, "*", SearchOption.AllDirectories)
    .Select(Path.GetDirectoryName)
    .Distinct()
    .ToList();
</code>```

The first way I thought to do this was to use EnumerateDirectories, and then for each directory use EnumerateFiles to filter out directories that don't contain any files. But this turned out to be much slower than the method above:

```<code>List<string> directoriesWithFiles = Directory
    .EnumerateDirectories(rootDir, "*", SearchOption.AllDirectories)
    .Where(d => Directory.EnumerateFiles(d).Any())
    .ToList();
</code>```

Body:
I'm trying to obtain all of the folder paths that have files inside them, while excluding the folder paths that only have other folders in them. I'm using

Directory.GetDirectories(dirPath, "*", SearchOption.AllDirectories);

Which does what I need it to, except that it returns the paths of folders that only have other folders in them.

Body:
One way to do this would be to EnumerateFiles for the directory and all it's sub-directories, and get a Distinct() list of their directory names:

List<string> directoriesWithFiles = Directory
    .EnumerateFiles(rootDir, "*", SearchOption.AllDirectories)
    .Select(Path.GetDirectoryName)
    .Distinct()
    .ToList();

The first way I thought to do this was to use EnumerateDirectories, and then for each directory use EnumerateFiles to filter out directories that don't contain any files. But this turned out to be much slower than the method above:

List<string> directoriesWithFiles = Directory
    .EnumerateDirectories(rootDir, "*", SearchOption.AllDirectories)
    .Where(d => Directory.EnumerateFiles(d).Any())
    .ToList();


问:
Is it possible to abort a map function on a Swift collection?
We have a case where we're being handed an object of type Array<Any> which we need to convert to an Array<Codable>. If any of the items in the original array don't adhere to Codable, then we want the entire thing to abort and return nil.

Or current approach is to manually loop over everything, testing along the way, like so...

```<code>func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    var codableArray = Array<Codable>()

    for item in sourceArray{

        guard let codableItem = item as? Codable else {
            return nil
        }

        codableArray.append(codableItem)
    }

    return codableArray
}
</code>```

However, I'm wondering if there's an easier way to do this with the map command, but it would require it to short-circuit if any of the elements can't be mapped.  That's what I'm not sure or not is possible.

For instance, this pseudo-code...

```<code>func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    return sourceArray.map({ $0 as? Codable});
}
</code>```

Is this possible, or is our original way the correct/only way?

答:
As @rmaddy shows, you can utilise the fact that map(_:) can accept a throwing closure, and will stop mapping upon an error being thrown, propagating the error thrown back to the caller (which you can then absorb with try?).

One slight variation on this would be to define your own throwing cast(_:to:) function to call in the transformation closure:

```<code>struct TypeMismatchError : Error {
  var expected: Any.Type
  var actual: Any.Type
}

func cast<T, U>(_ x: T, to _: U.Type) throws -> U {
  guard let casted = x as? U else {
    throw TypeMismatchError(expected: U.self, actual: type(of: x))
  }
  return casted
}

func makeCodable(sourceArray: [Any]) -> [Codable]? {
  return try? sourceArray.map { try cast($0, to: Codable.self) }
}
</code>```

Although we're completely ignoring the error thrown in this case, I have found it occasionally useful in other cases to have a throwing casting function about (you could of course also propagate the error by making makeCodable a throwing function and using try).

However, that all being said, note that your resulting [Codable]? really isn't too useful in its current form. You can't decode stuff from it because you don't have any concrete types to hand, and you can't directly encode it as protocols don't conform to themselves (i.e Codable doesn't conform to Encodable, so you can't just hand off a Codable or [Codable] to JSONEncoder).

If you actually wanted to do some encoding with your [Codable], you'd need to wrap each of the elements in a Encodable conforming wrapper, for example:

```<code>struct AnyEncodable : Encodable {

  var base: Encodable

  init(_ base: Encodable) {
    self.base = base
  }

  func encode(to encoder: Encoder) throws {
    try base.encode(to: encoder)
  }
}

func makeEncodable(sourceArray: [Any]) -> [AnyEncodable]? {
  return try? sourceArray.map {
    AnyEncodable(try cast($0, to: Encodable.self))
  }
}
</code>```

Now [AnyEncodable] is something you can pass off to, for example, JSONEncoder.

Body:
We have a case where we're being handed an object of type Array<Any> which we need to convert to an Array<Codable>. If any of the items in the original array don't adhere to Codable, then we want the entire thing to abort and return nil.

Or current approach is to manually loop over everything, testing along the way, like so...

func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    var codableArray = Array<Codable>()

    for item in sourceArray{

        guard let codableItem = item as? Codable else {
            return nil
        }

        codableArray.append(codableItem)
    }

    return codableArray
}

However, I'm wondering if there's an easier way to do this with the map command, but it would require it to short-circuit if any of the elements can't be mapped.  That's what I'm not sure or not is possible.

For instance, this pseudo-code...

func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{

    return sourceArray.map({ $0 as? Codable});
}

Is this possible, or is our original way the correct/only way?

Body:
As @rmaddy shows, you can utilise the fact that map(_:) can accept a throwing closure, and will stop mapping upon an error being thrown, propagating the error thrown back to the caller (which you can then absorb with try?).

One slight variation on this would be to define your own throwing cast(_:to:) function to call in the transformation closure:

struct TypeMismatchError : Error {
  var expected: Any.Type
  var actual: Any.Type
}

func cast<T, U>(_ x: T, to _: U.Type) throws -> U {
  guard let casted = x as? U else {
    throw TypeMismatchError(expected: U.self, actual: type(of: x))
  }
  return casted
}

func makeCodable(sourceArray: [Any]) -> [Codable]? {
  return try? sourceArray.map { try cast($0, to: Codable.self) }
}

Although we're completely ignoring the error thrown in this case, I have found it occasionally useful in other cases to have a throwing casting function about (you could of course also propagate the error by making makeCodable a throwing function and using try).

However, that all being said, note that your resulting [Codable]? really isn't too useful in its current form. You can't decode stuff from it because you don't have any concrete types to hand, and you can't directly encode it as protocols don't conform to themselves (i.e Codable doesn't conform to Encodable, so you can't just hand off a Codable or [Codable] to JSONEncoder).

If you actually wanted to do some encoding with your [Codable], you'd need to wrap each of the elements in a Encodable conforming wrapper, for example:

struct AnyEncodable : Encodable {

  var base: Encodable

  init(_ base: Encodable) {
    self.base = base
  }

  func encode(to encoder: Encoder) throws {
    try base.encode(to: encoder)
  }
}

func makeEncodable(sourceArray: [Any]) -> [AnyEncodable]? {
  return try? sourceArray.map {
    AnyEncodable(try cast($0, to: Encodable.self))
  }
}

Now [AnyEncodable] is something you can pass off to, for example, JSONEncoder.


问:
CreateFileMapping fails when 64-bit application reaches 2GB
I have a 64-bit application WPF/C# which allocates memory using CreateFileMapping()
the function returns error 1455 once I hit 2GB limit.

My machine has 32GB RAM and page file is disabled.
Can it be the CreateFileMapping(win32 API) works only on 32 bit?

```<code>_byteCount = (uint)((_stride) * height * ((short)bpp).NumberOfBytes());

 ColorFileMapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, _byteCount, null);
</code>```

答: _byteCount should be of type DWORD to avoid overflow of uint.</p>

Body:
I have a 64-bit application WPF/C# which allocates memory using CreateFileMapping()
the function returns error 1455 once I hit 2GB limit.

My machine has 32GB RAM and page file is disabled.
Can it be the CreateFileMapping(win32 API) works only on 32 bit?

_byteCount = (uint)((_stride) * height * ((short)bpp).NumberOfBytes());

 ColorFileMapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, _byteCount, null);


问:
Can't pass state value from child to parent component in react native
I have a state inside of child component that I want to use in parent component. This is how my components set:

Child:

```<code>export default class Child extends React.PureComponent {
  constructor() {
    this.state = {
      value: "123",
    };
  }
updateValue(data){
    this.props.updateValue(data);
}

componentWillMount(){
    this.updateValue(this.state.value);
}
}
</code>```

Parent:

```<code>export default class Parent extends Component {
    constructor() {
    super(props)
    this.state = {
        newValue: ""
    };
  }

updateState (data) {
        this.setState(newValue: data);
    }
  render() {
return(
        <Child updateValue={this.updateState.bind(this)}/>
)
}
}
</code>```

However, it doesn't seem to work and gives me an error. Am I doing something wrong?

答:
Remember that this.setState takes an argument. You have passed a key:value pair that isn't stored in a data structure.

```<code>this.setState(newValue: data);
</code>```

should be

```<code>this.setState({newValue: data});
</code>```

Body:
I have a state inside of child component that I want to use in parent component. This is how my components set:

Child:

export default class Child extends React.PureComponent {
  constructor() {
    this.state = {
      value: "123",
    };
  }
updateValue(data){
    this.props.updateValue(data);
}

componentWillMount(){
    this.updateValue(this.state.value);
}
}

Parent:

export default class Parent extends Component {
    constructor() {
    super(props)
    this.state = {
        newValue: ""
    };
  }

updateState (data) {
        this.setState(newValue: data);
    }
  render() {
return(
        <Child updateValue={this.updateState.bind(this)}/>
)
}
}

However, it doesn't seem to work and gives me an error. Am I doing something wrong?

Body:
Remember that this.setState takes an argument. You have passed a key:value pair that isn't stored in a data structure.

this.setState(newValue: data);

should be

this.setState({newValue: data});


问:
Left Outer Join returns duplicate records - Oracle
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

```<code>ID NAME PRICE GST
1  Book 100   10
2  CD   50    5
</code>```

Ex:

Table ORDER

```<code>ID   NAME  COST
1    Book  110
2    CD    55
</code>```

Table COST

```<code>ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5
</code>```

LEFT OUTER JOIN returns multiple rows when below condition is used

```<code>SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID
</code>```

答:
So Select ORDER.ID, COST.COST_TYPE, COST.VALUE from ORDERS LEFT OUTER JOIN COST ON ORDER.ID = COST.ORDER_ID and COST.COST_TYPE = 'PRICE'

If you don't specify COST_TYPE then it will return multiple rows because ORDER_ID repeats on your COST TABLE.

Body:
Scenario :

Join Table ORDER with Table COST
where COST has multiple rows for a single reference from Table ORDER

Desired outcome:

Return single row per Order with its associated costs.

ID NAME PRICE GST
1  Book 100   10
2  CD   50    5

Ex:

Table ORDER

ID   NAME  COST
1    Book  110
2    CD    55

Table COST

ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5

LEFT OUTER JOIN returns multiple rows when below condition is used

SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID


问:
python database insert formatting
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line

```<code>        cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date))
</code>```

but every time it tries to run the table name has ' ' around it so it turns out like INSERT INTO table_name('12', ..., ..., ...) ... instead of
INSERT INTO table_name(12, ..., ..., ...) ... how can I make the string formatter leave the quotes out or remove them or something? It is causing a syntax error around the 12 because it doesn't need the single quotes.

答:
Use it with triple quotes. Also you may pass table_name as a element of second parameter, too.

```<code> cur.execute("""INSERT INTO %s (price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)""",(table_name, exchange_rate, buy_rate, sell_rate, date))
</code>```

More detailed approach;

Triple qoutes give developers a change to write SQL query as multi-lines.

Also it allows you to use single and double qoutes without escaping from them. (It is beneficiary for complex SQL Queries but you don't need that on your case)

ContentLicense: CC BY-SA 4.0

Title: python database insert formatting

Body:
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line

        cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date))

but every time it tries to run the table name has ' ' around it so it turns out like INSERT INTO table_name('12', ..., ..., ...) ... instead of
INSERT INTO table_name(12, ..., ..., ...) ... how can I make the string formatter leave the quotes out or remove them or something? It is causing a syntax error around the 12 because it doesn't need the single quotes.

Body:
Use it with triple quotes. Also you may pass table_name as a element of second parameter, too.

 cur.execute("""INSERT INTO %s (price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)""",(table_name, exchange_rate, buy_rate, sell_rate, date))

More detailed approach;

Triple qoutes give developers a change to write SQL query as multi-lines.

Also it allows you to use single and double qoutes without escaping from them. (It is beneficiary for complex SQL Queries but you don't need that on your case)