问:
Winform: Trouble updating combobox
I am working on a Windows Form using Powershell that will query a print server for all Printers Installed (function: FetchPrinters). I have a button added to run the FetchPrinters function.

```<code>Function:

    $Global:PrintServer = ""
function FetchPrinters {
    $printerTxtFileLocation = 'C:\Temp\PrinterList.csv'
    $outputBox.text = "Fetching list of printers on $Global:PrintServer"
    # $Global:PrintServer = $Global:DropDownBox1.SelectedItem.ToString()
    Get-Printer -ComputerName "$Global:PrintServer" | Select-Object -ExpandProperty Name | Sort-Object -CaseSensitive | Out-File -Force -Encoding utf8 -FilePath "$printerTxtFileLocation"
    $PrinterList = Get-Content -Path "$printerTxtFileLocation" -Encoding UTF8 -Force
    foreach ($Printer in $PrinterList) {
        $DropDownBox2.ResetText()
        [void] $DropDownBox2.Items.Add($Printer)
    }
}
</code>```

In Dropdownbox1, there will be a list of sites (location), that when selected will determine what Print Server to query.

```<code>    $DropDownBox1 = New-Object System.Windows.Forms.ComboBox

$DropDownBox1.Text = "Select Site Name"

$DropDownBox1.Size = New-Object System.Drawing.Size(190, 20)

$DropDownBox1.Location = New-Object System.Drawing.Point(20, 20)

$Sites = @(

    'Site 1',

    'Site 2',

    'Site 3',

    'Site 4',

    'Site 5',

    'Site 6'

    'Site 7'

)

ForEach ($Site in $Sites) {

    $DropDownBox1.Items.Add($Site) | Out-Null

}

$Global:DropDownBox1_SelectedIndexChanged = {

    Switch ($DropDownBox1.Text) {

        'Site 1' { $Global:PrintServer = "\\Printserver1" }

        'Site 2' { $PrintServer = "\\Printserver2" }

        'Site 3' { $PrintServer = "\\Printserver3" }

        'Site 4' { $PrintServer = "\\Printserver3" }

        'Site 5' { $PrintServer = "\\Printserver4" }

        'Site 6' { $PrintServer = "\\Printserver5" }

        'Site 7' { $PrintServer = "\\Printserver6" }

    }

}

$DropDownBox1.add_SelectedIndexChanged($Global:DropDownBox1_SelectedIndexChanged)

$Form.Controls.Add($DropDownBox1)
</code>```

In Dropdownbox2 there will be the list of printers available to install

```<code>    $DropDownBox2 = New-Object System.Windows.Forms.ComboBox

$DropDownBox2.Text = "Select the Printer to install"

$DropDownBox2.Location = New-Object System.Drawing.Size(20, 60)

$DropDownBox2.Size = New-Object System.Drawing.Size(180, 20)

$DropDownBox2.DropDownHeight = 200

$DropDownBox2.add_SelectedIndexChanged({ })

$Form.Controls.Add($DropDownBox2)
</code>```

As is, everything works fine, I can select a site in Drowndownbox1, hit Fetch Printers button, Dropdownbox2 shows the printers available for that site.

The issue I'm having is when I attempt to select another site (in the same form), and hit the Fetch Printers button, the $Printers variable  is retaining it's old data it looks like, so the Dropdownbox2 contains Printers from the previous query, and the current.

Ideally whenever I select a site, hit fetch printers, dropdownbox2 contains info only for that Site.

I've tried using the Clear-Variable cmdlet, but it's doesn't seem to do the trick, but it's also possible I am doing something wrong, and not thinking of this correctly.

any help is greatly appreciated.

答:
Looks like adding: </p>

```<code>$dropdownbox2.Items.Clear()
</code>```

<p>... to my function does what I need. Could have sworn I tried this, but maybe the syntax was wrong.</p>

Title: Winform: Trouble updating combobox

Body:
I am working on a Windows Form using Powershell that will query a print server for all Printers Installed (function: FetchPrinters). I have a button added to run the FetchPrinters function.

Function:

    $Global:PrintServer = ""
function FetchPrinters {
    $printerTxtFileLocation = 'C:\Temp\PrinterList.csv'
    $outputBox.text = "Fetching list of printers on $Global:PrintServer"
    # $Global:PrintServer = $Global:DropDownBox1.SelectedItem.ToString()
    Get-Printer -ComputerName "$Global:PrintServer" | Select-Object -ExpandProperty Name | Sort-Object -CaseSensitive | Out-File -Force -Encoding utf8 -FilePath "$printerTxtFileLocation"
    $PrinterList = Get-Content -Path "$printerTxtFileLocation" -Encoding UTF8 -Force
    foreach ($Printer in $PrinterList) {
        $DropDownBox2.ResetText()
        [void] $DropDownBox2.Items.Add($Printer)
    }
}

In Dropdownbox1, there will be a list of sites (location), that when selected will determine what Print Server to query.

    $DropDownBox1 = New-Object System.Windows.Forms.ComboBox

$DropDownBox1.Text = "Select Site Name"

$DropDownBox1.Size = New-Object System.Drawing.Size(190, 20)

$DropDownBox1.Location = New-Object System.Drawing.Point(20, 20)

$Sites = @(

    'Site 1',

    'Site 2',

    'Site 3',

    'Site 4',

    'Site 5',

    'Site 6'

    'Site 7'

)

ForEach ($Site in $Sites) {

    $DropDownBox1.Items.Add($Site) | Out-Null

}

$Global:DropDownBox1_SelectedIndexChanged = {

    Switch ($DropDownBox1.Text) {

        'Site 1' { $Global:PrintServer = "\\Printserver1" }

        'Site 2' { $PrintServer = "\\Printserver2" }

        'Site 3' { $PrintServer = "\\Printserver3" }

        'Site 4' { $PrintServer = "\\Printserver3" }

        'Site 5' { $PrintServer = "\\Printserver4" }

        'Site 6' { $PrintServer = "\\Printserver5" }

        'Site 7' { $PrintServer = "\\Printserver6" }

    }

}

$DropDownBox1.add_SelectedIndexChanged($Global:DropDownBox1_SelectedIndexChanged)

$Form.Controls.Add($DropDownBox1)

In Dropdownbox2 there will be the list of printers available to install

    $DropDownBox2 = New-Object System.Windows.Forms.ComboBox

$DropDownBox2.Text = "Select the Printer to install"

$DropDownBox2.Location = New-Object System.Drawing.Size(20, 60)

$DropDownBox2.Size = New-Object System.Drawing.Size(180, 20)

$DropDownBox2.DropDownHeight = 200

$DropDownBox2.add_SelectedIndexChanged({ })

$Form.Controls.Add($DropDownBox2)

As is, everything works fine, I can select a site in Drowndownbox1, hit Fetch Printers button, Dropdownbox2 shows the printers available for that site.

The issue I'm having is when I attempt to select another site (in the same form), and hit the Fetch Printers button, the $Printers variable  is retaining it's old data it looks like, so the Dropdownbox2 contains Printers from the previous query, and the current.

Ideally whenever I select a site, hit fetch printers, dropdownbox2 contains info only for that Site.

I've tried using the Clear-Variable cmdlet, but it's doesn't seem to do the trick, but it's also possible I am doing something wrong, and not thinking of this correctly.

any help is greatly appreciated.

Body:
Looks like adding:

$dropdownbox2.Items.Clear()

... to my function does what I need. Could have sworn I tried this, but maybe the syntax was wrong.


来源: stackexchange

问:
Why does THREAD_MODE_BACKGROUND_BEGIN cause my code to run 20x slower than THREAD_PRIORITY_LOWEST?
So I won't bore you with why, but my application can optionally perform some integrity checking on very large files (Up to 50gb) using CRC.  Because I don't want to kill user's machines if they turn this option on I set the IoPriorityHintVeryLow hint on the handle and also was setting the thread priority to THREAD_MODE_BACKGROUND_BEGIN using this API.

The time consuming part of my code looks like this:

```<code>//
// Read one block of the changed data at a time, checking each CRC
//
DWORD blockNum = 0;
vector<BYTE> changeBuffer(DIRTY_BLOCK_SIZE);
outputDirtyBlockMap.reserve(crcList.size() / 8);
while (::ReadFile(hChangedFile, changeBuffer.data(), DIRTY_BLOCK_SIZE, &bytesRead, NULL) && bytesRead > 0)
{
    // Check for cancellation every 500 blocks, doing it every time reduces CPU performance by 50% since WaitForSingleObject is quite expensive
    if ((blockNum % 500 == 0) && IsCancelEventSignalled(hCancel))
    {
        RETURN_TRACED(ERROR_CANCELLED);
    }

    // Increase the size of the dirty block map?
    ULONG mapByte = blockNum / 8;
    if (mapByte == outputDirtyBlockMap.size())
    {
        outputDirtyBlockMap.resize(mapByte + 1);
    }

    DWORD mapBitNum = blockNum & 0x7L;
    UCHAR mapBit = 1 << (7 - mapBitNum);
    if (driverDirtyBlockMap.size() > mapByte && (driverDirtyBlockMap[mapByte] & mapBit))
    {
        //
        // The bit is already set in the drivers block map, we don't have to bother generating comparing CRCs for this block
        //
        outputDirtyBlockMap[mapByte] |= mapBit;
    }
    else
    {
        // Validate that the CRC hasn't changed, if it has, mark it as such in the dirty block map
        DWORD newCrc = CRC::Crc32(changeBuffer.data(), changeBuffer.size());
        if ((blockNum >= crcList.size() || newCrc != crcList[blockNum]))
        {
            OPTIONAL_DEBUG(DEBUG_DIRTY_BLOCK_MAP & DEBUG_VERBOSE, "Detected change at block [%u], CRC [new 0x%x != old 0x%x]", blockNum, newCrc, blockNum < crcList.size() ? crcList[blockNum] : 0x0);

            // The CRC is changed or the file has grown, mark it as such in the dirty block map
            outputDirtyBlockMap[mapByte] |= mapBit;
        }
    }

    ++blockNum;
}
</code>```

