问:
Fish is not returning to new line after executing bind
I'm binding Ctrl+f to fg so I can Ctrl+z and Ctrl+f back into vim. However after two times doing the combo twice, it ruins the terminal:

```<code>user@pc:~$ vim
Job 1, 'vim' has stopped
user@pc:~$ Send job 1, “vim” to foreground
Job 1, 'vim' has stopped
^F▉
</code>```

Cursor is now not on a line (which begins with user@pc) and executing any command show it as string (^Fas example).

Pressing enter fixes this, but there should be a better solution.

Edit: using bind \cf 'fg; commandline -f repaint' shows the PS1, but it's still in text mode, meaning pressing Ctrl+f, doesn't run fg but outputs ^F.

答:
Solution was to instad of using:

```<code>bind \cf 'fg'
</code>```

use:

```<code>bind \cf 'fg; commandline -f execute'
</code>```

It ocassionaly does an extra enter, but whatever.

Body:
I'm binding Ctrl+f to fg so I can Ctrl+z and Ctrl+f back into vim. However after two times doing the combo twice, it ruins the terminal:

user@pc:~$ vim
Job 1, 'vim' has stopped
user@pc:~$ Send job 1, “vim” to foreground
Job 1, 'vim' has stopped
^F▉

Cursor is now not on a line (which begins with user@pc) and executing any command show it as string (^Fas example).

Pressing enter fixes this, but there should be a better solution.

Edit: using bind \cf 'fg; commandline -f repaint' shows the PS1, but it's still in text mode, meaning pressing Ctrl+f, doesn't run fg but outputs ^F.

Body:
Solution was to instad of using:

bind \cf 'fg'

use:

bind \cf 'fg; commandline -f execute'

It ocassionaly does an extra enter, but whatever.


来源: stackexchange

问:
Navigate to file share created by Terraform in Azure
What specific syntax should we use to navigate to the file share directory created by the Terraform code below when we putty in to a RHEL virtual machine in the same resource group?

Form Of Answer Requested:

This OP is asking for an answer with a few lines of code in a form that looks something like:

```<code>ls -al sharename/example
mkdir sharename/example/newdirectory
cd sharename/example/newdirectory
ls -al
</code>```

Also, we are asking if any additional resources need to be created in order for there to be storage that can be used by a VM that has permissions to use the storage share directory.

Terraform Code That Creates The Storage:

```<code>resource "azurerm_storage_account" "example" {
  name                     = "azureteststorage"
  resource_group_name      = azurerm_resource_group.my-resources.name
  location                 = azurerm_resource_group.my-resources.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "sharename"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}
</code>```

答:
There are multiple ways to configure the usage of File Share from a Azure VM .

Scenario 1 : You can create share and VM at the same time and mount the Share using remote_exec on the VM like below :

```<code>provider "azurerm" {
  features{}
}

data "azurerm_resource_group" "example" {
  name     = "ansumantest"
}

resource "azurerm_virtual_network" "example" {
  name                = "example-network"
  address_space       = ["10.0.0.0/16"]
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
}

resource "azurerm_subnet" "example" {
  name                 = "internal"
  resource_group_name  = data.azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name
  address_prefixes     = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "aks-nfs-public-ip" {
  name                = "aks-nfs-public-ip"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
  allocation_method   = "Static"

}
resource "azurerm_network_security_group" "example" {
  name                = "ansuman-nsg"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name

  security_rule {
    name                       = "test123"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet_network_security_group_association" "example" {
  subnet_id                 = azurerm_subnet.example.id
  network_security_group_id = azurerm_network_security_group.example.id
}

resource "azurerm_network_interface" "example" {
  name                = "example-nic"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.example.id
    public_ip_address_id = azurerm_public_ip.aks-nfs-public-ip.id
    private_ip_address_allocation = "Dynamic"
  }
  depends_on = [
    azurerm_subnet_network_security_group_association.example
  ]
}

resource "azurerm_storage_account" "example" {
  name                     = "ansuazureteststorage1"
  resource_group_name      = data.azurerm_resource_group.example.name
  location                 = data.azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "ansushare"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}
resource "azurerm_ssh_public_key" "example" {
  name                = "ansuman-sshkey"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  public_key          = file("~/.ssh/id_rsa.pub")
}

resource "azurerm_linux_virtual_machine" "example" {
  name                = "example-machine"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  size                = "Standard_D4s_v4"
  admin_username      = "adminuser"
  admin_password      = "Password@1234"
  disable_password_authentication = false
  network_interface_ids = [
    azurerm_network_interface.example.id,
  ]
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }
    admin_ssh_key {
    username   = "adminuser"
    public_key = azurerm_ssh_public_key.example.public_key
  }

  source_image_reference {
    publisher = "RedHat"
    offer     = "RHEL"
    sku       = "82gen2"
    version   = "latest"
  }

    connection {
      type        = "ssh"
      host        = azurerm_public_ip.aks-nfs-public-ip.ip_address
      user        = "adminuser"
      password    = "Password@1234"
    }
    provisioner "remote-exec" {
    inline = [
        "sudo yum install cifs-utils -y",
        "sudo mkdir -p /mnt/${azurerm_storage_account.example.name}/${azurerm_storage_share.example.name}",
        "sudo mount -t cifs //${azurerm_storage_account.example.name}.file.core.windows.net/${azurerm_storage_share.example.name} /mnt/${azurerm_storage_account.example.name}/${azurerm_storage_share.example.name} -o vers=3.0,dir_mode=0777,file_mode=0777,serverino,username=${azurerm_storage_account.example.name},password=${azurerm_storage_account.example.primary_access_key}",
    ]
  }
}
</code>```

Output:

Scenario-2 : If you have an existing VM then you can just create the storage resources and then using custom script extension you can mount them :

terraform code :

```<code>resource "azurerm_storage_account" "example" {
  name                     = "ansuazureteststorage1"
  resource_group_name      = data.azurerm_resource_group.example.name
  location                 = data.azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "ansushare"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}

data "azurerm_virtual_machine" "example" {
  name = "example-machine"
  resource_group_name = "ansumantest"
}

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "MountShare"
 virtual_machine_id    = data.azurerm_virtual_machine.example.id
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  settings = <<SETTINGS
    {
        "script": "${base64encode(templatefile("customdata.sh", {
          Storage_account_name="${azurerm_storage_account.example.name}",
          File_share_name="${azurerm_storage_share.example.name}",
          Storage_account_key = "${azurerm_storage_account.example.primary_access_key}"
        }))}"
    }
SETTINGS
}
</code>```

customdata.sh:

```<code>#!/bin/sh
sudo yum install cifs-utils -y
sudo mkdir -p "/mnt/${Storage_account_name}/${File_share_name}"
sudo mount -t cifs "//${Storage_account_name}.file.core.windows.net/${File_share_name}" "/mnt/${Storage_account_name}/${File_share_name}" -o "vers=3.0,dir_mode=0777,file_mode=0777,serverino,username=${Storage_account_name},password=${Storage_account_key}"
</code>```

Output :

Scenario - 3 : If you want to use putty to ssh and then mount you can just go to>>Portal>>share that you created from terraform >> Connect >> Linux and copy the script provided there and run in the VM after doing putty:

ContentLicense: CC BY-SA 4.0

Body:
What specific syntax should we use to navigate to the file share directory created by the Terraform code below when we putty in to a RHEL virtual machine in the same resource group?

Form Of Answer Requested:

This OP is asking for an answer with a few lines of code in a form that looks something like:

ls -al sharename/example
mkdir sharename/example/newdirectory
cd sharename/example/newdirectory
ls -al

Also, we are asking if any additional resources need to be created in order for there to be storage that can be used by a VM that has permissions to use the storage share directory.

Terraform Code That Creates The Storage:

resource "azurerm_storage_account" "example" {
  name                     = "azureteststorage"
  resource_group_name      = azurerm_resource_group.my-resources.name
  location                 = azurerm_resource_group.my-resources.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "sharename"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}

Body:
There are multiple ways to configure the usage of File Share from a Azure VM .

Scenario 1 : You can create share and VM at the same time and mount the Share using remote_exec on the VM like below :

provider "azurerm" {
  features{}
}

data "azurerm_resource_group" "example" {
  name     = "ansumantest"
}

resource "azurerm_virtual_network" "example" {
  name                = "example-network"
  address_space       = ["10.0.0.0/16"]
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
}