When I was profiling this code I was very surprised to find that when this loop runs in THREAD_MODE_BACKGROUND_BEGIN it takes 74 seconds to run over a 500Mb file.  When running with THREAD_PRIORITY_LOWEST it takes 2.7 seconds to run over a 500Mb file.  (I've tested this around 8 times now and that was the average)

In both cases the machine I was testing on was idle other than running this loop.  So question:

Why does THREAD_MODE_BACKGROUND_BEGIN make this take so long?  I'd have thought that if the machine isn't doing anything else, it should still run as quick as with any other priority because it doesn't need to be prioritized?

Is there something I should know about this priority that I haven't been able to figure out from the docs?

答:
As others have noted, there is a difference between

thread scheduling priority

thread I/O priority

Nowhere is this difference more noticable than Resource Monitor, where you can see some "background" I/O operations take 500 ms:

When it might normally take 7 ms.

SysMain (nee SuperFetch) does everything at Background I/O priority. That's why your hard drive can be churning without SuperFetch affecting the machine.

ContentLicense: CC BY-SA 3.0

Body:
So I won't bore you with why, but my application can optionally perform some integrity checking on very large files (Up to 50gb) using CRC.  Because I don't want to kill user's machines if they turn this option on I set the IoPriorityHintVeryLow hint on the handle and also was setting the thread priority to THREAD_MODE_BACKGROUND_BEGIN using this API.

The time consuming part of my code looks like this:

//
// Read one block of the changed data at a time, checking each CRC
//
DWORD blockNum = 0;
vector<BYTE> changeBuffer(DIRTY_BLOCK_SIZE);
outputDirtyBlockMap.reserve(crcList.size() / 8);
while (::ReadFile(hChangedFile, changeBuffer.data(), DIRTY_BLOCK_SIZE, &bytesRead, NULL) && bytesRead > 0)
{
    // Check for cancellation every 500 blocks, doing it every time reduces CPU performance by 50% since WaitForSingleObject is quite expensive
    if ((blockNum % 500 == 0) && IsCancelEventSignalled(hCancel))
    {
        RETURN_TRACED(ERROR_CANCELLED);
    }

    // Increase the size of the dirty block map?
    ULONG mapByte = blockNum / 8;
    if (mapByte == outputDirtyBlockMap.size())
    {
        outputDirtyBlockMap.resize(mapByte + 1);
    }

    DWORD mapBitNum = blockNum & 0x7L;
    UCHAR mapBit = 1 << (7 - mapBitNum);
    if (driverDirtyBlockMap.size() > mapByte && (driverDirtyBlockMap[mapByte] & mapBit))
    {
        //
        // The bit is already set in the drivers block map, we don't have to bother generating comparing CRCs for this block
        //
        outputDirtyBlockMap[mapByte] |= mapBit;
    }
    else
    {
        // Validate that the CRC hasn't changed, if it has, mark it as such in the dirty block map
        DWORD newCrc = CRC::Crc32(changeBuffer.data(), changeBuffer.size());
        if ((blockNum >= crcList.size() || newCrc != crcList[blockNum]))
        {
            OPTIONAL_DEBUG(DEBUG_DIRTY_BLOCK_MAP & DEBUG_VERBOSE, "Detected change at block [%u], CRC [new 0x%x != old 0x%x]", blockNum, newCrc, blockNum < crcList.size() ? crcList[blockNum] : 0x0);

            // The CRC is changed or the file has grown, mark it as such in the dirty block map
            outputDirtyBlockMap[mapByte] |= mapBit;
        }
    }

    ++blockNum;
}

When I was profiling this code I was very surprised to find that when this loop runs in THREAD_MODE_BACKGROUND_BEGIN it takes 74 seconds to run over a 500Mb file.  When running with THREAD_PRIORITY_LOWEST it takes 2.7 seconds to run over a 500Mb file.  (I've tested this around 8 times now and that was the average)

In both cases the machine I was testing on was idle other than running this loop.  So question:

Why does THREAD_MODE_BACKGROUND_BEGIN make this take so long?  I'd have thought that if the machine isn't doing anything else, it should still run as quick as with any other priority because it doesn't need to be prioritized?

Is there something I should know about this priority that I haven't been able to figure out from the docs?

ContentLicense: CC BY-SA 4.0


问:
Refreshing static content with Spring MVC and Boot
I'm evaluating Spring MVC & Boot and AngularJs for building web applications. I've run into the problem that when I make modifications to my static content (html, js, css), I have to restart the application every time. I hope there is a some way of solving that because restarting the whole application for static content changes is not efficient. Every other web app framework I've tried allows updating static content files on the fly(even just Spring MVC and plain old WAR application).

I've setup my project from "Building a RESTful Web Service with Spring Boot Actuator" guide (http://spring.io/guides/gs/actuator-service/). Basically it uses Spring Boot and MVC controllers to create a REST service. In addition, I've used "Consuming a RESTful Web Service with AngularJS" guide (http://spring.io/guides/gs/consuming-rest-angularjs/) to build a frontend with AngularJS. It creates a web page that displays the response from the REST service. The only change I've made is that the requests are made to my application instead of "http://rest-service.guides.spring.io/greeting". My static content is stored in "src/main/resources/public" folder. This setup works correctly except it doesn't reload static content.

答:
For Spring Boot 2+ with gradle Kotlin dsl:

```<code>tasks.bootRun {
    sourceResources(sourceSets.getAt(SourceSet.MAIN_SOURCE_SET_NAME))
}
</code>```

thanks to @briskr's answer for the gradle dsl version :)

Body:
For Spring Boot 2+ with gradle Kotlin dsl:

tasks.bootRun {
    sourceResources(sourceSets.getAt(SourceSet.MAIN_SOURCE_SET_NAME))
}

thanks to @briskr's answer for the gradle dsl version :)


问:
Jenkins JNLP port exposes internal ip
We have configured our Jenkins server to use a fixed port and JNLP 4.
Our info sec team has flagged that if one were to open a web browser pointing at the JNLP port, the internal properties below are listed which includes the internal ip of the Jenkins server.

Jenkins-Agent-Protocols:
Jenkins-Version:
Jenkins-Session:
Client:
Server:
Remoting-Minimum-Version:

Is this information necessary? Is this something which can be suppressed?

答:
From the source: https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/TcpSlaveAgentListener.java

It looks like there is no mechanism to turn it off, and according to the comments, it seems to be only for testing:

```<code>String header = new String(head, Charsets.US_ASCII);
if (header.startsWith("GET ")) {
    // this looks like an HTTP client
    respondHello(header,s);
    return;
}

// otherwise assume this is AgentProtocol and start from the beginning
</code>```

(...)

```<code>/**
 * Respond to HTTP request with simple diagnostics.
 * Primarily used to test the low-level connectivity.
 */
private void respondHello(String header, Socket s) throws IOException {
</code>```

(...)

If infosec requires you to turn this off, you might need to open a support ticket with cloudbees.

Title: Jenkins JNLP port exposes internal ip

Body:
From the source: https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/TcpSlaveAgentListener.java

It looks like there is no mechanism to turn it off, and according to the comments, it seems to be only for testing:

String header = new String(head, Charsets.US_ASCII);
if (header.startsWith("GET ")) {
    // this looks like an HTTP client
    respondHello(header,s);
    return;
}

// otherwise assume this is AgentProtocol and start from the beginning

(...)

/**
 * Respond to HTTP request with simple diagnostics.
 * Primarily used to test the low-level connectivity.
 */
private void respondHello(String header, Socket s) throws IOException {

(...)

If infosec requires you to turn this off, you might need to open a support ticket with cloudbees.


问:
Highcharts polygon with no fill
How can I create a Highcharts polygon plot with border line but without fill?

```<code>$(function() {

  $('#container').highcharts({
    series: [{
      name: 'Target',
      type: 'polygon',
      data: [
        [153, 42],
        [149, 46],
        [149, 55],
        [152, 60],
        [159, 70],
        [170, 77],
        [180, 70],
        [180, 60],
        [173, 52],
        [166, 45]
      ]
    }],
  });
});
</code>```

http://jsfiddle.net/s3zp8cce/

答:
Use scatter series type:

```<code>series: [{
  type: 'scatter',
  lineWidth: 2,
  data: [...]
}]
</code>```

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4874/

API Reference: https://api.highcharts.com/highcharts/series.scatter.lineWidth

Title: Highcharts polygon with no fill

Body:
How can I create a Highcharts polygon plot with border line but without fill?

$(function() {

  $('#container').highcharts({
    series: [{
      name: 'Target',
      type: 'polygon',
      data: [
        [153, 42],
        [149, 46],
        [149, 55],
        [152, 60],
        [159, 70],
        [170, 77],
        [180, 70],
        [180, 60],
        [173, 52],
        [166, 45]
      ]
    }],
  });
});

http://jsfiddle.net/s3zp8cce/

Body:
Use scatter series type:

series: [{
  type: 'scatter',
  lineWidth: 2,
  data: [...]
}]

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4874/

API Reference: https://api.highcharts.com/highcharts/series.scatter.lineWidth


问:
Configure vbs "hello world" script for EditPlus user tool
How do I configure an EditPlus user tool (Preferences dialog box) to execute a vbs script that simply pastes a "Hello World" string to an open file?  I use editPlus version 3.30/</p>

答:
EditPlus text editor: How to create a script that will paste a string.  The script can serve as a  user toolbar item to paste custom code snippets.

Configure the Preference/Tools dialog like this:

Command:

Cscript.exe "$(AppDir)\filters\Pastetext.js"

Argument: //NoLogo $(CurRow)

leave initial directory blank

Action:

```<code>Run as text (Insert)
</code>```

Save Option: Select "Current file"

Save the following line as Pastetext.js in the appropriate directory

```<code>`WScript.echo("Hello World");`
</code>```

The string will print where your cursor is in an open document.

Body:
EditPlus text editor: How to create a script that will paste a string.  The script can serve as a  user toolbar item to paste custom code snippets.

Configure the Preference/Tools dialog like this:

Command:

Cscript.exe "$(AppDir)\filters\Pastetext.js"

Argument: //NoLogo $(CurRow)

leave initial directory blank

Action:

Run as text (Insert)

Save Option: Select "Current file"

Save the following line as Pastetext.js in the appropriate directory

`WScript.echo("Hello World");`

The string will print where your cursor is in an open document.


问:
Can Xero contacts be filtered (by name) case insensitive?
Using the Where filter with Contacts, is it possible to make the term Name.Contains("Peter") not case sensitive?

答:
You can use ToLower() to achieve this - make your where clause something like:

```<code>Name.ToLower().Contains("peter")
</code>```

Body:
You can use ToLower() to achieve this - make your where clause something like:

Name.ToLower().Contains("peter")


问:
Cube.js unable to join table from different dataSources
In my cube.js server I have 2 tables from different data sources(both of them are postgres). I'm trying to create a join on these tables but get the following error

Error: Joins across data sources aren't supported in community edition. Found data sources: dataSource_1, dataSource_2

I have student_details cube and test_results cube (both cubes from different data source).

I'm trying to achieve a join on student id (test_results cube) and id (student_details cube ) but get the above error in bold.

Any help or work around for this would be appreciated.

Thanks in advance

答: As error says this feature isn't part of open source Cube.js edition. As of now there's no way you can do it using open source Cube.js edition unless you implement it yourself.</p>


问:
Return count of rows on today's date grouped by the hour w/ 0's for hours with no count
I am trying to get the count of rows within a hour, starting with 12 am to the current hour. I currently am getting the last 24 hours easily, but am unsure how start the series with 2/17/2020 12:00 am up to the current time.

Here is what I have currently returning the last 24 hours where hours with no count return 0:

```<code>with hour_range as (
    select generate_series(date_trunc('hour', now() - interval '23 hours'), date_trunc('hour', now()), '1 hour':: interval) as hour
),

hour_count as (
    select date_trunc('hour', local_start_time) as hour,
        count (*) as ct
    from call_data.rc_api_call_logs
    where local_start_time::date = current_date -- today
    and br_call_flag = 1
    group by 1
)

select to_char(hour_range.hour, 'Mon DD YYYY HH12:MI:SSam'),
       coalesce(hour_count.ct, 0)
from hour_range
left outer join hour_count on hour_range.hour = hour_count.hour;
</code>```

Also I am just reformatting military time to normal time in my last select for readability. The local_start_time is of timestamp type. The issue is really with the generate_series query, and fixing the start time since I am using it to join to get the hours with count 0.

EDIT: Any suggestions for performance will be helpful, otherwise I will accept my answer.

答:
Did some more research and realized casting current_time to a timestamp gives the current date with 0:00:00 as the timestamp.

Therefore:

current_date::timestamp -- returns 2020-2-17 00:00:00

select generate_series(date_trunc('hour', current_date::timestamp),
                       date_trunc('hour', now()), '1 hour':: interval) as hour; -- 2020-2-17 0:00:00 to 2020-2-17 current time
```

<p>As mentioned in the comments by user, this works as well:</p>

```current_date + time '00:00:00' -- 2020-2-17 00:00:00
```

Body:
I am trying to get the count of rows within a hour, starting with 12 am to the current hour. I currently am getting the last 24 hours easily, but am unsure how start the series with 2/17/2020 12:00 am up to the current time.

Here is what I have currently returning the last 24 hours where hours with no count return 0:

with hour_range as (
    select generate_series(date_trunc('hour', now() - interval '23 hours'), date_trunc('hour', now()), '1 hour':: interval) as hour
),

hour_count as (
    select date_trunc('hour', local_start_time) as hour,
        count (*) as ct
    from call_data.rc_api_call_logs
    where local_start_time::date = current_date -- today
    and br_call_flag = 1
    group by 1
)

select to_char(hour_range.hour, 'Mon DD YYYY HH12:MI:SSam'),
       coalesce(hour_count.ct, 0)
from hour_range
left outer join hour_count on hour_range.hour = hour_count.hour;

Also I am just reformatting military time to normal time in my last select for readability. The local_start_time is of timestamp type. The issue is really with the generate_series query, and fixing the start time since I am using it to join to get the hours with count 0.

EDIT: Any suggestions for performance will be helpful, otherwise I will accept my answer.

Body:
Did some more research and realized casting current_time to a timestamp gives the current date with 0:00:00 as the timestamp.

Therefore:

current_date::timestamp -- returns 2020-2-17 00:00:00

select generate_series(date_trunc('hour', current_date::timestamp),
                       date_trunc('hour', now()), '1 hour':: interval) as hour; -- 2020-2-17 0:00:00 to 2020-2-17 current time

As mentioned in the comments by user, this works as well:

current_date + time '00:00:00' -- 2020-2-17 00:00:00


问:
Outlook-Addin: How to retrive folder tree fast when Exchange-Online is used
I'm using Outlook Redemption library.

I am trying to retrieve the folder list of an Outlook store. I only need folders which meet a some criterias and only need their name and there DefaultMessageClass.

Iteration the RDOFolder objects is quite slow when an Exchange Account without a cached is used.

So I played around with the GetAllChildFolders() and combined it the the RODFolderItems findmethod.

http://www.dimastr.com/redemption/RDOFolders.htm

var allFolder = ((RDOFolder2)rootFolder).GetAllChildFolders();

string folderSelect = "SELECT Name, EntryId, DefaultMessageClass FROM  FOLDER WHERE \"http://schemas.microsoft.com/mapi/proptag/0x3613001F\" like '%Note%'";

try
{
RDOFolder vFolder = vFolders.Find(folderSelect);

  while (vFolder != null)
  {
    System.Diagnostics.Debug.WriteLine(vFolder.Name);
    System.Diagnostics.Debug.WriteLine(vFolder.EntryID);
    System.Diagnostics.Debug.WriteLine(vFolder.DefaultMessageClass);

    vFolder = vFolders.FindNext();

   }
}
catch (Exception ex)
{
    //log error here!
}

```

Now I got two questions!

1. SQL Syntax

From the docmentation of find method

The properties specified in the SQL query must either use the Outlook Object Model (or RDO)
  property name (e.g. Subject, Email1Address)

I can't make Outlook or Redemption properties work within the SQL statement. Has somebody a working example?

2. Performance access properties

The online documentation states the following.

Including the SELECT clause allows Redemption to pre-fetch the
  properties from the folder hierarchy table without opening the item
  resulting in a significant performance gain (see example "I wish there was one :-)"). If you
  later access a property not specified in the SELECT clause, Redemption
  will open the item.

How do I access the properties prefetch from the folder hierarchy?
If I use RDOFolder.Name, the whole folder object is opened and there is not much of an performance gain.

答:
Which properties do not work? Are you getting a particular error?

What is your full SELECT statement? To avoid the chance of opening a folder, use RDOFolders.MAPITable.ExecSQL - it will
return an ADODB.Recordset object.

Body:
I'm using Outlook Redemption library.

I am trying to retrieve the folder list of an Outlook store. I only need folders which meet a some criterias and only need their name and there DefaultMessageClass.

Iteration the RDOFolder objects is quite slow when an Exchange Account without a cached is used.

So I played around with the GetAllChildFolders() and combined it the the RODFolderItems findmethod.

http://www.dimastr.com/redemption/RDOFolders.htm

var allFolder = ((RDOFolder2)rootFolder).GetAllChildFolders();

string folderSelect = "SELECT Name, EntryId, DefaultMessageClass FROM  FOLDER WHERE \"http://schemas.microsoft.com/mapi/proptag/0x3613001F\" like '%Note%'";

try
{
RDOFolder vFolder = vFolders.Find(folderSelect);

  while (vFolder != null)
  {
    System.Diagnostics.Debug.WriteLine(vFolder.Name);
    System.Diagnostics.Debug.WriteLine(vFolder.EntryID);
    System.Diagnostics.Debug.WriteLine(vFolder.DefaultMessageClass);

    vFolder = vFolders.FindNext();

   }
}
catch (Exception ex)
{
    //log error here!
}

Now I got two questions!

1. SQL Syntax

From the docmentation of find method

The properties specified in the SQL query must either use the Outlook Object Model (or RDO)
  property name (e.g. Subject, Email1Address)

I can't make Outlook or Redemption properties work within the SQL statement. Has somebody a working example?

2. Performance access properties

The online documentation states the following.

Including the SELECT clause allows Redemption to pre-fetch the
  properties from the folder hierarchy table without opening the item
  resulting in a significant performance gain (see example "I wish there was one :-)"). If you
  later access a property not specified in the SELECT clause, Redemption
  will open the item.

How do I access the properties prefetch from the folder hierarchy?
If I use RDOFolder.Name, the whole folder object is opened and there is not much of an performance gain.


问:
What Development and Build Lifecycle Tools Do You Use?
I'm working on transitioning my current project of about 20 developers to a modern development and build environment.  We currently use an RCS based source control system and an associated issue tracking system, both with Motif UIs.  There is no formal production build process, its just whatever works.

I'm interested in:

Development Tools

Version Control

Issue Tracking

Dependency Management

Configuration Management

Automated Building

Automated Testing

Continuous Integration

Artifact Management

Release Management

Deployment Management

Requirements Tracing

What else?

I'm interested in not just which tools you use, but how well the integrate with each other, how easy they are to setup and use, and how both developers and management likes them.  Our project is a combination of Java, C++, and VHDL, but I'd still like to hear from people with other languages.  I'm currently going down the path of eclipse, subversion, trac, maven, hudson, and nexus.

Also, is there a better term than "Build Lifecycle" that encompasses not just building, but the flow of code from when the developer creates it to when its built, tested, and in a production system?  "Build Lifecycle" seems limited, but "Project Lifecycle" is already taken.

答:
Development Tools JetBrains IntelliJ IDEA

Version Control Subversion

Issue Tracking Atlassian Jira

Dependency Management Maven

Configuration Management TeamCity

Automated Building TeamCity

Automated Testing JUnit(?)

Continuous Integration TeamCity

Artifact Management Maven

Release Management Homo Sapien

Deployment Management Maven/Homo Sapien

Requirements Tracing Wishful thinking

One-Off Automation Bash

Developer-to-Developer Documentation MediaWiki

OwnerDisplayName: John Ellinwood

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Ellinwood

OwnerDisplayName: cynoclast


问:
umbraco - usercontrols - umbracoNaviHide
I know I can get the current node with 'var top = Node.GetCurrent();' but I cant seem to find where I can get the related properties, specifically 'umbracoNaviHide'. I'd like to know how to access the same data that is accessible from XSLT in a user control</p>

答:
To get properties you need to use the GetProperty() method.

var top = Node.GetCurrent();
top.GetProperty("umbracoNaviHide").Value;


问:
BASH: unescape string
Suppose I have the following string:

```<code>"some\nstring\n..."
</code>```

And it displays as one line when catted in bash. Further,

```<code>string_from_pipe | sed 's/\\\\/\\/g' # does not work
| awk '{print $0}'
| awk '{s = $0; print s}'
| awk '{s = $0; printf "%s",s}'
| echo $0
| sed 's/\\(.)/\1/g'
# all have not worked.
</code>```

How do I unescape this string such that it prints as:

```<code>some
string
</code>```

Or even displays that way inside a file?

答:
How about using the -e option of echo?

```<code>$ s="some\nstring\n..." && echo -e "$s"
some
string
...
</code>```

From the echo man-page

```<code>  -e    enable interpretation of the following backslash escapes
  [...]
      \a    alert (bell)
      \b    backspace
      \c    suppress further output
      \e    escape character
      \f    form feed
      \n    new line
      \r    carriage return
      \t    horizontal tab
      \v    vertical tab
      \\    backslash
      \0nnn the character whose ASCII code is NNN (octal).  NNN can be 0 to 3 octal digits
      \xHH  the eight-bit character whose value is HH (hexadecimal).  HH can be one or two hex digits
</code>```

Title: BASH: unescape string

Body:
Suppose I have the following string:

"some\nstring\n..."

And it displays as one line when catted in bash. Further,

string_from_pipe | sed 's/\\\\/\\/g' # does not work
| awk '{print $0}'
| awk '{s = $0; print s}'
| awk '{s = $0; printf "%s",s}'
| echo $0
| sed 's/\\(.)/\1/g'
# all have not worked.

How do I unescape this string such that it prints as:

some
string

Or even displays that way inside a file?

Body:
How about using the -e option of echo?

$ s="some\nstring\n..." && echo -e "$s"
some
string
...

From the echo man-page

  -e    enable interpretation of the following backslash escapes
  [...]
      \a    alert (bell)
      \b    backspace
      \c    suppress further output
      \e    escape character
      \f    form feed
      \n    new line
      \r    carriage return
      \t    horizontal tab
      \v    vertical tab
      \\    backslash
      \0nnn the character whose ASCII code is NNN (octal).  NNN can be 0 to 3 octal digits
      \xHH  the eight-bit character whose value is HH (hexadecimal).  HH can be one or two hex digits


问:
Emulate Google Cloud Storage in local/dev kubernetes cluster
I’m working on an application that will use Google Cloud Storage to save files and I was wondering: what’s the best way to emulate it for development?

The application will run on kubernetes, and I was planning to run a development environment on my machine using Minikube (or similar). I know I can set up a different storage for development purposes but I was wondering if there was a way to avoid charges and most important to be able to work offline.

Thanks in advance

答:
There is another alternative since a few days: https://pypi.org/project/gcloud-storage-emulator/

Although it is still in its early fase, it could be a viable alternative when using python.


问:
Prolog Program Not Merging Sorted Lists Correctly
I have a simple program I'm trying to write in Prolog. Essentially, as I learning exercise, I'm trying to write a program that takes two sorted lists as input, and returns the merged list that is also sorted. I have dubbed the predicate "merge2" as to no be confused with the included predicate "merge" that seems to do this already.

I am using recursion. My implementation is below

```<code>merge2([],[],[]).
merge2([X],[],[X]).
merge2([],[Y],[Y]).
merge2([X|List1],[Y|List2],[X|List]):- X =< Y,merge2(List1,[Y|List2],List).
merge2([X|List1],[Y|List2],[Y|List]):- merge2([X|List1],List2,List).
</code>```

When I run this, I get X = [1,2,4,5,3,6] which is obviously incorrect. I've been able to code multiple times and tried to draw out the recursion. To the best of my knowledge, this should be returning the correct result. I'm not sure why the actualy result is so strange.

Thank you.

答:
QuickCheck is your friend. In this case, the property that you want to verify can be expressed using the following predicate:

```<code>sorted(L1, L2) :-
    sort(L1, S1),
    sort(L2, S2),
    merge2(S1, S2, L),
    sort(L, S),
    L == S.
</code>```

Note that sort/2 is a standard Prolog built-in predicate. Using the QuickCheck implementation provided by Logtalk's lgtunit tool, which you can run using most Prolog systems, we get:

```<code>?- lgtunit::quick_check(sorted(+list(integer),+list(integer))).
*     quick check test failure (at test 2 after 0 shrinks):
*       sorted([0],[0])
false.
</code>```

I.e. you code fails for L1 = [0] and L2 = [0]:

```<code>?- merge2([0], [0], L).
L = [0, 0] ;
L = [0, 0] ;
false.
</code>```

Tracing this specific query should allow you to quickly find at least one of the bugs in your merge2/4 predicate definition. In most Prolog systems, you can simply type:

```<code>?- trace, merge2([0], [0], L).
</code>```

If you want to keep duplicates in the merged list, you can use the de facto standard predicates msort/2 in the definition of the property:

```<code>sorted(L1, L2) :-
    sort(L1, S1),
    sort(L2, S2),
    merge2(S1, S2, L),
    msort(L, S),
    L == S.
</code>```

In this case, running QuickCheck again:

```<code>?- lgtunit::quick_check(sorted(+list(integer),+list(integer))).
*     quick check test failure (at test 3 after 8 shrinks):
*       sorted([],[475,768,402])
false.
</code>```

This failure is more informative if you compare the query with your clauses that handle the case where the first list is empty...

Body:
I have a simple program I'm trying to write in Prolog. Essentially, as I learning exercise, I'm trying to write a program that takes two sorted lists as input, and returns the merged list that is also sorted. I have dubbed the predicate "merge2" as to no be confused with the included predicate "merge" that seems to do this already.

I am using recursion. My implementation is below

merge2([],[],[]).
merge2([X],[],[X]).
merge2([],[Y],[Y]).
merge2([X|List1],[Y|List2],[X|List]):- X =< Y,merge2(List1,[Y|List2],List).
merge2([X|List1],[Y|List2],[Y|List]):- merge2([X|List1],List2,List).

When I run this, I get X = [1,2,4,5,3,6] which is obviously incorrect. I've been able to code multiple times and tried to draw out the recursion. To the best of my knowledge, this should be returning the correct result. I'm not sure why the actualy result is so strange.

Thank you.

Body:
QuickCheck is your friend. In this case, the property that you want to verify can be expressed using the following predicate:

sorted(L1, L2) :-
    sort(L1, S1),
    sort(L2, S2),
    merge2(S1, S2, L),
    sort(L, S),
    L == S.

Note that sort/2 is a standard Prolog built-in predicate. Using the QuickCheck implementation provided by Logtalk's lgtunit tool, which you can run using most Prolog systems, we get:

?- lgtunit::quick_check(sorted(+list(integer),+list(integer))).
*     quick check test failure (at test 2 after 0 shrinks):
*       sorted([0],[0])
false.

I.e. you code fails for L1 = [0] and L2 = [0]:

?- merge2([0], [0], L).
L = [0, 0] ;
L = [0, 0] ;
false.

Tracing this specific query should allow you to quickly find at least one of the bugs in your merge2/4 predicate definition. In most Prolog systems, you can simply type:

?- trace, merge2([0], [0], L).

If you want to keep duplicates in the merged list, you can use the de facto standard predicates msort/2 in the definition of the property:

sorted(L1, L2) :-
    sort(L1, S1),
    sort(L2, S2),
    merge2(S1, S2, L),
    msort(L, S),
    L == S.

In this case, running QuickCheck again:

?- lgtunit::quick_check(sorted(+list(integer),+list(integer))).
*     quick check test failure (at test 3 after 8 shrinks):
*       sorted([],[475,768,402])
false.

This failure is more informative if you compare the query with your clauses that handle the case where the first list is empty...


问:
How firebase order documents in database (cloud firestore)
How firebase order to docs???, i said that because the docs have a special comportament and idk why.Thx

See to know what i mean:

答:
There's a little filter icon at the top of that document list:

If you click that, you'll get the option to sort the document list on any fields.


问:
Create Google Contact with Node.js and Service Account
I would like to create a script to be scheduled in a .bat file that automatically links to google contacts and creates contacts read in a Mysql Database.

I would like a system that does not require any user action.

I know that service-account exist but I have no idea how to create the program. Do you know how to do it?

I hope you can give me a hand.

For the moment, I wish you a good day.

答:
This can be done in three steps if the user is not part of G Suite.

Authenticate the user using OAuth with access_type = offline.

Save the generated Refresh Token.

Use the Refresh Token to generate a new Access Token and then update the account's contacts. The Access Token will be valid (default) for 3,600 seconds.

If the user is part of G Suite, then enable Domain Wide Delegation on a service account and impersonate the user.


问:
Laravel - Query to mysql DB
I am new to Laravel. I have a existing and working query that allow me to get all the item present in my Mysql Table.
File --> ProductRepostitory.php

```<code>Public function getAll(){
        $data = Product::paginate(10);
        if(empty($data)){
            return false;
        }else{
            return $data;
        }
    }
</code>```

In that table I have a column named PR_ACTIF --> 1 or 0.
I would like to display in the query only PR_ACTIF = 1
Thanks for you help!

答:
Try this</p>

```<code>...
Public function getAll(){
    $data = Product::where('PR_ACTIF', 1)->paginate(10);
    if(empty($data)){
        return false;
    }else{
        return $data;
    }
}
...
</code>```

Title: Laravel - Query to mysql DB

Body:
I am new to Laravel. I have a existing and working query that allow me to get all the item present in my Mysql Table.
File --> ProductRepostitory.php

Public function getAll(){
        $data = Product::paginate(10);
        if(empty($data)){
            return false;
        }else{
            return $data;
        }
    }

In that table I have a column named PR_ACTIF --> 1 or 0.
I would like to display in the query only PR_ACTIF = 1
Thanks for you help!

Body:
Try this

...
Public function getAll(){
    $data = Product::where('PR_ACTIF', 1)->paginate(10);
    if(empty($data)){
        return false;
    }else{
        return $data;
    }
}
...


问:
Check if a value is within a range of numbers
I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.

The range is 0.001-0.009. I know how to use multiple if to check this, but I want to know if there is any way to check it in a single if statement.

答:
If you're already using lodash, you could use the inRange() function:
https://lodash.com/docs/4.17.15#inRange

_.inRange(3, 2, 4);
// => true

_.inRange(4, 8);
// => true

_.inRange(4, 2);
// => false

_.inRange(2, 2);
// => false

_.inRange(1.2, 2);
// => true

_.inRange(5.2, 4);
// => false

_.inRange(-3, -2, -6);
// => true
```


问:
Helper script or dockerfile commands in dockerfile
I have a question about best practices. Which method is recommended.

Having a helper script install-plugins.sh that installs all that is required during build time. Or...

Having the installations occur in the dockerfile by using RUN commands.

I know the 1st one enhances the readability of the dockerfile. How are these 2 comparable? And which is the better one?

Thanks

答:
You can use entrypoint for this purpose. It will run on each execution of container.

RUN runs only on build time when image creating.

For example, first solution could be implemented when you need to update packages on each container execution but in this case starting it could be more slowly. Also helper could update some Environment settings on each execution.


问:
Lua: "Hide" functions
I want to call c functions from lua to change variables defined in C, but I don't want the lua "user" to realize they are functions.

For example, consider an integer and an array created in c:

```<code>int c_level = 0;
int c_map[4] = {0,0,0,0};
</code>```

Now the program creates a Lua state and runs this:

```<code>set_level(2) --c_level = 2
set_tile(1,23) --c_map[0] = 23
</code>```

I want them to look like this in the lua script:

```<code>L_level = 2
L_map[1] = 23
</code>```

So, L_level and L_map would be functions defined in C.

L_level's argument would be "2".

L_map's arguments are "1" and "23".

Is that possible?.

I can get the lua variables using getglobal, but I wanted to know if I can create some lua functions that look like the ones I showed.

Thanks.

答:
When you set

```<code>L_level = 2
</code>```

you really index the global table _G with the key L_level and set it to 2. What you can do is to set a meta-table for _G and set the function __newindex to a function, that checks if the key is L_level or L_map and handles these cases differently.

This function can be directly a C-function or a Lua-function, that checks the key and calls a c-function if the name matches one of your tracked names, for example like

```<code>setmetatable(_G, {
    __newindex = function (_, k, v)
        if (k == "L_level") then do_setlevel(v)
        elseif (k == "L_map") then do_setmap(v)
        else rawset(_G, k, v)
        endif
    end
})
</code>```

do_setlevel and do_setmap are in this case global c functions. You can of course do all this completely in C, too.

Title: Lua: "Hide" functions

Body:
I want to call c functions from lua to change variables defined in C, but I don't want the lua "user" to realize they are functions.

For example, consider an integer and an array created in c:

int c_level = 0;
int c_map[4] = {0,0,0,0};

Now the program creates a Lua state and runs this:

set_level(2) --c_level = 2
set_tile(1,23) --c_map[0] = 23

I want them to look like this in the lua script:

L_level = 2
L_map[1] = 23

So, L_level and L_map would be functions defined in C.

L_level's argument would be "2".

L_map's arguments are "1" and "23".

Is that possible?.

I can get the lua variables using getglobal, but I wanted to know if I can create some lua functions that look like the ones I showed.

Thanks.

Body:
When you set

L_level = 2

you really index the global table _G with the key L_level and set it to 2. What you can do is to set a meta-table for _G and set the function __newindex to a function, that checks if the key is L_level or L_map and handles these cases differently.

This function can be directly a C-function or a Lua-function, that checks the key and calls a c-function if the name matches one of your tracked names, for example like

setmetatable(_G, {
    __newindex = function (_, k, v)
        if (k == "L_level") then do_setlevel(v)
        elseif (k == "L_map") then do_setmap(v)
        else rawset(_G, k, v)
        endif
    end
})

do_setlevel and do_setmap are in this case global c functions. You can of course do all this completely in C, too.


问:
A compiler's evaluation of the size of an array's declaration. When does it take place?
This is more for clarity or a better understanding of the internal workings of compilers: I'm beginning to study compiler design and compiler theory.

Typically When declaring the size of an array on the stack it has to be known at compile-time and this is understood, but this is not always the case.

What I would like to know is; when does this evaluation occur? Does it happen during the precompiler, tokenizer, syntax analysis, etc.? Also, does it depend on the particular compiler that is being used? Finally, is the point in time of this evaluation specified to be at any particular stage of a compiler within the language standards?

Pseudo Code snippet. C or C++

```<code>int main() {
    int x[5]; // When does the evaluation of the 5 for the array's size take place
              // during the compilation process?
              // Does it take place during pre-compiler or normal compilation time.
    return 0;
}
</code>```

答:
After reading through the comments from various users it has come to my conclusion that there is nothing specific within the standard. There are differences between C and C++ on their implementation details of whether or not variable-sized arrays are permitted within the language within the stack frame.

When it comes to compiler design there is no context for the pre-processor. When it comes to stages of the compiler it depends on the language to which stage it belongs and it appears that it is also agnostic between compilers and their design. It appears that it is left up to the implementation design of the compiler for which stage this evaluation takes place.

Some C++ compilers may do this during syntax analysis while others may do this during tokenization. So in the end, the only true way to determine when this actually takes place is to know the particular compiler inside and out and to read through its own source code to see how it was designed and to step through the process of the compilation stages or phases.

Thank you everyone for your input and feedback. Please, by all means, correct me if I'm wrong by leaving a comment under this answer.

Body:
This is more for clarity or a better understanding of the internal workings of compilers: I'm beginning to study compiler design and compiler theory.

Typically When declaring the size of an array on the stack it has to be known at compile-time and this is understood, but this is not always the case.

What I would like to know is; when does this evaluation occur? Does it happen during the precompiler, tokenizer, syntax analysis, etc.? Also, does it depend on the particular compiler that is being used? Finally, is the point in time of this evaluation specified to be at any particular stage of a compiler within the language standards?

Pseudo Code snippet. C or C++

int main() {
    int x[5]; // When does the evaluation of the 5 for the array's size take place
              // during the compilation process?
              // Does it take place during pre-compiler or normal compilation time.
    return 0;
}


问:
"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte
Here is my code,

```<code>for line in open('u.item'):
# Read each line
</code>```

Whenever I run this code it gives the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte

I tried to solve this and add an extra parameter in open(). The code looks like:

```<code>for line in open('u.item', encoding='utf-8'):
# Read each line
</code>```

But again it gives the same error. What should I do then?

答:
This works:

open('filename', encoding='latin-1')
```
<p>Or:</p>
<pre class="lang-py prettyprint-override"><code>open('filename', encoding="ISO-8859-1")
</code>```

Body:
Here is my code,

for line in open('u.item'):
# Read each line

Whenever I run this code it gives the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte

I tried to solve this and add an extra parameter in open(). The code looks like:

for line in open('u.item', encoding='utf-8'):
# Read each line

But again it gives the same error. What should I do then?

Body:
This works:

open('filename', encoding='latin-1')

Or:

open('filename', encoding="ISO-8859-1")


问:
Notify user if flash player is not installed on his android device
I need to ask user to install flash player, when he install my apps in his android phone and flash player is not already installed, how can I do this with coding ???

Please help me

答:
Try trough Javacode :

```<code>Intent intent = new Intent();

    intent.setComponent(new ComponentName("com.adobe.flashplayer", "com.adobe.flashplayer.FlashExpandableFileChooser"));
    PackageManager pm = getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
    if (activities != null && activities.size() > 0) {
        Toast.makeText(this, "Flash is installed!", Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(this, "Flash not installed!", Toast.LENGTH_LONG).show();
    }
</code>```

Reference : How to check if the Flash players is installed on Android

Body:
Try trough Javacode :

Intent intent = new Intent();

    intent.setComponent(new ComponentName("com.adobe.flashplayer", "com.adobe.flashplayer.FlashExpandableFileChooser"));
    PackageManager pm = getPackageManager();
    List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
    if (activities != null && activities.size() > 0) {
        Toast.makeText(this, "Flash is installed!", Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(this, "Flash not installed!", Toast.LENGTH_LONG).show();
    }

Reference : How to check if the Flash players is installed on Android


问:
Java8: Stream merge two lists
I have two lists

```<code>List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)
</code>```

Want to merge both the list as  (1, 4, 2, 5, 3, 6, 7, 8) using java streams

First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end.

答:
using java streams you can do it easily.
List1.stream().collect(Collectors.toList()).addAll(List2);</p>

Title: Java8: Stream merge two lists

Body:
I have two lists

List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)

Want to merge both the list as  (1, 4, 2, 5, 3, 6, 7, 8) using java streams

First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end.


问:
How to create a manual sum up counter with record logs using Javascript and html?
I need to create a manual input counter using app script editor.

I've already have my website design with a single input textbox, reset button and a disabled box.

What I want is when I input a number in the textbox and press 'Enter' it will be displayed in the disabled box.If I repeat the process the new number in the textbox will sum up to the value inside the disabled box.

I would also like to have a reset button for the disabled box.

Lastly, having a record log of values inside the disabled box.

I really need to finish this before this month ends.

Is this even possible to make by just using html, Javascript and app script?

Here's my code:

```<code>let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  box2.value = e.target.value;
  history.unshift(e.target.value);
  historyContainer.innerHTML += `<p>${e.target.value}</p>`;
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
});
</code>```

I've used this code and apparently when the disabled box has a value and I try to enter a new number inside the input box it just merged with the value inside the disabled box, the new value must sum up to the value inside the disabled box. Also, the history log record all values entered in the textbox and not the previous value in the disabled box.

How can I fix this?

Please someone help me

答:
You just need to convert datatype to number using parseFloat or number:

```<code>box2.value = Number(box2.value) + Number(e.target.value);
</code>```

Live example:

<!DOCTYPE html>

<meta charset="UTF-8" />
<title></title>

    <input id="box1" type="number" />
    <input id="box2" type="number" disabled />
    <button id="reset">Reset</button>

History

```

Body:
I need to create a manual input counter using app script editor.

I've already have my website design with a single input textbox, reset button and a disabled box.

What I want is when I input a number in the textbox and press 'Enter' it will be displayed in the disabled box.If I repeat the process the new number in the textbox will sum up to the value inside the disabled box.

I would also like to have a reset button for the disabled box.

Lastly, having a record log of values inside the disabled box.

I really need to finish this before this month ends.

Is this even possible to make by just using html, Javascript and app script?

Here's my code:

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  box2.value = e.target.value;
  history.unshift(e.target.value);
  historyContainer.innerHTML += `<p>${e.target.value}</p>`;
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
});

I've used this code and apparently when the disabled box has a value and I try to enter a new number inside the input box it just merged with the value inside the disabled box, the new value must sum up to the value inside the disabled box. Also, the history log record all values entered in the textbox and not the previous value in the disabled box.

How can I fix this?

Please someone help me

Body:
You just need to convert datatype to number using parseFloat or number:

box2.value = Number(box2.value) + Number(e.target.value);

Live example:

<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="UTF-8" />
<title></title>
  </head>
  <body>
<div>
  <p>
    <input id="box1" type="number" />
    <input id="box2" type="number" disabled />
    <button id="reset">Reset</button>
    <div id="history">History</div>
  </p>
</div>
<script charset="utf-8">
  let box1 = document.getElementById('box1');
  let box2 = document.getElementById('box2');
  let resetBtn = document.getElementById('reset');
  let historyContainer = document.getElementById('history');
  let history = [];

  //listen key enter press on the input
  box1.addEventListener('keyup', e => {
    if (e.key === 'Enter' && e.target.value !== '') {
      box2.value = Number(box2.value)+ Number(e.target.value);
      history.unshift(e.target.value);
      historyContainer.innerHTML += `<p>${e.target.value}</p>`;
    }
  });
  //reset the second box and
  resetBtn.addEventListener('click', () => {
    box2.value = '';
  });