resource "azurerm_subnet" "example" {
  name                 = "internal"
  resource_group_name  = data.azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name
  address_prefixes     = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "aks-nfs-public-ip" {
  name                = "aks-nfs-public-ip"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name
  allocation_method   = "Static"

}
resource "azurerm_network_security_group" "example" {
  name                = "ansuman-nsg"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name

  security_rule {
    name                       = "test123"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet_network_security_group_association" "example" {
  subnet_id                 = azurerm_subnet.example.id
  network_security_group_id = azurerm_network_security_group.example.id
}

resource "azurerm_network_interface" "example" {
  name                = "example-nic"
  location            = data.azurerm_resource_group.example.location
  resource_group_name = data.azurerm_resource_group.example.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.example.id
    public_ip_address_id = azurerm_public_ip.aks-nfs-public-ip.id
    private_ip_address_allocation = "Dynamic"
  }
  depends_on = [
    azurerm_subnet_network_security_group_association.example
  ]
}

resource "azurerm_storage_account" "example" {
  name                     = "ansuazureteststorage1"
  resource_group_name      = data.azurerm_resource_group.example.name
  location                 = data.azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "ansushare"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}
resource "azurerm_ssh_public_key" "example" {
  name                = "ansuman-sshkey"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  public_key          = file("~/.ssh/id_rsa.pub")
}

resource "azurerm_linux_virtual_machine" "example" {
  name                = "example-machine"
  resource_group_name = data.azurerm_resource_group.example.name
  location            = data.azurerm_resource_group.example.location
  size                = "Standard_D4s_v4"
  admin_username      = "adminuser"
  admin_password      = "Password@1234"
  disable_password_authentication = false
  network_interface_ids = [
    azurerm_network_interface.example.id,
  ]
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }
    admin_ssh_key {
    username   = "adminuser"
    public_key = azurerm_ssh_public_key.example.public_key
  }

  source_image_reference {
    publisher = "RedHat"
    offer     = "RHEL"
    sku       = "82gen2"
    version   = "latest"
  }

    connection {
      type        = "ssh"
      host        = azurerm_public_ip.aks-nfs-public-ip.ip_address
      user        = "adminuser"
      password    = "Password@1234"
    }
    provisioner "remote-exec" {
    inline = [
        "sudo yum install cifs-utils -y",
        "sudo mkdir -p /mnt/${azurerm_storage_account.example.name}/${azurerm_storage_share.example.name}",
        "sudo mount -t cifs //${azurerm_storage_account.example.name}.file.core.windows.net/${azurerm_storage_share.example.name} /mnt/${azurerm_storage_account.example.name}/${azurerm_storage_share.example.name} -o vers=3.0,dir_mode=0777,file_mode=0777,serverino,username=${azurerm_storage_account.example.name},password=${azurerm_storage_account.example.primary_access_key}",
    ]
  }
}

Output:

Scenario-2 : If you have an existing VM then you can just create the storage resources and then using custom script extension you can mount them :

terraform code :

resource "azurerm_storage_account" "example" {
  name                     = "ansuazureteststorage1"
  resource_group_name      = data.azurerm_resource_group.example.name
  location                 = data.azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

resource "azurerm_storage_share" "example" {
  name                 = "ansushare"
  storage_account_name = azurerm_storage_account.example.name
  quota                = 50
}

resource "azurerm_storage_share_directory" "example" {
  name                 = "example"
  share_name           = azurerm_storage_share.example.name
  storage_account_name = azurerm_storage_account.example.name
}

data "azurerm_virtual_machine" "example" {
  name = "example-machine"
  resource_group_name = "ansumantest"
}

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "MountShare"
 virtual_machine_id    = data.azurerm_virtual_machine.example.id
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  settings = <<SETTINGS
    {
        "script": "${base64encode(templatefile("customdata.sh", {
          Storage_account_name="${azurerm_storage_account.example.name}",
          File_share_name="${azurerm_storage_share.example.name}",
          Storage_account_key = "${azurerm_storage_account.example.primary_access_key}"
        }))}"
    }
SETTINGS
}

customdata.sh:

#!/bin/sh
sudo yum install cifs-utils -y
sudo mkdir -p "/mnt/${Storage_account_name}/${File_share_name}"
sudo mount -t cifs "//${Storage_account_name}.file.core.windows.net/${File_share_name}" "/mnt/${Storage_account_name}/${File_share_name}" -o "vers=3.0,dir_mode=0777,file_mode=0777,serverino,username=${Storage_account_name},password=${Storage_account_key}"

Output :

Scenario - 3 : If you want to use putty to ssh and then mount you can just go to>>Portal>>share that you created from terraform >> Connect >> Linux and copy the script provided there and run in the VM after doing putty:


问:
Problem calling WCF service internet
I am developing a WCF service that will be called by customer in internet. The service is hosted in IIS7 and accept only http. For clients call us from https we do is have a reverse proxy that forwards the request to the application https to http. The customer give a https url to connect and does so smoothly, adding the reference to the service properly. The problem comes when trying to create a client and add in your endpoint https and execute it, as it reads:

System.ArgumentException: The provided URI scheme 'https' is invalid,

  expected 'http'. Parameter name: via.

I leave part of the service's web.config:

```<code><bindings>
 <wsHttpBinding>
  <binding name="ConfigEP">
   <security mode="Message">
    <message clientCredentialType="Certificate" />
   </security>
  </binding>
 </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
 <baseAddressPrefixFilters>
  <add prefix="http://serverInterno/App/"/>
 </baseAddressPrefixFilters>
</serviceHostingEnvironment>
<services>
 <service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
  <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior" binding="wsHttpBinding" bindingConfiguration="ConfigEP" name="App.AppM_NameEP" bindingNamespace="http://siteName/AppM_Name" contract="App.IAppM_Name" />
 </service>
</services>
<behaviors>
 <endpointBehaviors>
  <behavior name="App.AppM_NameEPBehavior">
   <wsdlExtensions location="https://urlsegura/App/Appm_Name.svc" singleFile="true" />
  </behavior>
 </endpointBehaviors>
 <serviceBehaviors>
  <behavior name="App.AppM_NameBehavior">
   <serviceDebug includeExceptionDetailInFaults="true" />
   <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
   <serviceCredentials>
    <clientCertificate>
     <authentication customCertificateValidatorType="App.Validador, App" certificateValidationMode="Custom" />
    </clientCertificate>
    <serviceCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
   </serviceCredentials>
  </behavior>
 </serviceBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
  <add name="wsdlExtensions" type="WCFExtras.Wsdl.WsdlExtensionsConfig, WCFExtras, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>
</code>```

and here the client's app.config:

```<code><system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="NewBehavior">
    <clientCredentials>
     <clientCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
    </clientCredentials>
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <bindings>
  <wsHttpBinding>
   <binding name="App.AppM_NameEP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
    <security mode="Message">
     <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
     <message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
    </security>
   </binding>
  </wsHttpBinding>
 </bindings>
 <client>
  <endpoint address="https://urlsegura/App/Appm_Name.svc" binding="wsHttpBinding" bindingConfiguration="App.AppM_NameEP" contract="App.IAppM_Name" name="App.AppM_NameEP">
   <identity>
    <certificate encodedValue="XXXX" />
   </identity>
  </endpoint>
 </client>
</system.serviceModel>
</code>```

Thanks in advance.
Best regards.

答:
I think your error is being caused because you're using message based security on your  configuration. Try changing it to Transport instead (in both the client and service configuration files), so that it uses SSL for security rather than encrypting the message.

You can use TransportWithMessageCredential if you absolutely must have the message encrypted also. Hope that helps.

ContentLicense: CC BY-SA 3.0

Title: Problem calling WCF service internet

Body:
I am developing a WCF service that will be called by customer in internet. The service is hosted in IIS7 and accept only http. For clients call us from https we do is have a reverse proxy that forwards the request to the application https to http. The customer give a https url to connect and does so smoothly, adding the reference to the service properly. The problem comes when trying to create a client and add in your endpoint https and execute it, as it reads:

System.ArgumentException: The provided URI scheme 'https' is invalid,

  expected 'http'. Parameter name: via.

I leave part of the service's web.config:

<bindings>
 <wsHttpBinding>
  <binding name="ConfigEP">
   <security mode="Message">
    <message clientCredentialType="Certificate" />
   </security>
  </binding>
 </wsHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
 <baseAddressPrefixFilters>
  <add prefix="http://serverInterno/App/"/>
 </baseAddressPrefixFilters>
</serviceHostingEnvironment>
<services>
 <service behaviorConfiguration="App.AppM_NameBehavior" name="App.AppM_Name">
  <endpoint address="" behaviorConfiguration="App.AppM_NameEPBehavior" binding="wsHttpBinding" bindingConfiguration="ConfigEP" name="App.AppM_NameEP" bindingNamespace="http://siteName/AppM_Name" contract="App.IAppM_Name" />
 </service>