</script>
  </body>
</html>


问:
Hyper-V installed and enabled
I can see that Hyper-V installed with the following command Get-WindowsFeature and get back a long list where I can see that Hyper-V is crossed under Display name and Installed under Install State.

But with the following powershell snippet,I can see that Hyper-V is disabled.

```<code>$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online
# Check if Hyper-V is enabled
if($hyperv.State -eq "Enabled") {
    Write-Host "Hyper-V is enabled."
} else {
   Write-Host "Hyper-V is disabled."
</code>```

I think it has to be enabled , how to enable it ?

答: As long as Get-WindowsFeature shows that Hyper-V is installed, it is enabled. There is no need to enable it.</p>

Title: Hyper-V installed and enabled

Body:
I can see that Hyper-V installed with the following command Get-WindowsFeature and get back a long list where I can see that Hyper-V is crossed under Display name and Installed under Install State.

But with the following powershell snippet,I can see that Hyper-V is disabled.

$hyperv = Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online
# Check if Hyper-V is enabled
if($hyperv.State -eq "Enabled") {
    Write-Host "Hyper-V is enabled."
} else {
   Write-Host "Hyper-V is disabled."

I think it has to be enabled , how to enable it ?


问:
ModuleNotFoundError: No module named 'Levenshtein'
I installed Levenshtein using pip and it's included in pip list packages. But when I run a python script, appears this error:

ModuleNotFoundError: No module named 'Levenshtein'

This is the pip list:

```<code>Cython (0.29.15)
docopt (0.6.2)
dyNET (2.1)
mosestokenizer (1.1.0)
numpy (1.16.6)
openfile (0.0.7)
pip (9.0.1)
python-Levenshtein (0.12.0)
setuptools (28.8.0)
toolwrapper (1.0.0)
uctools (1.0.2)
wheel (0.29.0)
</code>```

The gcc is linked to the environment variables.

Any suggestions? Thanks in advance.

答:
Try executing the following

```<code>$ pip show python-Levenshtein | grep Location
$ python -c "import sys; print(sys.path)"
</code>```

If the package location is not in the sys.path then that would cause the error.

Body:
I installed Levenshtein using pip and it's included in pip list packages. But when I run a python script, appears this error:

ModuleNotFoundError: No module named 'Levenshtein'

This is the pip list:

Cython (0.29.15)
docopt (0.6.2)
dyNET (2.1)
mosestokenizer (1.1.0)
numpy (1.16.6)
openfile (0.0.7)
pip (9.0.1)
python-Levenshtein (0.12.0)
setuptools (28.8.0)
toolwrapper (1.0.0)
uctools (1.0.2)
wheel (0.29.0)

The gcc is linked to the environment variables.

Any suggestions? Thanks in advance.

Body:
Try executing the following

$ pip show python-Levenshtein | grep Location
$ python -c "import sys; print(sys.path)"

If the package location is not in the sys.path then that would cause the error.


问:
Error: 'Cannot create unknown type '{clr-namespace:NameSpace.Properties}Settings'.'
I define my settings and styles in a ResourceDictionary:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:properties="clr-namespace:Kavand.UI.Properties">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary>
            <properties:Settings x:Key="settings" />
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
    <Style x:Key="PopupMenu_StackPanel">
        <Setter Property="TextBlock.FontSize" Value="{Binding Source={StaticResource settings}, Path=Default.Font_Menu_Size}" />
        <Setter Property="TextBlock.FontFamily" Value="{Binding Source={StaticResource settings}, Path=Default.Font_Menu_Family}" />
        <Setter Property="TextBlock.FontWeight" Value="{Binding Source={StaticResource settings}, Path=Default.Font_Menu_Weight}" />
        <Style.Resources>
            <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource KavandMenuItem}">
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="true">
                        <Setter Property="IsEnabled" Value="false" />
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsChecked" Value="True" />
                            <Condition Property="IsHighlighted" Value="True" />
                        </MultiTrigger.Conditions>
                        <Setter Property="Foreground" Value="{DynamicResource K_Brush_Gray}" />
                    </MultiTrigger>
                </Style.Triggers>
            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>