</services>
<behaviors>
 <endpointBehaviors>
  <behavior name="App.AppM_NameEPBehavior">
   <wsdlExtensions location="https://urlsegura/App/Appm_Name.svc" singleFile="true" />
  </behavior>
 </endpointBehaviors>
 <serviceBehaviors>
  <behavior name="App.AppM_NameBehavior">
   <serviceDebug includeExceptionDetailInFaults="true" />
   <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
   <serviceCredentials>
    <clientCertificate>
     <authentication customCertificateValidatorType="App.Validador, App" certificateValidationMode="Custom" />
    </clientCertificate>
    <serviceCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
   </serviceCredentials>
  </behavior>
 </serviceBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
  <add name="wsdlExtensions" type="WCFExtras.Wsdl.WsdlExtensionsConfig, WCFExtras, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>

and here the client's app.config:

<system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="NewBehavior">
    <clientCredentials>
     <clientCertificate findValue="XX XX XX XX XX XX XX XX XX XX" x509FindType="FindBySerialNumber" />
    </clientCredentials>
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <bindings>
  <wsHttpBinding>
   <binding name="App.AppM_NameEP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
    <security mode="Message">
     <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
     <message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
    </security>
   </binding>
  </wsHttpBinding>
 </bindings>
 <client>
  <endpoint address="https://urlsegura/App/Appm_Name.svc" binding="wsHttpBinding" bindingConfiguration="App.AppM_NameEP" contract="App.IAppM_Name" name="App.AppM_NameEP">
   <identity>
    <certificate encodedValue="XXXX" />
   </identity>
  </endpoint>
 </client>
</system.serviceModel>

Thanks in advance.
Best regards.


问:
Azure Logic App - xpath for xml with namespace prefix
In my logic app i am using xpath() function to get the value of . I have tried different xpaths but getting error

'The template language function 'xpath' parameters are invalid: the 'xpath' parameter must be a supported, well formed XPath expression. Please see https://aka.ms/logicexpressions#xpath for usage details.'.

i have the following xml:

I have tried:

```<code>@xpath(xml(<YourMessage>), '/*[local-name()=\"Envelope\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]/*[local-name()=\"Body\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]')
@xpath(xml(<YourMessage>), 'string(/*[local-name()=\"Envelope\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]/*[local-name()=\"Body\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"])')
</code>```

but getting the same error

答:
Coming to this late, but the error is because you've escaped the double-quotes in the designer (which automagically escapes double-quotes for you).

This is from the Reference guide to expression functions for Azure Logic Apps and Power Automate:

Important

If you work in code view, escape the double quotation mark (") by using the backslash character (\). For example, you need to use escape characters when you serialize an expression as a JSON string. However, if you're work in the Logic App Designer or expression editor, you don't need to escape the double quotation mark because the backslash character is added automatically to the underlying definition, for example:

Code view: xpath(xml(body('Http')), '/*[name()=\"file\"]/*[name()=\"location\"]')

Expression editor: xpath(xml(body('Http')), '/*[name()="file"]/*[name()="location"]')

Body:
In my logic app i am using xpath() function to get the value of . I have tried different xpaths but getting error

'The template language function 'xpath' parameters are invalid: the 'xpath' parameter must be a supported, well formed XPath expression. Please see https://aka.ms/logicexpressions#xpath for usage details.'.

i have the following xml:

I have tried:

@xpath(xml(<YourMessage>), '/*[local-name()=\"Envelope\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]/*[local-name()=\"Body\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]')
@xpath(xml(<YourMessage>), 'string(/*[local-name()=\"Envelope\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"]/*[local-name()=\"Body\" and namespace-uri()=\"http://schemas.xmlsoap.org/soap/envelope/\"])')

but getting the same error


问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答:
Delete the folder under %appdata%\Docker as indicated in Github issues

For quick access press Ctrl+R, paste "%appdata%\Docker" then Enter, it should open a folder located in AppData\Roaming\Docker (e.g. C:\Users\YourUsername\AppData\Roaming\Docker)

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at


问:
How to find model records having some or no associated model records in rails?
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

```<code>Employee.includes(:documents).where(documents: {id: nil})
</code>```

and Employees with some or all documents submitted by:

```<code>Employee.includes(:documents).where.not(documents: {id: nil})
</code>```

I want the list so that I can iterate through their missing documents by:

```<code>Document.where.not(id: employee.documents.pluck(:id))
</code>```

and send the list.
Currently, my mailer looks like this:

```<code>class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end
</code>```

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

```<code><% if employee.documents.length < Document.all.count %>
</code>```

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

答:
The questions is pretty confusing but if you have a list of documents and want to find employees with matches with all or some of the records you can do it by grouping and using having to set conditions on the group:

Employee
  .left_joins(:documents)
  .where(documents: { id: documents })
  .group(:id)
  # HAVING COUNT("documents"."id") < 7
  .having(Document.arel_table[:id].count.lt(documents.size))
```
<p>This would give users that don't have matches with all the documents but may have some. The conditions can be simply changed by using <code>eq</code>, <code>lteq</code>, <code>gt</code> or <code>gteq</code> instead of <code>lt</code> (less than).</p>
<p>On Postgres you can use <code>COUNT(documents.*)</code> instead with:</p>
```.having(Document.arel_table[Arel.star].count.lt(documents.size))
```

Body:
I am creating an Employee Management System app using Rails 7. Here I have one Employee model, one Document model having a list of all documents and these two are associated through the EmployeeDocuments model which has Employee ID and Document ID. Now I want to use an action mailer to send a list of employees with documents they have not submitted. The problem is I cannot get the Employee list with some or no documents submitted in a single query.
I can get Employees with no submitted documents like this:

Employee.includes(:documents).where(documents: {id: nil})

and Employees with some or all documents submitted by:

Employee.includes(:documents).where.not(documents: {id: nil})

I want the list so that I can iterate through their missing documents by:

Document.where.not(id: employee.documents.pluck(:id))

and send the list.
Currently, my mailer looks like this:

class DocsNotifierMailer < ApplicationMailer
  default from: 'user@email.com'

  def notification_email
    @employees = Employee.all
    mail(to: 'recipient@email.com',
      subject: 'Reminder for missing documents')
  end
end

So I can get the list of all employees in my HTML template and there I am using an If statement like this:

<% if employee.documents.length < Document.all.count %>

to filter out the employees with all documents.
But I want to filter them in the mailer itself.
Since I am a beginner, can not find a way out of this. Please help.

Body:
The questions is pretty confusing but if you have a list of documents and want to find employees with matches with all or some of the records you can do it by grouping and using having to set conditions on the group:

Employee
  .left_joins(:documents)
  .where(documents: { id: documents })
  .group(:id)
  # HAVING COUNT("documents"."id") < 7
  .having(Document.arel_table[:id].count.lt(documents.size))

This would give users that don't have matches with all the documents but may have some. The conditions can be simply changed by using eq, lteq, gt or gteq instead of lt (less than).

On Postgres you can use COUNT(documents.*) instead with:

.having(Document.arel_table[Arel.star].count.lt(documents.size))


问:
Is this a CompletableFuture chaining anti-pattern?
Lately I have been applying a pattern where I chain futures together where for some future I don't care about the result but I do care it completed without exception before continuing the futures chain.

What I do is using thenCompose() and then supply it with a CompletableFuture that always ends with .thenApply(a). Example:

futureR
   .thenCompose(r -> sequentialFutureTask1(r).thenApply(ignored -> r))
   .thenCompose(r -> sequentialFutureTask2(r).thenApply(ignored -> r))
   .thenCompose(r -> sequentialFutureTask3(r).thenApply(ignored -> r))
```
<p>I've even streamlined this with a helper method:</p>
<pre class="lang-java prettyprint-override"><code>futureFoo
   .thenCompose(identityComposing(r -> sequentialFutureTask1(r)))
   .thenCompose(identityComposing(r -> sequentialFutureTask2(r)))
   .thenCompose(identityComposing(r -> sequentialFutureTask3(r)))

public static <T> Function<T, CompletableFuture<T>> identityComposing(Function<T, CompletableFuture<?>> c) {
    return r -> cf.apply(r).thenApply(ignored -> r);
}
</code>```

Is this an anti-pattern? It looks concise enough to me, but somehow I feel I missed some point.

答:
Outside of the invisible side-effects pointed out by Antoniossss in the comments, which drives this a bit away from functional programming, the other issue is that you are still repeating yourself with all these identityComposing() wrapping calls.

As you said, the requirement is that those methods are called in sequence, so semantically you don’t really need the "composition" result. The intent is really to chain the calls themselves.

This would be best represented by composing those calls directly instead:

```<code>futureR.thenAccept(r -> sequentialFutureTask1(r)
           .thenCompose(ignored -> sequentialFutureTask2(r))
           .thenCompose(ignored -> sequentialFutureTask3(r)));
</code>```

Of course, there is still a lot of repetition here with the thenCompose(ignored -> …(r)). If this is a frequent pattern you have, you could wrap this in the following method:

```<code>@SafeVarargs
public final <R> void executeInSequence(R r,
        Function<? super R, ? extends CompletionStage<?>> firstTask,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    CompletionStage<?> prev = firstTask.apply(r);
    for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
        prev = prev.thenCompose(ignored -> task.apply(r));
    }
}
</code>```

(I also wanted to do this with Stream but I didn’t find a nice, clean solution)

which you would use as:

```<code>futureR.thenAccept(r -> executeInSequence(r,
        this::sequentialFutureTask1,
        this::sequentialFutureTask2,
        this::sequentialFutureTask3));
</code>```

or if you prefer to pass futureR as parameter:

```<code>@SafeVarargs
public final <R> void executeAfter(CompletionStage<R> futureR,
        Function<? super R, ? extends CompletionStage<?>> firstTask,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    futureR.thenAccept(r -> {
        CompletionStage<?> prev = firstTask.apply(r);
        for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
            prev = prev.thenCompose(ignored -> task.apply(r));
        }
    });
}
</code>```

used as:

```<code>executeAfter(futureR,
        this::sequentialFutureTask1,
        this::sequentialFutureTask2,
        this::sequentialFutureTask3);
</code>```

Alternatively, this executeAfter() can be implemented with one less parameter:

```<code>@SafeVarargs
public final <R> void executeAfter2(CompletionStage<R> futureR,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    futureR.thenAccept(r -> {
        CompletionStage<?> prev = futureR;
        for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
            prev = prev.thenCompose(ignored -> task.apply(r));
        }
    });
}
</code>```

but this prev = futureR causes an additional, useless thenCompose() that might be confusing (performance impact should be negligible since futureR is already completed when this will be invoked).

Body:
Lately I have been applying a pattern where I chain futures together where for some future I don't care about the result but I do care it completed without exception before continuing the futures chain.

What I do is using thenCompose() and then supply it with a CompletableFuture that always ends with .thenApply(a). Example:

futureR
   .thenCompose(r -> sequentialFutureTask1(r).thenApply(ignored -> r))
   .thenCompose(r -> sequentialFutureTask2(r).thenApply(ignored -> r))
   .thenCompose(r -> sequentialFutureTask3(r).thenApply(ignored -> r))

I've even streamlined this with a helper method:

futureFoo
   .thenCompose(identityComposing(r -> sequentialFutureTask1(r)))
   .thenCompose(identityComposing(r -> sequentialFutureTask2(r)))
   .thenCompose(identityComposing(r -> sequentialFutureTask3(r)))

public static <T> Function<T, CompletableFuture<T>> identityComposing(Function<T, CompletableFuture<?>> c) {
    return r -> cf.apply(r).thenApply(ignored -> r);
}

Is this an anti-pattern? It looks concise enough to me, but somehow I feel I missed some point.

Body:
Outside of the invisible side-effects pointed out by Antoniossss in the comments, which drives this a bit away from functional programming, the other issue is that you are still repeating yourself with all these identityComposing() wrapping calls.

As you said, the requirement is that those methods are called in sequence, so semantically you don’t really need the "composition" result. The intent is really to chain the calls themselves.

This would be best represented by composing those calls directly instead:

futureR.thenAccept(r -> sequentialFutureTask1(r)
           .thenCompose(ignored -> sequentialFutureTask2(r))
           .thenCompose(ignored -> sequentialFutureTask3(r)));

Of course, there is still a lot of repetition here with the thenCompose(ignored -> …(r)). If this is a frequent pattern you have, you could wrap this in the following method:

@SafeVarargs
public final <R> void executeInSequence(R r,
        Function<? super R, ? extends CompletionStage<?>> firstTask,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    CompletionStage<?> prev = firstTask.apply(r);
    for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
        prev = prev.thenCompose(ignored -> task.apply(r));
    }
}

(I also wanted to do this with Stream but I didn’t find a nice, clean solution)

which you would use as:

futureR.thenAccept(r -> executeInSequence(r,
        this::sequentialFutureTask1,
        this::sequentialFutureTask2,
        this::sequentialFutureTask3));

or if you prefer to pass futureR as parameter:

@SafeVarargs
public final <R> void executeAfter(CompletionStage<R> futureR,
        Function<? super R, ? extends CompletionStage<?>> firstTask,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    futureR.thenAccept(r -> {
        CompletionStage<?> prev = firstTask.apply(r);
        for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
            prev = prev.thenCompose(ignored -> task.apply(r));
        }
    });
}

used as:

executeAfter(futureR,
        this::sequentialFutureTask1,
        this::sequentialFutureTask2,
        this::sequentialFutureTask3);

Alternatively, this executeAfter() can be implemented with one less parameter:

@SafeVarargs
public final <R> void executeAfter2(CompletionStage<R> futureR,
        Function<? super R, ? extends CompletionStage<?>>... otherTasks) {
    futureR.thenAccept(r -> {
        CompletionStage<?> prev = futureR;
        for (Function<? super R, ? extends CompletionStage<?>> task : otherTasks) {
            prev = prev.thenCompose(ignored -> task.apply(r));
        }
    });
}

but this prev = futureR causes an additional, useless thenCompose() that might be confusing (performance impact should be negligible since futureR is already completed when this will be invoked).


问:
ModuleNotFoundError: No module named aws_cdk
When I run cdk deploy, I get the following error:

```<code>Traceback (most recent call last):
  File "app.py", line 3, in <module>
    from aws_cdk import core
ModuleNotFoundError: No module named 'aws_cdk'
</code>```

I installed cdk with npm

```<code>npm install -g aws-cdk
</code>```

I activated the virtual env by

```<code>source .env/bin/activate
</code>```

I'm using python3.8. I installed aws_cdk dependencies by

```<code>pip install -r requirements.txt
</code>```

When editing the python files, I am able to import aws_cdk and run individual functions successfully. I think the problem is that cdk is located in the /usr directory:

```<code>> which cdk
/usr/local/bin/cdk
</code>```

And I think it's using python from my /usr/bin instead of virtual env. How do I make cdk use python in my virtual environment?

EDIT:

requirements.txt

```<code>-e .
</code>```

答:
install via cmd as below.

```<code>pip install aws-cdk.core
</code>```

or

add following line in requirements.txt file

```<code>aws-cdk.core
</code>```

it should resolved

Body:
When I run cdk deploy, I get the following error:

Traceback (most recent call last):
  File "app.py", line 3, in <module>
    from aws_cdk import core
ModuleNotFoundError: No module named 'aws_cdk'

I installed cdk with npm

npm install -g aws-cdk

I activated the virtual env by

source .env/bin/activate

I'm using python3.8. I installed aws_cdk dependencies by

pip install -r requirements.txt

When editing the python files, I am able to import aws_cdk and run individual functions successfully. I think the problem is that cdk is located in the /usr directory:

> which cdk
/usr/local/bin/cdk

And I think it's using python from my /usr/bin instead of virtual env. How do I make cdk use python in my virtual environment?

EDIT:

requirements.txt

-e .

Body:
install via cmd as below.

pip install aws-cdk.core

or

add following line in requirements.txt file

aws-cdk.core

it should resolved


问:
Best way to transfer struct from one process to another?
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

```<code>typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;
</code>```

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

答: It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit.</p>

Body:
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.


问:
How do getters and setters work in Python?
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

```<code>class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)
</code>```

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

答:
what I understand is that they are used so that no one could change the object's attributes directly.

Your understanding is wrong. There is no magic rule that tells the python interpreter oh, this class has a setter, so direct access to the fields aren't allowed any more.

In other words: this is merely "works by convention". When you see a python class that has setter methods, then you know you should not access the fields directly, although you still can do that.

And note: python is mostly rather lenient on such things. A lot of things are "by convention" only. It is just "the nature" of python: you can do a lot of things that other languages, especially statically typed ones like Java do not allow.

Body:
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.


问:
is it possible to build a azure function which uses graph api call and can handle reliable authentification on massive load?
According to this post

How to use a token authentification from Graph API in Azure http trigger function as webhook

the azure function crashes on many triggers at same time and so if in the code the token (Graph API) is executed the token will be requested so many time there was thrown this exception.

2022-01-31T06:51:59Z   [Information]   AADSTS900023: Specified tenant identifier 'a1ae89fb-21b9-40bf-9d82-a10ae85a2407a1ae89fb-21b9-40bf-9d82-a10ae85a2407' is neither a valid DNS name, nor a valid external domain.

Trace ID: ebbb51ed-2ef1-4931-81b6-702833c93f00

Correlation ID: cb112afc-08bf-44bb-9a8e-b0a93938f6cb

Timestamp: 2022-01-31 06:51:55Z

at Microsoft.Identity.Client.Internal.Requests.RequestBase.HandleTokenRefreshError(MsalServiceException e, MsalAccessTokenCacheItem cachedAccessTokenItem)

at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)

at Namespace1.Webhook.GetOnlyDesiredDataAfterFiltersAsync(String CallRecordId, AzFuncCallRecordsConfiguration config, ILogger log) in D:\Repos\Webhook.cs:line 518

at Namespace1.Webhook.Run(HttpRequest req, ExecutionContext context, ILogger log) in D:\Repos..\BWebhook.cs:line 180

So the question is now:
Is it realizeable with azure functions because on statefull services it is possible to store the auth token to avoid requiring every time?

I hope this question will not  be seen as a duplicate, but it is 2 different questions.

if no please write the possible failure causes why it is not possible.

答:
after the comment and answer of junas I made this workaround:

Add this 2 static Vars to your class:

```<code>    static string AuthToken = null;
    static DateTime TokenExpDate;