</code>```

When I run my application, I get the error:

'Cannot create unknown type
  '{clr-namespace:Kavand.UI.Properties}Settings'.'
  Line number '6' and line position
  '14'.

答:
As a variation on other answers & comments, this worked for me:

Set the file's "Build Action" property to "Page".

Build (problem gone - but...)

Set the file's "Build Action" property to "Resource".

Build

Problem still gone!

Seems like a VS bug to me.

Body:
I define my settings and styles in a ResourceDictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:properties="clr-namespace:Kavand.UI.Properties">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary>
            <properties:Settings x:Key="settings" />
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>

            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>

When I run my application, I get the error:

'Cannot create unknown type
  '{clr-namespace:Kavand.UI.Properties}Settings'.'
  Line number '6' and line position
  '14'.


问:
How to determine if glTF has animation data
I've had a few errors progressing from displaying a static mesh,(works fine) to an animated one (mixed results). I suspect the fbx that I've been exporting to glTF is as fault, but I'd just like to ask:

Firstly, how do you determine if a glTF file has animation data/clips? And, if the model displaying doesn't have any animation will that cause any problems using calling the AnimationMixer?

This is what I have:

```<code>    // Mix and animate!
    mixer = new THREE.AnimationMixer( model );
    var clips = model.animations;

    // if there's no first animation; there's no animation
    if (mixer.clipAction( gltf.animations[ 0 ] ) == undefined)
    // if (clips == undefined) // doesn't seem to work
    {
        // console.log("-> clips " + clips);
        console.log("-> no anim for " + model.name);
    }
    else
    {
        mixer.clipAction( gltf.animations[ 0 ] ).play();
    }