</code>```

Chekc this Vars before Aquiring the token.

```<code>IConfidentialClientApplication app;

AuthenticationResult result = null;
string[] scopes = null;
string data = null;

IRestResponse response = null;

// build Authenticate for getting a token
config.Authority += config.CallRecordTenantID;

app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                          .WithClientSecret(config.ClientSecret)
                                          .WithAuthority(new Uri(config.Authority))
                                          .Build();

scopes = new string[] { "https://graph.microsoft.com/.default" };

// ask static vars if token is vaild
if (AuthToken == null || TokenExpDate < DateTime.UtcNow)
{
    try
    {
        result = await app.AcquireTokenForClient(scopes)
              .ExecuteAsync();

        if (result != null)
        {
            AuthToken = result.AccessToken;
            TokenExpDate = result.ExpiresOn.UtcDateTime;
        }
    }
    catch (Exception ex)
    {
        log.LogInformation("Exc.:" + ex.Message + "\n" + ex.StackTrace);
    }
}
</code>```

Body:
after the comment and answer of junas I made this workaround:

Add this 2 static Vars to your class:

    static string AuthToken = null;
    static DateTime TokenExpDate;

Chekc this Vars before Aquiring the token.

IConfidentialClientApplication app;

AuthenticationResult result = null;
string[] scopes = null;
string data = null;

IRestResponse response = null;

// build Authenticate for getting a token
config.Authority += config.CallRecordTenantID;

app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                          .WithClientSecret(config.ClientSecret)
                                          .WithAuthority(new Uri(config.Authority))
                                          .Build();

scopes = new string[] { "https://graph.microsoft.com/.default" };

// ask static vars if token is vaild
if (AuthToken == null || TokenExpDate < DateTime.UtcNow)
{
    try
    {
        result = await app.AcquireTokenForClient(scopes)
              .ExecuteAsync();

        if (result != null)
        {
            AuthToken = result.AccessToken;
            TokenExpDate = result.ExpiresOn.UtcDateTime;
        }
    }
    catch (Exception ex)
    {
        log.LogInformation("Exc.:" + ex.Message + "\n" + ex.StackTrace);
    }
}


问:
Spark: Find country by geographical coordinates
I have a spark dataframe created in Scala that contains geographical coordinates. I have to add column with country basing on this this geographical coordinates. I found some Python tools but as far as I know I can t use it in Scala code. Also I am not sure about efficiency if I have to process every row one by one by udf (it s about 50000 rows). Do you know how can I process this in the fastest possible way?</p>

答:
You can use Pandas UDF if the tool you found is a python library.
With this, it will parallelize your function and not apply it "row by row".

https://databricks.com/fr/blog/2017/10/30/introducing-vectorized-udfs-for-pyspark.html

https://databricks.com/fr/blog/2020/05/20/new-pandas-udfs-and-python-type-hints-in-the-upcoming-release-of-apache-spark-3-0.html


问:
straight out of react.js.org and it crashes
```<code>export default function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) => (
 <li key={number.toString()}> {number}</li>
));
return <ul>{listItems}</ul>;
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById("root")
);
</code>```

It works ,but when i reload it breaks , it says "Uncaught TypeError: Cannot read properties of undefined (reading 'map')"

答:
```<code>export default function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers?.length ? numbers.map((number) => (
 <li key={number.toString()}> {number}</li>
)) : [];
return <ul>{listItems}</ul>;
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById("root")
);
</code>```

Hi, you can use ternary operator to check if array not undefined and has length. With this way you can prevent undefined error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Body:
export default function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) => (

 {number}

));
return
{listItems}
;
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById("root")
);

It works ,but when i reload it breaks , it says "Uncaught TypeError: Cannot read properties of undefined (reading 'map')"

Body:
export default function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers?.length ? numbers.map((number) => (
 <li key={number.toString()}> {number}</li>
)) : [];
return <ul>{listItems}</ul>;
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById("root")
);

Hi, you can use ternary operator to check if array not undefined and has length. With this way you can prevent undefined error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


问:
Is there any way to remove or rename local URL to hide the address?
I have a html file and use it for my job. when I open this file with browser the URL shows the address of file location in address bar (in this case on my desktop)

file:///C:/Users/Sina/Desktop/File.html

I need some settings that local users cant change any thing to original file. when local users saw the address, they change or delete file.

Is there any way to hide, remove, rename or ... to not show the real address or location of the file? (on this PC or any PC when run)

some settings like just show the name of file

File.html

答: It is impossible unless you are running it on a server. You can use the .htaccess file to define mod_rewrite rules if you are planning to move it to server. Please look into this tutorial video tutorial to do so.


问:
How to pass additional parameter in firebase transaction method in Python
I am trying to create a transaction like this for real time firebase database:

```<code>tranRef = db.reference('all_items')
new_transRef = tranRef.transaction(updateDatabase)
</code>```

My updateDatabase function looks like this:

```<code>def updateDatabase(current_value):
    print(type(current_value))
    return current_value
</code>```

Here the current_value is data containing all the child nodes at root "all_items". This works fine.

What I want is to pass an additional argument to the updateDatabase say cartList which is a list of dictionaries.
How should I do that?
What I essentially want is a function that looks something like this:

```<code>def updateDatabase(current_value, cartList):
    print(type(current_value))
    return current_value
</code>```

How should I pass the list in calling the function:

```<code>tranRef = db.reference('all_items')
new_transRef = tranRef.transaction( ## what should I write here ##)
</code>```

答:
I was also dealing with same problem and I solved it by using lambda:

```<code>extra_param = ['your cart list here']
tranRef = db.reference('all_items')
new_transRef = tranRef.transaction(lambda current_value: updateDatabase(current_value, extra_param))
</code>```

You can then call the transaction method like this:

```<code>def updateDatabase(current_value, cartList):
    print(type(current_value))
    return current_value
</code>```

Body:
I am trying to create a transaction like this for real time firebase database:

tranRef = db.reference('all_items')
new_transRef = tranRef.transaction(updateDatabase)

My updateDatabase function looks like this:

def updateDatabase(current_value):
    print(type(current_value))
    return current_value

Here the current_value is data containing all the child nodes at root "all_items". This works fine.

What I want is to pass an additional argument to the updateDatabase say cartList which is a list of dictionaries.
How should I do that?
What I essentially want is a function that looks something like this:

def updateDatabase(current_value, cartList):
    print(type(current_value))
    return current_value

How should I pass the list in calling the function:

tranRef = db.reference('all_items')
new_transRef = tranRef.transaction( ## what should I write here ##)

Body:
I was also dealing with same problem and I solved it by using lambda:

extra_param = ['your cart list here']
tranRef = db.reference('all_items')
new_transRef = tranRef.transaction(lambda current_value: updateDatabase(current_value, extra_param))

You can then call the transaction method like this:

def updateDatabase(current_value, cartList):
    print(type(current_value))
    return current_value


问:
Html purifier clears p tag
For some reason html purifier clears p tags. It happens when p is inside of span tags.
For example:

```<code><span class=\"large gray content_text article_text\">
<p>111111</p>
<p>222222</p>
<p>333333</p>
</span>
</code>```

Output:

```<code><span>111111

2222222

3333333</span>
</code>```

My htmlpurifier config:

```<code>$config = HTMLPurifier_Config::createDefault();
$config -> set('Core.Encoding', 'UTF-8');
$config -> set('HTML.Doctype', 'XHTML 1.0 Transitional');
$config -> set('HTML.TidyLevel','none');
$config -> set('HTML.Allowed', 'p, a[href|rel], span[style], img[src|style], object[height|width|data], param[name|value|allowscriptaccess|allowfullscreen|height|width], br, strong, em');
$config -> set('CSS.AllowedProperties', 'font-weight, font-style, text-decoration, color, width, height');
$config -> set('HTML.SafeObject', 'true');
$config -> set('Output.FlashCompat', 'true');
$config -> set('HTML.FlashAllowFullScreen', 'true');
$schemes = array('http' => true, 'https' => true);
$config -> set('URI.AllowedSchemes', $schemes);
$purifier = new HTMLPurifier($config);
$content = $purifier -> purify($content);
</code>```

答:
Hmm, HTML Purifier should have output:</p>

```<code><span class="large gray content_text article_text"></span>
<p><span class="large gray content_text article_text">111111</span></p>
<p><span class="large gray content_text article_text">222222</span></p>
<p><span class="large gray content_text article_text">333333</span></p>
<span class="large gray content_text article_text"></span>
</code>```

Title: Html purifier clears p tag

Body:
For some reason html purifier clears p tags. It happens when p is inside of span tags.
For example:

111111

222222

333333

Output:

111111

2222222

3333333

My htmlpurifier config:

$config = HTMLPurifier_Config::createDefault();
$config -> set('Core.Encoding', 'UTF-8');
$config -> set('HTML.Doctype', 'XHTML 1.0 Transitional');
$config -> set('HTML.TidyLevel','none');
$config -> set('HTML.Allowed', 'p, a[href|rel], span[style], img[src|style], object[height|width|data], param[name|value|allowscriptaccess|allowfullscreen|height|width], br, strong, em');
$config -> set('CSS.AllowedProperties', 'font-weight, font-style, text-decoration, color, width, height');
$config -> set('HTML.SafeObject', 'true');
$config -> set('Output.FlashCompat', 'true');
$config -> set('HTML.FlashAllowFullScreen', 'true');
$schemes = array('http' => true, 'https' => true);
$config -> set('URI.AllowedSchemes', $schemes);
$purifier = new HTMLPurifier($config);
$content = $purifier -> purify($content);

Body:
Hmm, HTML Purifier should have output:

<span class="large gray content_text article_text"></span>
<p><span class="large gray content_text article_text">111111</span></p>
<p><span class="large gray content_text article_text">222222</span></p>
<p><span class="large gray content_text article_text">333333</span></p>
<span class="large gray content_text article_text"></span>


问:
How to override the "MuiPaper-elevation1" atrribute in a Card component in Material-UI?
I have a Card component which is as below in HTML:

And I need to change the MuiPaper-elevation1 to MuiPaper-elevation0, which remove the shadow.

I tried

```<code>    <Card
      MuiPaperElevation0
      MuiPaper-elevation0
      style={{ boxShadow: 0 }}
    >
</code>```

but it doesn't work, nothing changed and the shadow is still there.

Could someone teach me how to do it plz?
Thx!

答:
You should just set boxShadow to none:</p>
```<code><Card style={{ boxShadow: 'none' }} >
</code>```

Body:
I have a Card component which is as below in HTML:

And I need to change the MuiPaper-elevation1 to MuiPaper-elevation0, which remove the shadow.

I tried

    <Card
      MuiPaperElevation0
      MuiPaper-elevation0
      style={{ boxShadow: 0 }}
    >

but it doesn't work, nothing changed and the shadow is still there.

Could someone teach me how to do it plz?
Thx!

Body:
You should just set boxShadow to none:

<Card style={{ boxShadow: 'none' }} >


问:
Build for prod with angular 7 results in Super expression must either be null or a function
I have a older angular application where I have implemented okta auth.

It uses angular 7.2, and okta versions

```<code>   "@okta/okta-angular": "^5.1.0",
    "@okta/okta-auth-js": "^5.9.0",
    "@okta/okta-signin-widget": "^5.16.1",
    "@oktadev/schematics": "^5.2.0",
</code>```

I'm using "target": "es2015",
When I'm compiling the app without the prod flag, everything works. But as soon as I compile with the --prod=true flag it crashes with the following error.

Uncaught TypeError: Super expression must either be null or a function.

If I go into the angular.json file and turn off optimizations, it works:

```<code>"optimization": false,
</code>```

But the application goes from 2mb to 9mb size.

What can I do to get optimizations to work?

答:
Turns out upgrading to angular 8 was the solution.</p>
```<code>npm config set legacy-peer-deps true
cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@8 update @angular/cli@8 @angular/core@8"
</code>```

Body:
I have a older angular application where I have implemented okta auth.

It uses angular 7.2, and okta versions

   "@okta/okta-angular": "^5.1.0",
    "@okta/okta-auth-js": "^5.9.0",
    "@okta/okta-signin-widget": "^5.16.1",
    "@oktadev/schematics": "^5.2.0",

I'm using "target": "es2015",
When I'm compiling the app without the prod flag, everything works. But as soon as I compile with the --prod=true flag it crashes with the following error.

Uncaught TypeError: Super expression must either be null or a function.

If I go into the angular.json file and turn off optimizations, it works:

"optimization": false,

But the application goes from 2mb to 9mb size.

What can I do to get optimizations to work?

Body:
Turns out upgrading to angular 8 was the solution.

npm config set legacy-peer-deps true
cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@8 update @angular/cli@8 @angular/core@8"


问:
Google Analytics - Events data not reflecting
In my website we have a banner which on clicking directs the user to our client's website. In order to track the number of people clicking the banner we decided to make use of the google analytics events component. I added the JS provided by them just below my Google analytics script.

```<code>var captureOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function(){document.location = url;} }); }
</code>```

Then in the place of the banner I called the function

```<code><a href="https://example.com/pg/" onclick="return captureOutboundLink('https://example.com/pg/');">
<img src="https://www.moreexample.com/admin/banner/mascot.jpg" alt="macott2022" title="macott2022" class="img-res innerbann" />
</code>```

But the google analytics events tab is still not tracking. I tried clicking the Banner few times but it shows no signs of activity. Does it take time to reflect ?

答:
yes, events report might need some time to process the data. you can use "events" section of real-time report instead.
moreover you might use Tag assistant or other GA debugging tool to make sure that your event data being sent.</p>

Body:
In my website we have a banner which on clicking directs the user to our client's website. In order to track the number of people clicking the banner we decided to make use of the google analytics events component. I added the JS provided by them just below my Google analytics script.

var captureOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function(){document.location = url;} }); }

Then in the place of the banner I called the function

But the google analytics events tab is still not tracking. I tried clicking the Banner few times but it shows no signs of activity. Does it take time to reflect ?


问:
How to create connection timeout with python SocketServer
Good day! I was writen simple server:

```<code>class SingleTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        self.request.close()

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

    daemon_threads = True

    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

def running():
    server = SimpleServer((settings.host, settings.port), SingleTCPHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)
</code>```

How to set connection timeout. I want when the client not send me data and is not active in 30 seconds, server will close connection.

P.S. sorry for my english.

UPDATE

```<code>#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import time

import SocketServer
import datetime
import settings
import os
from signal import SIGTERM, SIGCHLD, signal, alarm
import socket
import subprocess
from threading import Thread
import MySQLdb
import re

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    "One instance per connection.  Override handle(self) to customize action."
    def handle(self):
        alarm(30)
        data = self.request.recv(1024)
        # Some code
        self.request.close()

class SimpleServer(SocketServer.ForkingMixIn, SocketServer.TCPServer):

    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

def running():
    server = SimpleServer((settings.host, settings.port), SingleTCPHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

def deamonize(stdout='/dev/null', stderr=None, stdin='/dev/null', pidfile=None, startmsg='started with pid %s'):
    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError, e:
        sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)

    os.chdir(settings.place)
    os.umask(0)
    os.setsid()

    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError, e:
        sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)

    if (not stderr):
        stderr = stdout

        print stdin, stdout, stderr
        si = file(stdin, 'r')
        so = file(stdout, 'a+')
        se = file(stderr, 'a+', 0)
        pid = str(os.getpid())
        sys.stderr.write("\n%s\n" % startmsg % pid)
        sys.stderr.flush()
    if pidfile: file(pidfile, 'w+').write("%s\n" % pid)

    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null', pidfile='pid.txt', startmsg='started with pid %s'):
    if len(sys.argv) > 1:
        action = sys.argv[1]
        try:
            pf = open(pidfile)
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
        if ((action == 'stop') or (action == 'restart')):
            if (not pid):
                mess = "Не могу остановить, pid файл '%s' отсутствует.\n"
                sys.stderr.write(mess % pidfile)
                sys.exit(1)
            try:
                while 1:
                    os.kill(pid, SIGTERM)
                    time.sleep(1)
            except OSError, err:
                err = str(err)
                if err.find("No such process") > 0:
                    os.remove(pidfile)
                    if 'stop' == action:
                        sys.exit(0)
                    action = 'start'
                    pid = None
                else:
                    print str(err)
                    sys.exit(1)
        if ('start' == action):
            if (pid):
                mess = "Старт отменен — pid файл '%s' существует.\n"
                sys.stderr.write(mess % pidfile)
                sys.exit(1)
            deamonize(stdout, stderr, stdin, pidfile, startmsg)
            return
    print "Синтакс запуска: %s start|stop|restart" % sys.argv[0]
    sys.exit(2)