</code>```

only occasionally on a static mesh I get the error TypeError: Cannot read property 'uuid' of undefined Which leaves be a little confused.

答: The gltfloader calls the completion function with a structure.. in that struct is an .animations[] array. If that is empty, no animations were found. As long as you make your mixer and don't try to add an undefined animation, it should be fine by itself and you can add the animation later when you find one.</p>

Body:
I've had a few errors progressing from displaying a static mesh,(works fine) to an animated one (mixed results). I suspect the fbx that I've been exporting to glTF is as fault, but I'd just like to ask:

Firstly, how do you determine if a glTF file has animation data/clips? And, if the model displaying doesn't have any animation will that cause any problems using calling the AnimationMixer?

This is what I have:

    // Mix and animate!
    mixer = new THREE.AnimationMixer( model );
    var clips = model.animations;

    // if there's no first animation; there's no animation
    if (mixer.clipAction( gltf.animations[ 0 ] ) == undefined)
    // if (clips == undefined) // doesn't seem to work
    {
        // console.log("-> clips " + clips);
        console.log("-> no anim for " + model.name);
    }
    else
    {
        mixer.clipAction( gltf.animations[ 0 ] ).play();
    }

only occasionally on a static mesh I get the error TypeError: Cannot read property 'uuid' of undefined Which leaves be a little confused.


问:
best way for running code in async with kotlin
hi i want use jsoup to load a large table from html, what is the best way for doing this in async way?
AsyncTask? coroutines? doasync library? which one? i need show progressbar while fetching data so please tell me what is the best way?

UPDATE:
i want run this code in async

```<code>doc: Document = Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
// some code for parsing...
</code>```

答: I'll advice you try out Kotlin Coroutines. This would enable you dispatch expensive or long-running operations i.e. querying databases, making network requests/calls off to other threads thereby not blocking the Main Thread. Coroutines help you avoid the hassle of callbacks. Also, Google deprecated the AsyncTask API (in Android 11) and recommends using Java’s Concurrency framework or Kotlin Coroutines as the way to go for multi-threading purposes.</p>

Body:
hi i want use jsoup to load a large table from html, what is the best way for doing this in async way?
AsyncTask? coroutines? doasync library? which one? i need show progressbar while fetching data so please tell me what is the best way?

UPDATE:
i want run this code in async

doc: Document = Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
// some code for parsing...


问:
How to use Type converters for complex data type in ROOM library?
I'm new to ROOM library. I've some complex json data structure which i would like to store in ROOM database, i don't know how to use Type convertes for multiple list of objectes. Following are my Entities, </p>

```<code> // Trying to put all my custom models in a single table
@Entity(tableName = "myTable")
data class RaceModelDatabase(
    @PrimaryKey
    val ID: String,
    @Embedded val info: CustomModel,
    @Embedded(prefix = "parti")
    val parti: Map<String,UserModelDatabase> ,
    @Embedded val totalTime: Map<String,TimeDataModel>
)
</code>```

<p>// Custom Models which also has Map objects
    data class CustomModel (val name :String, val crdate : String )</p>

```<code>data class UserModelDatabase(@Embedded val info : CustomModel,
@Embedded(prefix = "Result_")  val result :Map<String,CustomModel>
)
data class TimeDataModel (
val Start : Long,
val End : Long
)
</code>```

答:
Here is an example of how to use TypeAdapter for one of your Map objects. You could follow the same for the rest.</p>

```<code>class RaceTypeConverter {
    @JvmStatic
    @TypeConverter
    fun fromString(value: String): Map<String, TimeDataModel > {
       val mapType = object : TypeToken<Map<String, TimeDataModel >>() {}.type
       return Gson().fromJson(value, mapType)
    }

    @TypeConverter
    @JvmStatic
    fun fromStringMap(map: Map<String, TimeDataModel>): String {
       val gson = Gson()
       return gson.toJson(map)
    }
}
</code>```

Body:
I'm new to ROOM library. I've some complex json data structure which i would like to store in ROOM database, i don't know how to use Type convertes for multiple list of objectes. Following are my Entities,

 // Trying to put all my custom models in a single table
@Entity(tableName = "myTable")
data class RaceModelDatabase(
    @PrimaryKey
    val ID: String,
    @Embedded val info: CustomModel,
    @Embedded(prefix = "parti")
    val parti: Map<String,UserModelDatabase> ,
    @Embedded val totalTime: Map<String,TimeDataModel>
)

// Custom Models which also has Map objects
    data class CustomModel (val name :String, val crdate : String )

data class UserModelDatabase(@Embedded val info : CustomModel,
@Embedded(prefix = "Result_")  val result :Map<String,CustomModel>
)
data class TimeDataModel (
val Start : Long,
val End : Long
)

Body:
Here is an example of how to use TypeAdapter for one of your Map objects. You could follow the same for the rest.

class RaceTypeConverter {
    @JvmStatic
    @TypeConverter
    fun fromString(value: String): Map<String, TimeDataModel > {
       val mapType = object : TypeToken<Map<String, TimeDataModel >>() {}.type
       return Gson().fromJson(value, mapType)
    }

    @TypeConverter
    @JvmStatic
    fun fromStringMap(map: Map<String, TimeDataModel>): String {
       val gson = Gson()
       return gson.toJson(map)
    }
}


问:
function is overriding variable declared in other scope
I have to functions both using i as an iterator.
One function is using the other.
I thought local Variables cant be changed by other scopes.
But now "i" is changed after the "createOptions" function.
Is it possible that the value is passed by the object?</p>

```<code>    function createOptions(array) {
       var optionArray = [];
       for (i=0;i<array.length;i++) {
         var option = $("<option></option").text(array[i]);
         $(option).attr("value", array[i]);
         optionArray.push(option);
       }
       return optionArray;
     }

     function buildForm(players) {
       var form = $("<form></form>");
       for (i=0; i<4; i++) {
         var playernumber = "player " + (i+1).toString();
         var select = $("<select></select>").attr({
          "id" : playernumber,
          "onchange" : "addNewPlayer(this)"
         });
         var selectPlayerOption = $("<option></option>").text("-- select Player --");
         $(selectPlayerOption).attr({
           "disabled" : true,
           "selected" : true
         })
         var newPlayerOption = $("<option></option>").text("New Player");
         var playerOptions = createOptions(players);
         console.log(playerOptions.j);
         $(select).append(selectPlayerOption, newPlayerOption, playerOptions);
         $(form).append(select);
       }
       $("#maincontent").append(form);
     }
</code>```

答:
If you create the variable like i = 0 even if it is inside a for loop still will be created as global variable.

Suggested way instead:

```<code>for (let i=0; i < array.length; i++) {
   // your code
}
</code>```

Read further here about let.

I hope that helps!

Body:
I have to functions both using i as an iterator.
One function is using the other.
I thought local Variables cant be changed by other scopes.
But now "i" is changed after the "createOptions" function.
Is it possible that the value is passed by the object?

    function createOptions(array) {
       var optionArray = [];
       for (i=0;i<array.length;i++) {
         var option = $("<option></option").text(array[i]);
         $(option).attr("value", array[i]);
         optionArray.push(option);
       }
       return optionArray;
     }

     function buildForm(players) {
       var form = $("<form></form>");
       for (i=0; i<4; i++) {
         var playernumber = "player " + (i+1).toString();
         var select = $("<select></select>").attr({
          "id" : playernumber,
          "onchange" : "addNewPlayer(this)"
         });
         var selectPlayerOption = $("<option></option>").text("-- select Player --");
         $(selectPlayerOption).attr({
           "disabled" : true,
           "selected" : true
         })
         var newPlayerOption = $("<option></option>").text("New Player");
         var playerOptions = createOptions(players);
         console.log(playerOptions.j);
         $(select).append(selectPlayerOption, newPlayerOption, playerOptions);
         $(form).append(select);
       }
       $("#maincontent").append(form);
     }

Body:
If you create the variable like i = 0 even if it is inside a for loop still will be created as global variable.

Suggested way instead:

for (let i=0; i < array.length; i++) {
   // your code
}

Read further here about let.

I hope that helps!


问:
RSpec response.body is still empty even with config.render_views
In my spec_helper.rb file I have specifically set it to config.render_views but the response.body I get back is still empty. Here is my basic spec

```<code>describe  "#index" do
    it "should list all rooms" do
      get 'index'
      stub(Person).all
    end

    it "responds with 200 response code" do
      response.should be_ok
    end

    it "renders the index template" do
      pp response.body
      response.should render_template("people/index")
    end

  end
</code>```

Is there anything else that could have shorted this behavior? It's fine when I go through the browser. I am on Rspec 2.5.0

答:
This was changed from RSpec 1 to RSpec 2. View specs now use rendered instead of response:

rendered.should =~ /some text/

More info in the release notes on github.

Body:
In my spec_helper.rb file I have specifically set it to config.render_views but the response.body I get back is still empty. Here is my basic spec

describe  "#index" do
    it "should list all rooms" do
      get 'index'
      stub(Person).all
    end

    it "responds with 200 response code" do
      response.should be_ok
    end

    it "renders the index template" do
      pp response.body
      response.should render_template("people/index")
    end

  end

Is there anything else that could have shorted this behavior? It's fine when I go through the browser. I am on Rspec 2.5.0


问:
Lambda can't find the file when code version inserted into Handler property in CloudFormation template
The artefact that I create and deploy has a version number in it. It is of the form:

```<code>universe-0.0.1-SNAPSHOT.zip
</code>```

where the 0.0.1-SNAPSHOT is the version.

Now the CloudFormation template has the Handler mapped through a Fn::Join function:

```<code>  UFunctionCelestial:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtefactRepositoryBucket
        S3Key: !Join [ '', [!Sub '${AWS::StackName}-', !Ref CodeVersion, '.zip' ] ]
      Handler: !Join [ '', [!Sub '${AWS::StackName}-', !Ref CodeVersion, '/src/lambdas/celestial_persist_function.handler'] ]
      Role: !GetAtt [ UIAMRoleFunctionServiceRoleCelestial, Arn ]
      Runtime: python3.7
      Environment:
        Variables:
          CELESTIAL_TABLE_NAME: !Ref UTableCelestial
          PRIMARY_KEY: id
    DependsOn:
      - UIAMRoleFunctionServiceRolePolicyCelestial
      - UIAMRoleFunctionServiceRoleCelestial

...SNIP...

Parameters:
  ArtefactRepositoryBucket:
    Type: String
    Description: S3 bucket for asset "foundry-cdk/CelestialHandler/Code"
  CodeVersion:
    Type: String
    Description: S3 key for asset version "foundry-cdk/CelestialHandler/Code"
</code>```

I guess most of this is irrelevant, except the Handler property

Now the !Ref CodeVersion code version for that line seems to evaluate as 0/0/1-SNAPSHOT for some reason, even though I call this template with the command:

aws2 cloudformation deploy \
    --template-file ${CF_TEMPLATE_FILE} \
    --region ${ACCOUNT_REGION} \
    --stack-name ${PROJECT_NAME} \
    --force-upload \
    --capabilities CAPABILITY_IAM \
    --parameter-overrides \
        ArtefactRepositoryBucket=${S3_AWS_RELEASES_BUCKET} \
        CodeVersion=${APPLICATION_VERSION}
```

I echoed out the ${APPLICATION_VERSION} and, yep, it evaluates to 0.0.1-SNAPSHOT

and yet when I go to the console and look at my Lambda I get the message:

Lambda can't find the file universe-0/0/1-SNAPSHOT/src/lambdas/celestial_persist_function.py. Make sure that your handler upholds the format: file-name.method.

So my question is, why is CloudFormation turning my dots into slashes and giving the Lambda a bum reference?

答:
It's not cloudformation what doing it. The behavior you are seeing is normal behavior.

Generally, When you define the handler as "folder1.folder2.file.handler", it will look for a folder1, then look for folder2 inside that, then look for the file file.py inside. Finally, the file.py is expected to have a function named handler.

I am assuming that your zip file has a top folder called src. In that case, your handler should be defined as src.lambdas.celestial_persist_function.handler since you have already mentioned where your zip file is using the S3Key.

hope this helps.

Body:
The artefact that I create and deploy has a version number in it. It is of the form:

universe-0.0.1-SNAPSHOT.zip

where the 0.0.1-SNAPSHOT is the version.

Now the CloudFormation template has the Handler mapped through a Fn::Join function:

  UFunctionCelestial:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: !Ref ArtefactRepositoryBucket
        S3Key: !Join [ '', [!Sub '${AWS::StackName}-', !Ref CodeVersion, '.zip' ] ]
      Handler: !Join [ '', [!Sub '${AWS::StackName}-', !Ref CodeVersion, '/src/lambdas/celestial_persist_function.handler'] ]
      Role: !GetAtt [ UIAMRoleFunctionServiceRoleCelestial, Arn ]
      Runtime: python3.7
      Environment:
        Variables:
          CELESTIAL_TABLE_NAME: !Ref UTableCelestial
          PRIMARY_KEY: id
    DependsOn:
      - UIAMRoleFunctionServiceRolePolicyCelestial
      - UIAMRoleFunctionServiceRoleCelestial

...SNIP...

Parameters:
  ArtefactRepositoryBucket:
    Type: String
    Description: S3 bucket for asset "foundry-cdk/CelestialHandler/Code"
  CodeVersion:
    Type: String
    Description: S3 key for asset version "foundry-cdk/CelestialHandler/Code"

I guess most of this is irrelevant, except the Handler property

Now the !Ref CodeVersion code version for that line seems to evaluate as 0/0/1-SNAPSHOT for some reason, even though I call this template with the command:

aws2 cloudformation deploy \
    --template-file ${CF_TEMPLATE_FILE} \
    --region ${ACCOUNT_REGION} \
    --stack-name ${PROJECT_NAME} \
    --force-upload \
    --capabilities CAPABILITY_IAM \
    --parameter-overrides \
        ArtefactRepositoryBucket=${S3_AWS_RELEASES_BUCKET} \
        CodeVersion=${APPLICATION_VERSION}

I echoed out the ${APPLICATION_VERSION} and, yep, it evaluates to 0.0.1-SNAPSHOT

and yet when I go to the console and look at my Lambda I get the message:

Lambda can't find the file universe-0/0/1-SNAPSHOT/src/lambdas/celestial_persist_function.py. Make sure that your handler upholds the format: file-name.method.

So my question is, why is CloudFormation turning my dots into slashes and giving the Lambda a bum reference?


问:
Git: Fix repo with a branch and its remote on different branches
I have no idea how this happened, but I have a git repo in the following kind of state:

```<code>A--B--C--D  master
    \
     E--F   origin/master
</code>```

The commits E and F are at this point obsolete; the changes they make on B have no relevance and they can be deleted if necessary.

I only keep the origin remote as a backup for my code, and nobody else has cloned it, so I can use whatever brute force I need.

What would be the cleanest way to clear this up?

答:
I only keep the origin remote as a backup for my code, and nobody else has cloned it, so I can use whatever brute force I need.

In that case, git push --force origin master will suffice.  Be very sure you're OK with origin/master in your repository, and master in the (separate) Git repository over on origin, being no-longer-able to find commit F.