if (__name__ == "__main__"):
    startstop(stdout=settings.log, pidfile=settings.pid)
    running()
</code>```

答:
Please look at it:

```<code>import sys
import SocketServer

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(1024)
        self.request.close()

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

    timeout = 30

    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

    def handle_timeout(self):
        print 'Timeout!'

def running():
    server = SimpleServer(('localhost', 6666), SingleTCPHandler)
    try:
        #server.serve_forever()
        server.handle_request()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == '__main__':
    running()

# vim: filetype=python syntax=python expandtab shiftwidth=4 softtabstop=4 encoding=utf8
</code>```

If you want to handle more than one request you need to execute server.handle_request() again.

Body:
Good day! I was writen simple server:

class SingleTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        self.request.close()

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

    daemon_threads = True

    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

def running():
    server = SimpleServer((settings.host, settings.port), SingleTCPHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

How to set connection timeout. I want when the client not send me data and is not active in 30 seconds, server will close connection.

P.S. sorry for my english.

UPDATE

#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import time

import SocketServer
import datetime
import settings
import os
from signal import SIGTERM, SIGCHLD, signal, alarm
import socket
import subprocess
from threading import Thread
import MySQLdb
import re

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    "One instance per connection.  Override handle(self) to customize action."
    def handle(self):
        alarm(30)
        data = self.request.recv(1024)
        # Some code
        self.request.close()

class SimpleServer(SocketServer.ForkingMixIn, SocketServer.TCPServer):

    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

def running():
    server = SimpleServer((settings.host, settings.port), SingleTCPHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)

def deamonize(stdout='/dev/null', stderr=None, stdin='/dev/null', pidfile=None, startmsg='started with pid %s'):
    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError, e:
        sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)

    os.chdir(settings.place)
    os.umask(0)
    os.setsid()

    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError, e:
        sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
        sys.exit(1)

    if (not stderr):
        stderr = stdout

        print stdin, stdout, stderr
        si = file(stdin, 'r')
        so = file(stdout, 'a+')
        se = file(stderr, 'a+', 0)
        pid = str(os.getpid())
        sys.stderr.write("\n%s\n" % startmsg % pid)
        sys.stderr.flush()
    if pidfile: file(pidfile, 'w+').write("%s\n" % pid)

    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null', pidfile='pid.txt', startmsg='started with pid %s'):
    if len(sys.argv) > 1:
        action = sys.argv[1]
        try:
            pf = open(pidfile)
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
        if ((action == 'stop') or (action == 'restart')):
            if (not pid):
                mess = "Не могу остановить, pid файл '%s' отсутствует.\n"
                sys.stderr.write(mess % pidfile)
                sys.exit(1)
            try:
                while 1:
                    os.kill(pid, SIGTERM)
                    time.sleep(1)
            except OSError, err:
                err = str(err)
                if err.find("No such process") > 0:
                    os.remove(pidfile)
                    if 'stop' == action:
                        sys.exit(0)
                    action = 'start'
                    pid = None
                else:
                    print str(err)
                    sys.exit(1)
        if ('start' == action):
            if (pid):
                mess = "Старт отменен — pid файл '%s' существует.\n"
                sys.stderr.write(mess % pidfile)
                sys.exit(1)
            deamonize(stdout, stderr, stdin, pidfile, startmsg)
            return
    print "Синтакс запуска: %s start|stop|restart" % sys.argv[0]
    sys.exit(2)

if (__name__ == "__main__"):
    startstop(stdout=settings.log, pidfile=settings.pid)
    running()

Body:
Please look at it:

import sys
import SocketServer

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(1024)
        self.request.close()

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

    timeout = 30

    daemon_threads = True
    allow_reuse_address = True

    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

    def handle_timeout(self):
        print 'Timeout!'

def running():
    server = SimpleServer(('localhost', 6666), SingleTCPHandler)
    try:
        #server.serve_forever()
        server.handle_request()
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == '__main__':
    running()

# vim: filetype=python syntax=python expandtab shiftwidth=4 softtabstop=4 encoding=utf8

If you want to handle more than one request you need to execute server.handle_request() again.


问:
Common character count giving unexpected problems
I have a simple problem where you get two strings where you need to see how many characters are common.

```<code>For s1 = "aabcc" and s2 = "dacaa", the output should be
solution(s1, s2) = 3.
</code>```

I've seen a lot of people solve these types of problems, but I don't want to copy and paste. I want to learn it my way with my solution and improve upon that. I think my solution makes sense but it obviously doesn't, because it doesn't work.

This is my solution:

```<code>#include <iostream>

using namespace std;

int main()
{

        int counter {};
        string s1 = "aabcc";
        string s2 = "dacaa";

        for (int i {}; i < s1.size(); ++i)
        {
            for (int j {}; j < s2.size(); ++j)
            {
                if (s1.at(i) == s2.at(j));
                {
                    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
                    counter++;
                    s2.erase(s2.begin()+j);
                    break;
                }
            }

            cout << s2 << endl;
        }

        cout << counter << endl;

        return 0;
    }
</code>```

This is the output I get (I did a lot of "cout" for debugging purposes.

```<code>Found character a at index 0 and d at index 0
acaa
Found character a at index 1 and a at index 0
caa
Found character b at index 2 and c at index 0
aa
Found character a at index 3 and a at index 0

Found character a at index 4 and a at index 0

5
</code>```

Let's talk about the first iteration. What I don't understand is how s1.at(i) is equal to s2.at(j) at index 0? s1.at(0) is "a" and s2.at(0) is "d". Since when was a = d?
This problem is driving me crazy and I would appreciate if you could explain why my solution acts like this.

答:
There is a typo

```<code>if (s1.at(i) == s2.at(j));
</code>```

Remove the semicolon.

In general the approach is bad because it changes one of the source strings.

I can suggest the following solution by means of using an additional container.

```<code>#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <map>
#include <iterator>
#include <algorithm>
#include <numeric>

size_t common_letters( std::string_view s1, std::string_view s2 )
{
    std::map<char, std::pair<size_t, size_t>> m;

    for (char c : s1)
    {
        if ( m.count( c ) == 0 && s2.find( c ) != std::string_view::npos )
        {
            m[c].first  = std::count( std::begin( s1 ), std::end( s1 ), c );
            m[c].second = std::count( std::begin( s2 ), std::end( s2 ), c );
        }
    }

    return std::accumulate( std::begin( m ), std::end( m ), ( size_t )0,
        []( const auto &acc, const auto &item )
        {
            return acc + std::min( item.second.first, item.second.second );
        } );
}