(Your own repository will remember both commits E and F for some time, under the reflog name origin/master@{number}, so as long as you keep your own repository intact, you can still get them back if they turn out not to be obsolete after all.  However, at some point they will really be removed.  The server may not have reflogs at all and its copy of commits E and F may go away relatively quickly—in seconds, or hours, or just a few days, for instance.)

How and why this works

Every Git repository has its own branch names, which are semi-private to that particular Git repository.  There is a repository over on the machine you're calling origin and it has a branch name master.

Your remote-tracking names,1 such as origin/master, are your Git's method of remembering what some other Git has as its branch names.  In this case your origin/master is your Git's memory of origin's master.

When you have your Git call up their Git, via git fetch or git push, the two Gits have a startup conversation.  It's slightly different for fetch and push, but you can observe what git fetch will itself observer using git ls-remote.  Just run git ls-remote origin (or leave origin out as the default is usually origin anyway): your Git will spill out the other Git's branch, tag, and other names that it listed.  That's the first part of a git fetch: your Git phones up their Git and gets this listing.

When you use git fetch, your Git uses this listing to ask their Git for any commits and other internal Git objects that they have, that you don't, that your Git would like to have.  For instance, if you didn't have commit F yet, and your origin/master remembered commit B or E instead, and they have commit F as their master, your Git will say: I'd like to have commit F please and they'd add that to a list of commits to send.  They'd then offer commit E—a Git must offer the parents of each commit—and your Git would either say no thanks, I have that already or yes please (in which case they would offer B, E's parent, and so on).

Their fetch process then bundles up whatever is needed to get those commits to your Git—this is where you'll see counting objects and compressing objects—and sends that over.  Your Git expands those so that you have a proper set of commits and their data, and then creates or updates your origin/master based on the hash ID stored in their master: now that you definitely have commit F, your Git can make your origin/master point to it.

Hence, if you run:

```<code>git fetch origin
</code>```

at any time—this is the "get me everything" form of the command—your Git will call up their Git and get the preliminary "everything" listing.  The two Gits will figure out from there what your Git needs to get, and give it to your Git.  Your Git will then create or update all your remote-tracking names based on all of their branch names.

When you use git push, which is as close as Git gets to the opposite of fetch—the pair are push and fetch rather than push and pull due to a historical mistake2—a similar process occurs, but there are two key differences:

Your Git sends, rather than receives.  (Your Git still chooses what to send, and the "must offer parent if sending commit" still holds, and so on, but with git fetch, their Git sent and your Git received.)

At the end, instead of some Git updating some sort of "remote-tracking name", your Git asks (politely) or commands (forcefully) their Git to set some of its branch names.3

If you ask or command them to set their master, and they obey, your Git now knows that their master is set to the hash ID you provided, so your Git now updates your origin/master remote-tracking name.

When you use a gentle, ask-type git push origin master, your Git sends commits you have that they don't—such as C and D—and then asks them politely: Please, if it's OK, set your master to point to commit D?  They will say No!  If I do that, I'll forget commit F!  This error comes back as the Git jargon words rejected and non-fast-forward, but it just means they said no, as that would lose commit F and hence E as well.

But that's precisely what you want them to do.  So you just need to send them a forceful command: Set your master!  They could still refuse—if you don't have permission, for instance—but of course you do have permission so in this case they will obey, and lose commit F.

There are two force modes for git push: git push --force is the ancient version, and git push --force-with-lease is a more-modern (since Git 1.9 or so) variant.  The difference between these is that --force just says set, but --force-with-lease says: I think your master is _____.  If so, set it to _____ and let me know that you did; if not, tell me I was wrong and don't set your master after all.  The first blank gets filled in with your Git's origin/master value: your Git's memory of their Git's master.  So that gives you the ability to be sure that you're having them throw away exactly what you think they will throw away.

If you're the only user of the other Git, there's no need for the care that --force-with-lease adds: what you think is right, is right, by definition.  But if you're concerned that you might be forgetful (e.g., if you use two different laptops and can't remember which one was up to date), you can use the fancier check-first-then-force --force-with-lease.  It's never wrong to use --force-with-lease, and except for the fact that the old --force is the historical default, --force-with-lease really should be the default.

1Git calls these remote-tracking branch names but I decided some years ago that the word branch in here is useless clutter that creates some extra confusion, so I now just call them remote-tracking names.

2Often, after fetching commits, you'd like to integrate those commits.  That's what git pull does: it runs git fetch to get commits, then runs a second Git command to integrate those commits.  This seemed, early on, like the correct natural granularity, so git pull was the user-facing command that was the opposite of git push.

It turns out, though, that it's often important to separate the fetch operation from the integrate operation, inserting some sort of inspect operation in between, for instance, so as to choose the correct form of integration.  Mercurial got this right and Git got it wrong: in Mercurial, hg pull means what Git means by git fetch and you have to add a separate operation, or an extra flag, to hg pull to make it also do an integration step.

3You can choose what names you ask them to set, so you can make your Git ask or command tag names to be set, or some other kind of name, but in general, the usual case here is "branch name".

Body:
I have no idea how this happened, but I have a git repo in the following kind of state:

A--B--C--D  master
    \
     E--F   origin/master

The commits E and F are at this point obsolete; the changes they make on B have no relevance and they can be deleted if necessary.

I only keep the origin remote as a backup for my code, and nobody else has cloned it, so I can use whatever brute force I need.

What would be the cleanest way to clear this up?

Body:
I only keep the origin remote as a backup for my code, and nobody else has cloned it, so I can use whatever brute force I need.

In that case, git push --force origin master will suffice.  Be very sure you're OK with origin/master in your repository, and master in the (separate) Git repository over on origin, being no-longer-able to find commit F.

(Your own repository will remember both commits E and F for some time, under the reflog name origin/master@{number}, so as long as you keep your own repository intact, you can still get them back if they turn out not to be obsolete after all.  However, at some point they will really be removed.  The server may not have reflogs at all and its copy of commits E and F may go away relatively quickly—in seconds, or hours, or just a few days, for instance.)

How and why this works

Every Git repository has its own branch names, which are semi-private to that particular Git repository.  There is a repository over on the machine you're calling origin and it has a branch name master.

Your remote-tracking names,1 such as origin/master, are your Git's method of remembering what some other Git has as its branch names.  In this case your origin/master is your Git's memory of origin's master.

When you have your Git call up their Git, via git fetch or git push, the two Gits have a startup conversation.  It's slightly different for fetch and push, but you can observe what git fetch will itself observer using git ls-remote.  Just run git ls-remote origin (or leave origin out as the default is usually origin anyway): your Git will spill out the other Git's branch, tag, and other names that it listed.  That's the first part of a git fetch: your Git phones up their Git and gets this listing.

When you use git fetch, your Git uses this listing to ask their Git for any commits and other internal Git objects that they have, that you don't, that your Git would like to have.  For instance, if you didn't have commit F yet, and your origin/master remembered commit B or E instead, and they have commit F as their master, your Git will say: I'd like to have commit F please and they'd add that to a list of commits to send.  They'd then offer commit E—a Git must offer the parents of each commit—and your Git would either say no thanks, I have that already or yes please (in which case they would offer B, E's parent, and so on).

Their fetch process then bundles up whatever is needed to get those commits to your Git—this is where you'll see counting objects and compressing objects—and sends that over.  Your Git expands those so that you have a proper set of commits and their data, and then creates or updates your origin/master based on the hash ID stored in their master: now that you definitely have commit F, your Git can make your origin/master point to it.

Hence, if you run:

git fetch origin

at any time—this is the "get me everything" form of the command—your Git will call up their Git and get the preliminary "everything" listing.  The two Gits will figure out from there what your Git needs to get, and give it to your Git.  Your Git will then create or update all your remote-tracking names based on all of their branch names.

When you use git push, which is as close as Git gets to the opposite of fetch—the pair are push and fetch rather than push and pull due to a historical mistake2—a similar process occurs, but there are two key differences:

Your Git sends, rather than receives.  (Your Git still chooses what to send, and the "must offer parent if sending commit" still holds, and so on, but with git fetch, their Git sent and your Git received.)

At the end, instead of some Git updating some sort of "remote-tracking name", your Git asks (politely) or commands (forcefully) their Git to set some of its branch names.3

If you ask or command them to set their master, and they obey, your Git now knows that their master is set to the hash ID you provided, so your Git now updates your origin/master remote-tracking name.

When you use a gentle, ask-type git push origin master, your Git sends commits you have that they don't—such as C and D—and then asks them politely: Please, if it's OK, set your master to point to commit D?  They will say No!  If I do that, I'll forget commit F!  This error comes back as the Git jargon words rejected and non-fast-forward, but it just means they said no, as that would lose commit F and hence E as well.

But that's precisely what you want them to do.  So you just need to send them a forceful command: Set your master!  They could still refuse—if you don't have permission, for instance—but of course you do have permission so in this case they will obey, and lose commit F.

There are two force modes for git push: git push --force is the ancient version, and git push --force-with-lease is a more-modern (since Git 1.9 or so) variant.  The difference between these is that --force just says set, but --force-with-lease says: I think your master is _____.  If so, set it to _____ and let me know that you did; if not, tell me I was wrong and don't set your master after all.  The first blank gets filled in with your Git's origin/master value: your Git's memory of their Git's master.  So that gives you the ability to be sure that you're having them throw away exactly what you think they will throw away.

If you're the only user of the other Git, there's no need for the care that --force-with-lease adds: what you think is right, is right, by definition.  But if you're concerned that you might be forgetful (e.g., if you use two different laptops and can't remember which one was up to date), you can use the fancier check-first-then-force --force-with-lease.  It's never wrong to use --force-with-lease, and except for the fact that the old --force is the historical default, --force-with-lease really should be the default.

1Git calls these remote-tracking branch names but I decided some years ago that the word branch in here is useless clutter that creates some extra confusion, so I now just call them remote-tracking names.

2Often, after fetching commits, you'd like to integrate those commits.  That's what git pull does: it runs git fetch to get commits, then runs a second Git command to integrate those commits.  This seemed, early on, like the correct natural granularity, so git pull was the user-facing command that was the opposite of git push.

It turns out, though, that it's often important to separate the fetch operation from the integrate operation, inserting some sort of inspect operation in between, for instance, so as to choose the correct form of integration.  Mercurial got this right and Git got it wrong: in Mercurial, hg pull means what Git means by git fetch and you have to add a separate operation, or an extra flag, to hg pull to make it also do an integration step.

3You can choose what names you ask them to set, so you can make your Git ask or command tag names to be set, or some other kind of name, but in general, the usual case here is "branch name".