int main()
{
    std::string s1 = "aabcc";
    std::string s2 = "dacaa";

    std::cout << "common_letters( s1, s2 ) = " << common_letters(s1, s2) << '\n';

    const char *s3 = "aabcc";
    const char *s4 = "dacaa";

    std::cout << "common_letters( s3, s4 ) = " << common_letters( s3, s4 ) << '\n';
}
</code>```

The program output is

```<code>common_letters( s1, s2 ) = 3
common_letters( s3, s4 ) = 3
</code>```

The if statement within the range-based for loop can be rewritten the following way to make the function more efficient

```<code>for (char c : s1)
{
    if ( auto pos = std::string_view::npos;
         m.count( c ) == 0 && ( pos = s2.find( c ) ) != std::string_view::npos )
    {
        m[c].first  = std::count( std::begin( s1 ), std::end( s1 ), c );
        m[c].second = std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), c );
    }
}
</code>```

Or if the compiler supports the C++ 20 then

```<code>for ( size_t i = 0; char c : s1)
{
    if ( auto pos = std::string_view::npos;
         m.count( c ) == 0 && ( pos = s2.find( c ) ) != std::string_view::npos )
    {
        m[c].first  = std::count( std::next( std::begin( s1 ), i ), std::end( s1 ), c );
        m[c].second = std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), c );
    }
    i++;
}
</code>```

Or instead of the range-based for loop there can be used an ordinary for loop with iterators. That is the function can look the following way

```<code>size_t common_letters( std::string_view s1, std::string_view s2 )
{
    std::map<char, std::pair<size_t, size_t>> m;

    for (  auto first = std::begin( s1 ), last = std::end( s1 ); first != last; ++first )
    {
        if ( auto pos = std::string_view::npos;
             m.count( *first ) == 0 && ( pos = s2.find( *first ) ) != std::string_view::npos )
        {
            m[*first] = { std::count( first , last, *first ),
                          std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), *first ) };
        }
    }

    return std::accumulate( std::begin( m ), std::end( m ), ( size_t )0,
        []( const auto &acc, const auto &item )
        {
            return acc + std::min( item.second.first, item.second.second );
        } );
}
</code>```

Body:
I have a simple problem where you get two strings where you need to see how many characters are common.

For s1 = "aabcc" and s2 = "dacaa", the output should be
solution(s1, s2) = 3.

I've seen a lot of people solve these types of problems, but I don't want to copy and paste. I want to learn it my way with my solution and improve upon that. I think my solution makes sense but it obviously doesn't, because it doesn't work.

This is my solution:

#include <iostream>

using namespace std;

int main()
{

        int counter {};
        string s1 = "aabcc";
        string s2 = "dacaa";

        for (int i {}; i < s1.size(); ++i)
        {
            for (int j {}; j < s2.size(); ++j)
            {
                if (s1.at(i) == s2.at(j));
                {
                    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
                    counter++;
                    s2.erase(s2.begin()+j);
                    break;
                }
            }

            cout << s2 << endl;
        }

        cout << counter << endl;

        return 0;
    }

This is the output I get (I did a lot of "cout" for debugging purposes.

Found character a at index 0 and d at index 0
acaa
Found character a at index 1 and a at index 0
caa
Found character b at index 2 and c at index 0
aa
Found character a at index 3 and a at index 0

Found character a at index 4 and a at index 0

5

Let's talk about the first iteration. What I don't understand is how s1.at(i) is equal to s2.at(j) at index 0? s1.at(0) is "a" and s2.at(0) is "d". Since when was a = d?
This problem is driving me crazy and I would appreciate if you could explain why my solution acts like this.

Body:
There is a typo

if (s1.at(i) == s2.at(j));

Remove the semicolon.

In general the approach is bad because it changes one of the source strings.

I can suggest the following solution by means of using an additional container.

#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <map>
#include <iterator>
#include <algorithm>
#include <numeric>

size_t common_letters( std::string_view s1, std::string_view s2 )
{
    std::map<char, std::pair<size_t, size_t>> m;

    for (char c : s1)
    {
        if ( m.count( c ) == 0 && s2.find( c ) != std::string_view::npos )
        {
            m[c].first  = std::count( std::begin( s1 ), std::end( s1 ), c );
            m[c].second = std::count( std::begin( s2 ), std::end( s2 ), c );
        }
    }

    return std::accumulate( std::begin( m ), std::end( m ), ( size_t )0,
        []( const auto &acc, const auto &item )
        {
            return acc + std::min( item.second.first, item.second.second );
        } );
}

int main()
{
    std::string s1 = "aabcc";
    std::string s2 = "dacaa";

    std::cout << "common_letters( s1, s2 ) = " << common_letters(s1, s2) << '\n';

    const char *s3 = "aabcc";
    const char *s4 = "dacaa";

    std::cout << "common_letters( s3, s4 ) = " << common_letters( s3, s4 ) << '\n';
}

The program output is

common_letters( s1, s2 ) = 3
common_letters( s3, s4 ) = 3

The if statement within the range-based for loop can be rewritten the following way to make the function more efficient

for (char c : s1)
{
    if ( auto pos = std::string_view::npos;
         m.count( c ) == 0 && ( pos = s2.find( c ) ) != std::string_view::npos )
    {
        m[c].first  = std::count( std::begin( s1 ), std::end( s1 ), c );
        m[c].second = std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), c );
    }
}

Or if the compiler supports the C++ 20 then

for ( size_t i = 0; char c : s1)
{
    if ( auto pos = std::string_view::npos;
         m.count( c ) == 0 && ( pos = s2.find( c ) ) != std::string_view::npos )
    {
        m[c].first  = std::count( std::next( std::begin( s1 ), i ), std::end( s1 ), c );
        m[c].second = std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), c );
    }
    i++;
}

Or instead of the range-based for loop there can be used an ordinary for loop with iterators. That is the function can look the following way

size_t common_letters( std::string_view s1, std::string_view s2 )
{
    std::map<char, std::pair<size_t, size_t>> m;

    for (  auto first = std::begin( s1 ), last = std::end( s1 ); first != last; ++first )
    {
        if ( auto pos = std::string_view::npos;
             m.count( *first ) == 0 && ( pos = s2.find( *first ) ) != std::string_view::npos )
        {
            m[*first] = { std::count( first , last, *first ),
                          std::count( std::next( std::begin( s2 ), pos ), std::end( s2 ), *first ) };
        }
    }

    return std::accumulate( std::begin( m ), std::end( m ), ( size_t )0,
        []( const auto &acc, const auto &item )
        {
            return acc + std::min( item.second.first, item.second.second );
        } );
}


问:
secondhalf is not been initialized

some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.why get me this error

```<code>class _ExpendedTextState extends State<ExpendedText> {
  late String firstHalf;
  late String secondHalf;
  bool hiddenText = true;
  double textHeight = Dimentions.screenHeight / 5.63;

  @override
  void initState() {
    super.initState();
    if (widget.text.length > textHeight) {
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }
  }

  @override
  Widget build(BuildContext context) {
    return secondHalf.isEmpty
        ? SmallText(text: firstHalf)
        : Column(
            children: [
              hiddenText
                  ? SmallText(
                      text: firstHalf + "....",
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6,
                    )
                  : SmallText(
                      text: firstHalf + secondHalf,
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6),
              InkWell(
                onTap: () {
                  setState(() {
                    hiddenText = !hiddenText;
                  });
                },
                child: Row(
                  children: [
                    SmallText(
                      text: 'Show more',
                      color: AppColors.mainColor,
                    ),
                    Icon(
                      hiddenText ? Icons.arrow_drop_down : Icons.arrow_drop_up,
                      color: AppColors.mainColor,
                    ),
                  ],
                ),
              )
            ],
          );
  }
}
</code>```

答:
This error occurs when you try to access a late variable that hasn't been initialized yet.

In your case, you need to check and debug

    if (widget.text.length > textHeight) { ///if amount of characters is greater than screenheight / 5.63 . This sounds like a very rare case.
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }
```

So lets say you have a screenheight of 563.
You'd need a text with 101 characters in order to initialize your late variables.

Title: secondhalf is not been initialized

Body:
some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.some one help me for this issu i cant solve this issu . i think i'm initialized secondhalf but why this error .pls some one help me.why get me this error

class _ExpendedTextState extends State<ExpendedText> {
  late String firstHalf;
  late String secondHalf;
  bool hiddenText = true;
  double textHeight = Dimentions.screenHeight / 5.63;

  @override
  void initState() {
    super.initState();
    if (widget.text.length > textHeight) {
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }
  }

  @override
  Widget build(BuildContext context) {
    return secondHalf.isEmpty
        ? SmallText(text: firstHalf)
        : Column(
            children: [
              hiddenText
                  ? SmallText(
                      text: firstHalf + "....",
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6,
                    )
                  : SmallText(
                      text: firstHalf + secondHalf,
                      color: AppColors.paraColor,
                      size: Dimentions.font16,
                      height: 1.6),
              InkWell(
                onTap: () {
                  setState(() {
                    hiddenText = !hiddenText;
                  });
                },
                child: Row(
                  children: [
                    SmallText(
                      text: 'Show more',
                      color: AppColors.mainColor,
                    ),
                    Icon(
                      hiddenText ? Icons.arrow_drop_down : Icons.arrow_drop_up,
                      color: AppColors.mainColor,
                    ),
                  ],
                ),
              )
            ],
          );
  }
}

Body:
This error occurs when you try to access a late variable that hasn't been initialized yet.

In your case, you need to check and debug

    if (widget.text.length > textHeight) { ///if amount of characters is greater than screenheight / 5.63 . This sounds like a very rare case.
      firstHalf = widget.text.substring(0, textHeight.toInt());
      secondHalf =
          widget.text.substring(textHeight.toInt() + 1, widget.text.length);
    }

So lets say you have a screenheight of 563.
You'd need a text with 101 characters in order to initialize your late variables.