问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
Well there is this ppossibility where:

```<code>$scope.setOperand=(operandEntered)=>{
    $scope.leftOperand=($scope.leftOperand===null)? // if
        operandEntered
        : // else if v
        ($scope.operator===null)?
            $scope.leftOperand+operandEntered
            : // else v
            (()=>{
                $scope.rightOperand=($scope.rightOperand===null)? // if
                    operandEntered
                    : // else if v
                    ($scope.answer===null)?
                        $scope.rightOperand+operandEntered
                        : // else v
                        $scope.rightOperand;
                return $scope.leftOperand;
            })();
};
</code>```

Which then shortens to this:

```<code>$scope.setOperand=(operandEntered)=>{$scope.leftOperand=($scope.leftOperand===null)?operandEntered:($scope.operator===null)?$scope.leftOperand+operandEntered:(()=>{$scope.rightOperand=($scope.rightOperand===null)?operandEntered:($scope.answer===null)?$scope.rightOperand+operandEntered:$scope.rightOperand;return $scope.leftOperand;})();};
</code>```

Which does exactly as you asks, and shortens each if/else if statement.

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
Well there is this ppossibility where:

$scope.setOperand=(operandEntered)=>{
    $scope.leftOperand=($scope.leftOperand===null)? // if
        operandEntered
        : // else if v
        ($scope.operator===null)?
            $scope.leftOperand+operandEntered
            : // else v
            (()=>{
                $scope.rightOperand=($scope.rightOperand===null)? // if
                    operandEntered
                    : // else if v
                    ($scope.answer===null)?
                        $scope.rightOperand+operandEntered
                        : // else v
                        $scope.rightOperand;
                return $scope.leftOperand;
            })();
};

Which then shortens to this:

$scope.setOperand=(operandEntered)=>{$scope.leftOperand=($scope.leftOperand===null)?operandEntered:($scope.operator===null)?$scope.leftOperand+operandEntered:(()=>{$scope.rightOperand=($scope.rightOperand===null)?operandEntered:($scope.answer===null)?$scope.rightOperand+operandEntered:$scope.rightOperand;return $scope.leftOperand;})();};

Which does exactly as you asks, and shortens each if/else if statement.


来源: stackexchange

问:
Python count items in dict value that is a list
Python 3.3, a dictionary with key-value pairs in this form.

```<code>d = {'T1': ['eggs', 'bacon', 'sausage']}
</code>```

The values are lists of variable length, and I need to iterate over the list items. This works:

```<code>count = 0
for l in d.values():
   for i in l: count += 1
</code>```

But it's ugly. There must be a more Pythonic way, but I can't seem to find it.

```<code>len(d.values())
</code>```

produces 1. It's 1 list (DUH). Attempts with Counter from here give 'unhashable type' errors.

答:
Doing my homework on Treehouse I came up with this. It can be made simpler by one step at least (that I know of), but it might be easier for beginners (like myself) to onderstand this version.</p>

```<code>dict = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['bread', 'butter', 'tosti']}

total = 0

for value in dict:
    value_list = dict[value]
    count = len(value_list)
    total += count

print(total)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Python 3.3, a dictionary with key-value pairs in this form.

d = {'T1': ['eggs', 'bacon', 'sausage']}

The values are lists of variable length, and I need to iterate over the list items. This works:

count = 0
for l in d.values():
   for i in l: count += 1

But it's ugly. There must be a more Pythonic way, but I can't seem to find it.

len(d.values())

produces 1. It's 1 list (DUH). Attempts with Counter from here give 'unhashable type' errors.

Body:
Doing my homework on Treehouse I came up with this. It can be made simpler by one step at least (that I know of), but it might be easier for beginners (like myself) to onderstand this version.

dict = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['bread', 'butter', 'tosti']}

total = 0

for value in dict:
    value_list = dict[value]
    count = len(value_list)
    total += count

print(total)


问:
attributeError:'module' object has no attribute 'MXIndexedRecordIO'
I have used im2rec.py to convert "caltech101 images" into record io format:

I have created "caltech.lst" succesfully using
os.system('python %s/tools/im2rec.py --list=1 --recursive=1 --shuffle=1 data/caltech data/101_ObjectCategories'%MXNET_HOME)
Then, when I run this :
os.system("python %s/tools/im2rec.py --train-ratio=0.8 --test-ratio=0.2 --num-thread=4 --pass-through=1 data/caltech data/101_ObjectCategories"%MXNET_HOME)
I have this error : attributeError:'module' object has no attribute 'MXIndexedRecordIO'
Please, someone has an idea to fix this error ?
Thanks in advance.

Environment info

Operating System:Windows 8.1

MXNet version:0.9.5

答: @user3824903 I think to create a bin directory, you have to compile MXNet from source with option USE_OPENCV=1</p>


问:
How to make console program to disappear and work in background?
How can I make console program disappear and work in the background?
I mean, I don't want to see the program, but I want to see it running in the task manager.

Thanks.

答: Assuming you cannot modify the console application and make it a windowless application you could create a windowless application that launches the console program and redirects all the standard input and output streams to "dummy" streams.</p>

OwnerDisplayName: Tal

OwnerDisplayName: Brian Ensink

ContentLicense: CC BY-SA 2.5


问:
IPv6 DNS query on Azure
I need to launch an IPv6 DNS query from my Azure VM.  I need to control all the parameters of this query.  I can do it via network calls or via the dig command.  Can I do this with Azure?  This probably: can the load balancer support an outbound IPv6 DNS query?</p>

答:
We needed to confirm that our DNS servers handled queries coming in over IPv6, and Azure was one of the cloud providers we could use.  It wasn't easy, but I eventually got it to work.

In order to get outgoing IPv6 service from an Azure VM, the VM needs to be created in an availability set with a load balancer that has public dynamic IPv6 addresses, inbound NAT rules for both IPv4 and IPv6, and load balancing rules for same.  Existing VMs can't be reconfigured to support this.  Azure seems to create some some of tunnel between the configured load balancer and the VMs you put in the same availability set.  This isn't obvious from the VM's perspective, except in that you can only communicate over IPv6 with the outside Internet and not with the other VMs in your Azure submit.

IPv6 support isn't currently possible to configure through the Azure portal.  I made heavy use of the following two links to get this working:

https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-ipv6-overview

https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-ipv6-internet-ps

You'll need a Windows VM to run much of the above; PowerShell for Linux and AzureRM.NetCore.Preview does not have feature parity with PowerShell in Windows.

I had to hack at the above example for some time before coming up with the following ... you may need to hack it some more to work in your environment.
Note that I ran this script from within Powershell ISE so I could pre-configure the environment with $mySecureCredentials and Login-AzureRMAccount as necessary.

The below will create a Centos 7.3 VM that can initiate IPv6 DNS queries against the Internet.  Note that you'll have to enable your IPv6 interfaces in the guest after rebooting.  Unfortunately my rep is too low to post more than 2 links, so search for 'azure linux dhcp ipv6' to see how enable DHCPv6 client configuration on your VM.

```<code>$resgroupName = 'YourResourceGroup'

$location = 'east US'  # of course, select your preferred location
# you will need some secure credentials.  run something like:
# $mySecureCredentials = Get-Credential -Message "Type the username and password of the local administrator account."

# you will also need to log into azure (Login-AzureRMAccount)

# IP addresses, load balancer config

$publicIPv4= New-AzureRmPublicIpAddress -name 'lb-pub-ipv4' -ResourceGroupName $resgroupName -location $location `
-Allocationmethod Static -IpAddressVersion IPv4 -domainnamelabel my-lbnrpipv4

$publicIPv6 = New-AzureRmPublicIpAddress -name 'lb-pub-ipv6' -ResourceGroupName $resgroupName -location $location `
-AllocationMethod Dynamic -IpAddressVersion IPv6 -DomainNameLabel my-lbnrpipv6

$FEIPConfigv4 = New-AzureRmLoadBalancerFrontendIpConfig -name "LB-Frontendv4" -PublicIpAddress $publicIPv4

$FEIPConfigv6 = New-AzureRmLoadBalancerFrontendIpConfig -name "LB-Frontendv6" -PublicIpAddress $publicIPv6

$backendpoolipv4 = New-AzureRmLoadBalancerBackendAddressPoolConfig -name "BackendPoolIPv4"

$backendpoolipv6 = New-AzureRmLoadBalancerBackendAddressPoolConfig -name "BackendPoolIPv6"

# This script assumes you already have a virtual network defined - replace myRG-vnet with the name of the virtual network you want to use.

$vnet = Get-AzureRmVirtualNetwork -name myRG-vnet -ResourceGroupName $resgroupName

# I assume you want to use the default subnet.

$backendSubnet = Get-AzureRmVirtualNetworkSubnetConfig -name default -virtualnetwork $vnet

# Create NAT rules for load balancer
# Even if you don't actually need any inbound rules, some rules appear to be necessary to make outbound IPv6 work.

# Inbound SSH
$inboundNATRule1v4 = New-AzureRmLoadBalancerInboundNatRuleConfig -name "NicNatRulev4" -FrontendIpConfiguration $FEIPConfigv4 -Protocol TCP -FrontendPort 22 -BackendPort 22
$inboundNATRule1v6 = New-AzureRmLoadBalancerInboundNatRuleConfig -name "NicNatRulev6" -FrontendIpConfiguration $FEIPConfigv6 -Protocol TCP -FrontendPort 22 -BackendPort 22

$lbrule1v4 = New-AzureRmLoadBalancerRuleConfig -name "HTTPv4" -FrontendIpConfiguration $FEIPConfigv4 -BackendAddressPool $backendpoolipv4 -Protocol TCP -FrontendPort 80 -BackendPort 80
$lbrule1v6 = New-AzureRmLoadBalancerRuleConfig -name "HTTPv6" -FrontendIpConfiguration $FEIPConfigv6 -BackendAddressPool $backendpoolipv6 -Protocol TCP -FrontendPort 80 -BackendPort 80

$NRPLB = New-AzureRmLoadBalancer -ResourceGroupName $resgroupName -name 'myNrpIPv6LB' -location $location `
-FrontendIpConfiguration $FEIPConfigv4,$FEIPConfigv6 -BackendAddressPool $backendpoolipv4,$backendpoolipv6 `
-LoadBalancingRule $lbrule1v4,$lbrule1v6 -inboundNatRule $inboundNATRule1v4,$inboundNATRule1v6

$nic1IPv4 = New-AzureRmNetworkInterfaceIpConfig -name "IPv4IPConfig" -PrivateIpAddressVersion "IPv4" -subnet $backendSubnet -LoadBalancerBackendAddressPool $backendpoolipv4 -LoadBalancerInboundNatRule $inboundNATRule1v4

$nic1IPv6 = New-AzureRmNetworkInterfaceIpConfig -name "IPv6IPConfig" -PrivateIpAddressVersion "IPv6" -LoadBalancerBackendAddressPool $backendpoolipv6 -LoadBalancerInboundNatRule $inboundNATRule1v6

$nic1 = New-AzureRmNetworkInterface -Name 'myNrpIPv6Nic0' -IpConfiguration $nic1IPv4,$nic1IPv6 `
-resourceGroupName $resgroupName -location $location

New-AzureRmAvailabilitySet -name "myNrpIPv6AvSet" -resourcegroupname $resgroupName -location $location

$avset1 = Get-AzureRmAvailabilitySet -resourcegroupname $resgroupName -name 'myNrpIPv6AvSet'

try {

 New-AzureRmStorageAccount -ResourceGroupName $resgroupName -name 'mynrpipv6stacct' -location $location -skuname `
 "Standard_LRS" -erroraction stop
   } catch {
     echo "new storage account failed, let's just hope it was a dup and gets found anyway"
 }

# find my existing storage account

$storAcct = Get-AzureRmStorageAccount -resourcegroupname $resgroupName -name 'mynrpipv6stacct'

if ($storAcct -eq $null) {
    throw "I could not find a storage accoount"
}

$nic1 = Get-AzureRmNetworkInterface -ResourceGroupName $resgroupName -name 'myNrpIPv6Nic0'

$vm1 = New-AzureRmVMConfig -vmName 'myNrpLinuxIPv6VM1' -vmSize 'Standard_d1' -AvailabilitySetId $avset1.Id
$vm1 = Set-AzureRmVMOperatingSystem -vm $vm1 -Linux -ComputerName 'myNrpLinuxIPv6VM1' -Credential $mySecureCredentials
$vm1 = Set-AzureRmVMSourceImage -VM $vm1 -PublisherName OpenLogic -Offer CentOS -Skus '7.3' -Version "latest"
$vm1 = Add-AzureRmVMNetworkInterface -VM $vm1 -Id $nic1.Id -Primary
$osDisk1Uri = $storAcct.PrimaryEndpoints.Blob.ToString() + "vhds/myNrpLinuxIPv6VM1osdisk.vhd"
$vm1 = Set-AzureRmVMOSDisk -VM $vm1 -Name 'myNrpLinuxIPv6VM1osdisk' -VhdUri $osDisk1Uri -CreateOption FromImage

echo now creating...
new-azurermvm -ResourceGroupName $resgroupName -location $location -VM $vm1

echo done
</code>```

Title: IPv6 DNS query on Azure

Body:
We needed to confirm that our DNS servers handled queries coming in over IPv6, and Azure was one of the cloud providers we could use.  It wasn't easy, but I eventually got it to work.

In order to get outgoing IPv6 service from an Azure VM, the VM needs to be created in an availability set with a load balancer that has public dynamic IPv6 addresses, inbound NAT rules for both IPv4 and IPv6, and load balancing rules for same.  Existing VMs can't be reconfigured to support this.  Azure seems to create some some of tunnel between the configured load balancer and the VMs you put in the same availability set.  This isn't obvious from the VM's perspective, except in that you can only communicate over IPv6 with the outside Internet and not with the other VMs in your Azure submit.

IPv6 support isn't currently possible to configure through the Azure portal.  I made heavy use of the following two links to get this working:

https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-ipv6-overview

https://learn.microsoft.com/en-us/azure/load-balancer/load-balancer-ipv6-internet-ps

You'll need a Windows VM to run much of the above; PowerShell for Linux and AzureRM.NetCore.Preview does not have feature parity with PowerShell in Windows.

I had to hack at the above example for some time before coming up with the following ... you may need to hack it some more to work in your environment.
Note that I ran this script from within Powershell ISE so I could pre-configure the environment with $mySecureCredentials and Login-AzureRMAccount as necessary.

The below will create a Centos 7.3 VM that can initiate IPv6 DNS queries against the Internet.  Note that you'll have to enable your IPv6 interfaces in the guest after rebooting.  Unfortunately my rep is too low to post more than 2 links, so search for 'azure linux dhcp ipv6' to see how enable DHCPv6 client configuration on your VM.

$resgroupName = 'YourResourceGroup'

$location = 'east US'  # of course, select your preferred location
# you will need some secure credentials.  run something like:
# $mySecureCredentials = Get-Credential -Message "Type the username and password of the local administrator account."

# you will also need to log into azure (Login-AzureRMAccount)

# IP addresses, load balancer config

$publicIPv4= New-AzureRmPublicIpAddress -name 'lb-pub-ipv4' -ResourceGroupName $resgroupName -location $location `
-Allocationmethod Static -IpAddressVersion IPv4 -domainnamelabel my-lbnrpipv4

$publicIPv6 = New-AzureRmPublicIpAddress -name 'lb-pub-ipv6' -ResourceGroupName $resgroupName -location $location `
-AllocationMethod Dynamic -IpAddressVersion IPv6 -DomainNameLabel my-lbnrpipv6

$FEIPConfigv4 = New-AzureRmLoadBalancerFrontendIpConfig -name "LB-Frontendv4" -PublicIpAddress $publicIPv4

$FEIPConfigv6 = New-AzureRmLoadBalancerFrontendIpConfig -name "LB-Frontendv6" -PublicIpAddress $publicIPv6

$backendpoolipv4 = New-AzureRmLoadBalancerBackendAddressPoolConfig -name "BackendPoolIPv4"

$backendpoolipv6 = New-AzureRmLoadBalancerBackendAddressPoolConfig -name "BackendPoolIPv6"

# This script assumes you already have a virtual network defined - replace myRG-vnet with the name of the virtual network you want to use.

$vnet = Get-AzureRmVirtualNetwork -name myRG-vnet -ResourceGroupName $resgroupName

# I assume you want to use the default subnet.

$backendSubnet = Get-AzureRmVirtualNetworkSubnetConfig -name default -virtualnetwork $vnet

# Create NAT rules for load balancer
# Even if you don't actually need any inbound rules, some rules appear to be necessary to make outbound IPv6 work.

# Inbound SSH
$inboundNATRule1v4 = New-AzureRmLoadBalancerInboundNatRuleConfig -name "NicNatRulev4" -FrontendIpConfiguration $FEIPConfigv4 -Protocol TCP -FrontendPort 22 -BackendPort 22
$inboundNATRule1v6 = New-AzureRmLoadBalancerInboundNatRuleConfig -name "NicNatRulev6" -FrontendIpConfiguration $FEIPConfigv6 -Protocol TCP -FrontendPort 22 -BackendPort 22

$lbrule1v4 = New-AzureRmLoadBalancerRuleConfig -name "HTTPv4" -FrontendIpConfiguration $FEIPConfigv4 -BackendAddressPool $backendpoolipv4 -Protocol TCP -FrontendPort 80 -BackendPort 80
$lbrule1v6 = New-AzureRmLoadBalancerRuleConfig -name "HTTPv6" -FrontendIpConfiguration $FEIPConfigv6 -BackendAddressPool $backendpoolipv6 -Protocol TCP -FrontendPort 80 -BackendPort 80

$NRPLB = New-AzureRmLoadBalancer -ResourceGroupName $resgroupName -name 'myNrpIPv6LB' -location $location `
-FrontendIpConfiguration $FEIPConfigv4,$FEIPConfigv6 -BackendAddressPool $backendpoolipv4,$backendpoolipv6 `
-LoadBalancingRule $lbrule1v4,$lbrule1v6 -inboundNatRule $inboundNATRule1v4,$inboundNATRule1v6

$nic1IPv4 = New-AzureRmNetworkInterfaceIpConfig -name "IPv4IPConfig" -PrivateIpAddressVersion "IPv4" -subnet $backendSubnet -LoadBalancerBackendAddressPool $backendpoolipv4 -LoadBalancerInboundNatRule $inboundNATRule1v4

$nic1IPv6 = New-AzureRmNetworkInterfaceIpConfig -name "IPv6IPConfig" -PrivateIpAddressVersion "IPv6" -LoadBalancerBackendAddressPool $backendpoolipv6 -LoadBalancerInboundNatRule $inboundNATRule1v6

$nic1 = New-AzureRmNetworkInterface -Name 'myNrpIPv6Nic0' -IpConfiguration $nic1IPv4,$nic1IPv6 `
-resourceGroupName $resgroupName -location $location

New-AzureRmAvailabilitySet -name "myNrpIPv6AvSet" -resourcegroupname $resgroupName -location $location

$avset1 = Get-AzureRmAvailabilitySet -resourcegroupname $resgroupName -name 'myNrpIPv6AvSet'

try {

 New-AzureRmStorageAccount -ResourceGroupName $resgroupName -name 'mynrpipv6stacct' -location $location -skuname `
 "Standard_LRS" -erroraction stop
   } catch {
     echo "new storage account failed, let's just hope it was a dup and gets found anyway"
 }

# find my existing storage account

$storAcct = Get-AzureRmStorageAccount -resourcegroupname $resgroupName -name 'mynrpipv6stacct'

if ($storAcct -eq $null) {
    throw "I could not find a storage accoount"
}

$nic1 = Get-AzureRmNetworkInterface -ResourceGroupName $resgroupName -name 'myNrpIPv6Nic0'

$vm1 = New-AzureRmVMConfig -vmName 'myNrpLinuxIPv6VM1' -vmSize 'Standard_d1' -AvailabilitySetId $avset1.Id
$vm1 = Set-AzureRmVMOperatingSystem -vm $vm1 -Linux -ComputerName 'myNrpLinuxIPv6VM1' -Credential $mySecureCredentials
$vm1 = Set-AzureRmVMSourceImage -VM $vm1 -PublisherName OpenLogic -Offer CentOS -Skus '7.3' -Version "latest"
$vm1 = Add-AzureRmVMNetworkInterface -VM $vm1 -Id $nic1.Id -Primary
$osDisk1Uri = $storAcct.PrimaryEndpoints.Blob.ToString() + "vhds/myNrpLinuxIPv6VM1osdisk.vhd"
$vm1 = Set-AzureRmVMOSDisk -VM $vm1 -Name 'myNrpLinuxIPv6VM1osdisk' -VhdUri $osDisk1Uri -CreateOption FromImage

echo now creating...
new-azurermvm -ResourceGroupName $resgroupName -location $location -VM $vm1

echo done


问:
How can I convert VRLM files to 3D PDF ? (python or freeware)
I would take an answer for either way, either using Python libraries or a freeware utility.
I have come across U3D-2-PDF but it seems that the project was abandoned and follow the instructions did not work (receiving an error)</p>

答:
Design Spark Mechanical solved my problem (freeware)
I was trying to get from Sketchup to 3D PDF via VRLM.
This software imports Skp files and exports them as 3D PDF </p>


问:
Kentico - Display query string as value of input field
I want to display the query string (if it's not empty) as the value of an input field, something like this <input name="campaign" type="hidden" value="ABC Campaign {% if (QueryString.GetValue("utm_source") != null) { return "| QueryString.GetValue("utm_source")"} %}" />

but couldn't make it work due to all the double quotes. I've tried escaping the quotes with back slash but didn't work. Could you help?
(The above code is placed inside the Form > Layout)

Body: {%String.IsNullOrEmpty(QueryString["utm_source"])?QueryString["utm_source"]:""%}


问:
Javascript synchronous loop in browser
Trying to automate a task in the browser with Greasemonkey.

Requirement: load a web page which contains a table displaying 15 out of 340+ results, with button controls to see the next page worth of results, go back, go to the end and so forth.

Collect the first 15 results --> got this working

Click on the 'Next' button  --> got this working

Wait until the page loads the next set of results --> dont know how

Repeat until the next button is disabled --> got this working

Cant show pictures cuz its a corporate app.

So far if I loop with setTimeouts, the timeouts get queued up and executed at the same time I think. Instead, the requirement is for the code to run the info collection, click next, wait, then collect info again.

答:
You can execute arbitrary JS logic mixed with API calls, recursion and timeouts sequentially via synchronous executor nsynjs:

function synchronousCode() {
    var i=0;
    while(true) {
      console.log("waiting 1 sec, iteration", i++);
      $('#myDiv').toggle();
      nsynWait(nsynjsCtx,1000);
    };
}

var ctx;
function btnStopClicked() {
    ctx.stop();
    ctx=null;
}

function btnStartClicked() {
    ctx=nsynjs.run(synchronousCode,{},function(){
   console.log("Synchronous Code done");
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/wrappers/nsynWait.js"></script>
<body>
  <button id="buttonStart" onclick="btnStartClicked()">Start</button>
  <button id="buttonStop" onclick="btnStopClicked()">Stop</button>
  <div id="myDiv">Flashing div</div>
</body></code>```

See more examples here: https://github.com/amaksr/nsynjs/tree/master/examples

Title: Javascript synchronous loop in browser

Body:
You can execute arbitrary JS logic mixed with API calls, recursion and timeouts sequentially via synchronous executor nsynjs:

function synchronousCode() {
    var i=0;
    while(true) {
      console.log("waiting 1 sec, iteration", i++);
      $('#myDiv').toggle();
      nsynWait(nsynjsCtx,1000);
    };
}

var ctx;
function btnStopClicked() {
    ctx.stop();
    ctx=null;
}

function btnStartClicked() {
    ctx=nsynjs.run(synchronousCode,{},function(){
   console.log("Synchronous Code done");
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
<script src="https://rawgit.com/amaksr/nsynjs/master/wrappers/nsynWait.js"></script>
<body>
  <button id="buttonStart" onclick="btnStartClicked()">Start</button>
  <button id="buttonStop" onclick="btnStopClicked()">Stop</button>
  <div id="myDiv">Flashing div</div>
</body>

See more examples here: https://github.com/amaksr/nsynjs/tree/master/examples


问:
IE screwiness (won't render empty cell in asp:listview)
I have an asp:listview using a css class.  On my dev system (VS2008), it renders correctly in Chrome, IE and FireFox.  On our production server (IIS 2.0), IE will not apply the style to an empty cell - but cells that contain text/whatever are fine.  Chrome and FireFox still render fine.  The style I want is a thin line on the bottom of each row, kind of like a row separator.  Any idea what I can try to fix this?

Here is the css I assign to the Item and AltItem templates

```<code>.itemtemplate
{
    background-color: White;
}
.itemtemplate TD
{
  border-bottom:solid 1px #eae9e1;
  border-right:solid 1px #eae9e1;
}
</code>```

Oh, one other thing.  If I change the background color in the css to say, orange, then the empty cells render with a border.

答:
In IE, a cell must have content of some kind to be displayed properly. Try programmatically adding an   entity to create empty content.

Edit:

To make sure that the   makes it into the html you may need to run your Eval through a method and return the result of the method:

```<code>...Text='<%# GetItemText(Eval("EmployeeNumber").ToString()) %>'
</code>```

With the code behind like:

```<code>public string GetItemText(string empNum)
{
    return (String.IsNullOrEmpty(empNum) ? " " : empNum;
}
</code>```

Body:
I have an asp:listview using a css class.  On my dev system (VS2008), it renders correctly in Chrome, IE and FireFox.  On our production server (IIS 2.0), IE will not apply the style to an empty cell - but cells that contain text/whatever are fine.  Chrome and FireFox still render fine.  The style I want is a thin line on the bottom of each row, kind of like a row separator.  Any idea what I can try to fix this?

Here is the css I assign to the Item and AltItem templates

.itemtemplate
{
    background-color: White;
}
.itemtemplate TD
{
  border-bottom:solid 1px #eae9e1;
  border-right:solid 1px #eae9e1;
}

Oh, one other thing.  If I change the background color in the css to say, orange, then the empty cells render with a border.

Body:
In IE, a cell must have content of some kind to be displayed properly. Try programmatically adding an &nbsp; entity to create empty content.

Edit:

To make sure that the &nbsp; makes it into the html you may need to run your Eval through a method and return the result of the method:

...Text='<%# GetItemText(Eval("EmployeeNumber").ToString()) %>'

With the code behind like:

public string GetItemText(string empNum)
{
    return (String.IsNullOrEmpty(empNum) ? "&nbsp;" : empNum;
}


问:
2 resources to notify the same service
Wanted to know if it's possible to notify the same service from two different resources:

let's say I have two configuration files:

```<code>file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~>file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~> service { 'some_service' :
  enable     => true,
}
</code>```

I'm not sure if the code above will even execute (because of the '~>' between the file resources)

答:
Use this:</p>

```<code>File {
  owner  => $owner,
  group  => $group,
  mode   => '0777',
  notify => Service['some_service'],
}

file {
  "${conf_dir}/1.conf":
  content => template("${module_name}/1.conf.erb");

  "${conf_dir}/2.conf":
  content => template("${module_name}/2.conf.erb"),
}

service { 'some_service':
  enable => true,
}
</code>```

Title: 2 resources to notify the same service

Body:
Wanted to know if it's possible to notify the same service from two different resources:

let's say I have two configuration files:

file { "${conf_dir}/1.conf" :
  content => template('1.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~>file { "${conf_dir}/2.conf" :
  content => template('2.conf.erb'),
  owner   => $owner,
  group   => $group,
  mode    => '0777',
}

~> service { 'some_service' :
  enable     => true,
}

I'm not sure if the code above will even execute (because of the '~>' between the file resources)

Body:
Use this:

File {
  owner  => $owner,
  group  => $group,
  mode   => '0777',
  notify => Service['some_service'],
}

file {
  "${conf_dir}/1.conf":
  content => template("${module_name}/1.conf.erb");

  "${conf_dir}/2.conf":
  content => template("${module_name}/2.conf.erb"),
}

service { 'some_service':
  enable => true,
}


问:
OpenGL on Mac operation
This is really architecture question or 'how does it work' question than a problem to solve.

Apple documentation claims that CGL is lowest level api for managing OpenGL contexts, yet is lacks functionality that allows to connect a context to a window.
AGL and Cocoa can bind a context to a window without a problem though, so the question is - how do they do that if they are built upon CGL?

The obvious way appears to be that they use CGL to render to offscreen memory and are then capable of compositing this somehow. If this is so, how does that happen?

答:
Complete example:</p>

```<code>/*
mkdir -p build/test.app/Contents/MacOS
clang++ --std=c++11
 -fno-exceptions
 -fno-rtti
 -mmacosx-version-min=10.9
 -Wno-writable-strings
 -Wno-deprecated-declarations
 -framework OpenGL
 -framework Carbon
 -g gui8.cpp
 -o build/test.app/Contents/MacOS/test

 */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <OpenGL/CGLTypes.h>
#include <OpenGL/CGLCurrent.h>
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl.h>

typedef int CGSConnectionID;
typedef int CGSWindowID;
typedef int CGSSurfaceID;

typedef uint32_t _CGWindowID;

extern "C" {

typedef int CGSConnection;
typedef int CGSWindow;
typedef int CGSValue;

typedef enum _CGSWindowOrderingMode {
   kCGSOrderAbove                =  1, // Window is ordered above target.
   kCGSOrderBelow                = -1, // Window is ordered below target.
   kCGSOrderOut                  =  0  // Window is removed from the on-screen window list.
} CGSWindowOrderingMode;

typedef void *CGSRegion;
typedef CGSRegion *CGSRegionRef;
typedef CGSWindow *CGSWindowRef;

extern CGError CGSNewWindow( CGSConnection cid, int, float, float, const CGSRegion, CGSWindowRef);
extern CGError CGSNewRegionWithRect( const CGRect * rect, CGSRegionRef newRegion );
extern OSStatus CGSOrderWindow(CGSConnection cid, CGSWindow win, CGSWindowOrderingMode place, CGSWindow relativeToWindow /* nullable */);
extern OSStatus CGSSetWindowProperty(const CGSConnection cid, CGSWindow wid, CGSValue key, CGSValue value);
extern CGSConnectionID CGSMainConnectionID(void);
extern CGError CGSAddSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID *sid);
extern CGError CGSSetSurfaceBounds(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, CGRect rect);
extern CGError CGSOrderSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, int a, int b);
extern OSStatus CGSMoveWindow(const CGSConnection cid, const CGSWindow wid, CGPoint *point);
extern CGLError CGLSetSurface(CGLContextObj gl, CGSConnectionID cid, CGSWindowID wid, CGSSurfaceID sid);

}
#define kCGSBufferedBackingType 2

int main () {

    CGLContextObj cgl_context = NULL;
    CGSWindow window = 0;

    int width = 500, height = 500;
    CGPoint window_pos = { .x = 200, .y = 200 };
    bool quit = false;

    CGSConnectionID connection_id = CGSMainConnectionID();
    assert(connection_id);

    {

        CGSRegion region = NULL;
        CGRect r = CGRectMake(0,0, width, height);
        auto err1 = CGSNewRegionWithRect(&r, &region);
        assert(region);
        auto err2 = CGSNewWindow(connection_id, kCGSBufferedBackingType, window_pos.x, window_pos.y, region, &window);
        assert(window);
        auto err3 = CGSOrderWindow(connection_id, window, kCGSOrderAbove, 0);
        assert (err3 == kCGErrorSuccess);

        CGLPixelFormatAttribute attributes[] = {
            kCGLPFADoubleBuffer,
            kCGLPFAAccelerated, // Hardware rendering
            // kCGLPFARendererID, (CGLPixelFormatAttribute) kCGLRendererGenericFloatID, // Software rendering
            (CGLPixelFormatAttribute)0
        };

        CGLPixelFormatObj pix;
        GLint num;
        auto err4 = CGLChoosePixelFormat(attributes, &pix, &num);
        assert(err4 == kCGLNoError); // CGLErrorString(err1)
        assert(pix);

        CGLCreateContext(pix, NULL, &cgl_context);
        assert(cgl_context);
        CGLDestroyPixelFormat(pix);
        CGLSetCurrentContext(cgl_context);

        GLint v_sync_enabled = 1;
        CGLSetParameter(cgl_context, kCGLCPSwapInterval, &v_sync_enabled);

        CGSSurfaceID surface_id = 0;
        auto err5 = CGSAddSurface(connection_id, window, &surface_id);
        assert(err5 == kCGErrorSuccess);
        auto err6 = CGSSetSurfaceBounds(connection_id, window, surface_id, CGRectMake(0, 0, width, height));
        assert(err6 == kCGErrorSuccess);
        auto err7 = CGSOrderSurface(connection_id, window, surface_id, 1, 0);
        assert(err7 == kCGErrorSuccess);

        auto err8 = CGLSetSurface(cgl_context, connection_id, window, surface_id);
        assert(err8 == kCGLNoError);

        GLint drawable = 0;
        CGLGetParameter(cgl_context, kCGLCPHasDrawable, &drawable);
        assert(drawable == 1);

    }

    assert(glGetError() == GL_NO_ERROR);

    CGPoint drag_starting_position;
    bool drag_started = false;
    while (!quit) {

        glClearColor(1,1,0,1);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        static float a = 0;
        glRotatef(a * 1000, 0, 0, 1);
        // printf("a: %f\n", a);
        a= a + .001;
        glBegin(GL_QUADS);
        if (a>1.5) a=0;
        glColor4f(0,a,1,1);
        glVertex2f(0.25, 0.25);
        glVertex2f(0.75, 0.25);
        glVertex2f(0.75, 0.75);
        glVertex2f(0.25, 0.75);
        glEnd();

        auto err1 = CGLFlushDrawable(cgl_context);
        assert(err1 == kCGLNoError);

        assert(glGetError() == GL_NO_ERROR);

    }

    CGLSetCurrentContext(NULL);
    CGLDestroyContext(cgl_context);

}
</code>```

Title: OpenGL on Mac operation

Body:
Complete example:

/*
mkdir -p build/test.app/Contents/MacOS
clang++ --std=c++11
 -fno-exceptions
 -fno-rtti
 -mmacosx-version-min=10.9
 -Wno-writable-strings
 -Wno-deprecated-declarations
 -framework OpenGL
 -framework Carbon
 -g gui8.cpp
 -o build/test.app/Contents/MacOS/test

 */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <OpenGL/CGLTypes.h>
#include <OpenGL/CGLCurrent.h>
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl.h>

typedef int CGSConnectionID;
typedef int CGSWindowID;
typedef int CGSSurfaceID;

typedef uint32_t _CGWindowID;

extern "C" {

typedef int CGSConnection;
typedef int CGSWindow;
typedef int CGSValue;

typedef enum _CGSWindowOrderingMode {
   kCGSOrderAbove                =  1, // Window is ordered above target.
   kCGSOrderBelow                = -1, // Window is ordered below target.
   kCGSOrderOut                  =  0  // Window is removed from the on-screen window list.
} CGSWindowOrderingMode;

typedef void *CGSRegion;
typedef CGSRegion *CGSRegionRef;
typedef CGSWindow *CGSWindowRef;

extern CGError CGSNewWindow( CGSConnection cid, int, float, float, const CGSRegion, CGSWindowRef);
extern CGError CGSNewRegionWithRect( const CGRect * rect, CGSRegionRef newRegion );
extern OSStatus CGSOrderWindow(CGSConnection cid, CGSWindow win, CGSWindowOrderingMode place, CGSWindow relativeToWindow /* nullable */);
extern OSStatus CGSSetWindowProperty(const CGSConnection cid, CGSWindow wid, CGSValue key, CGSValue value);
extern CGSConnectionID CGSMainConnectionID(void);
extern CGError CGSAddSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID *sid);
extern CGError CGSSetSurfaceBounds(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, CGRect rect);
extern CGError CGSOrderSurface(CGSConnectionID cid, _CGWindowID wid, CGSSurfaceID sid, int a, int b);
extern OSStatus CGSMoveWindow(const CGSConnection cid, const CGSWindow wid, CGPoint *point);
extern CGLError CGLSetSurface(CGLContextObj gl, CGSConnectionID cid, CGSWindowID wid, CGSSurfaceID sid);

}
#define kCGSBufferedBackingType 2

int main () {

    CGLContextObj cgl_context = NULL;
    CGSWindow window = 0;

    int width = 500, height = 500;
    CGPoint window_pos = { .x = 200, .y = 200 };
    bool quit = false;

    CGSConnectionID connection_id = CGSMainConnectionID();
    assert(connection_id);

    {

        CGSRegion region = NULL;
        CGRect r = CGRectMake(0,0, width, height);
        auto err1 = CGSNewRegionWithRect(&r, &region);
        assert(region);
        auto err2 = CGSNewWindow(connection_id, kCGSBufferedBackingType, window_pos.x, window_pos.y, region, &window);
        assert(window);
        auto err3 = CGSOrderWindow(connection_id, window, kCGSOrderAbove, 0);
        assert (err3 == kCGErrorSuccess);

        CGLPixelFormatAttribute attributes[] = {
            kCGLPFADoubleBuffer,
            kCGLPFAAccelerated, // Hardware rendering
            // kCGLPFARendererID, (CGLPixelFormatAttribute) kCGLRendererGenericFloatID, // Software rendering
            (CGLPixelFormatAttribute)0
        };

        CGLPixelFormatObj pix;
        GLint num;
        auto err4 = CGLChoosePixelFormat(attributes, &pix, &num);
        assert(err4 == kCGLNoError); // CGLErrorString(err1)
        assert(pix);

        CGLCreateContext(pix, NULL, &cgl_context);
        assert(cgl_context);
        CGLDestroyPixelFormat(pix);
        CGLSetCurrentContext(cgl_context);

        GLint v_sync_enabled = 1;
        CGLSetParameter(cgl_context, kCGLCPSwapInterval, &v_sync_enabled);

        CGSSurfaceID surface_id = 0;
        auto err5 = CGSAddSurface(connection_id, window, &surface_id);
        assert(err5 == kCGErrorSuccess);
        auto err6 = CGSSetSurfaceBounds(connection_id, window, surface_id, CGRectMake(0, 0, width, height));
        assert(err6 == kCGErrorSuccess);
        auto err7 = CGSOrderSurface(connection_id, window, surface_id, 1, 0);
        assert(err7 == kCGErrorSuccess);

        auto err8 = CGLSetSurface(cgl_context, connection_id, window, surface_id);
        assert(err8 == kCGLNoError);

        GLint drawable = 0;
        CGLGetParameter(cgl_context, kCGLCPHasDrawable, &drawable);
        assert(drawable == 1);

    }

    assert(glGetError() == GL_NO_ERROR);

    CGPoint drag_starting_position;
    bool drag_started = false;
    while (!quit) {

        glClearColor(1,1,0,1);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        static float a = 0;
        glRotatef(a * 1000, 0, 0, 1);
        // printf("a: %f\n", a);
        a= a + .001;
        glBegin(GL_QUADS);
        if (a>1.5) a=0;
        glColor4f(0,a,1,1);
        glVertex2f(0.25, 0.25);
        glVertex2f(0.75, 0.25);
        glVertex2f(0.75, 0.75);
        glVertex2f(0.25, 0.75);
        glEnd();

        auto err1 = CGLFlushDrawable(cgl_context);
        assert(err1 == kCGLNoError);

        assert(glGetError() == GL_NO_ERROR);

    }

    CGLSetCurrentContext(NULL);
    CGLDestroyContext(cgl_context);

}


问:
Elasticsearch Java API - How to get the number of documents without retrieving the documents
I need to get the number of documents in an index. not the documents themselves, but just this "how many" .

What's the best way to do that?

There is https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html. but I'm looking to do this in Java.

There also is https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/count.html, but it seems way old.

I can get all the documents in the given index and come up with "how many". But there must be a better way.

答:
Use the search API, but set it to return no documents and retrieve the count of hits from the SearchResponse object it returns.

For example:

```<code>import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response = client.prepareSearch("your_index_goes_here")
    .setTypes("YourTypeGoesHere")
    .setQuery(QueryBuilders.termQuery("some_field", "some_value"))
    .setSize(0) // Don't return any documents, we don't need them.
    .get();

SearchHits hits = response.getHits();
long hitsCount = hits.getTotalHits();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use the search API, but set it to return no documents and retrieve the count of hits from the SearchResponse object it returns.

For example:

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response = client.prepareSearch("your_index_goes_here")
    .setTypes("YourTypeGoesHere")
    .setQuery(QueryBuilders.termQuery("some_field", "some_value"))
    .setSize(0) // Don't return any documents, we don't need them.
    .get();

SearchHits hits = response.getHits();
long hitsCount = hits.getTotalHits();


问:
Cannot apply unary operator `-` to type `usize`
I'm trying to get some older Rust code to compile, and on this bit of code:

```<code>const SOMETHING: *const c_char = -1 as *const c_char;
</code>```

I get this error:

error: cannot apply unary operator `-` to type `usize`
  --> src/lib.rs:32:34
   |
32 | const SOMETHING: *const c_char = -1 as *const c_char;
   |
```

I suspect this is because c_char is unsigned and unsigned can't be negative, but I don't know how to fix it. This code worked with some unknown older version of Rust. I tried changing c_char to i8 just for fun and that didn't work.

答:
The type of the pointee is irrelevant. When you cast an integer to a pointer, Rust infers that the integer must be a usize, because it's the only type (besides isize, though it's not used as often) that is guaranteed to have the same size as a pointer.

Indeed, in Rust, the unary negation operator is no longer available for unsigned integer types. Instead, you should use the bitwise not operator (which is written !, not ~ as in C).

In two's complement binary, there is a straightforward equivalence between these two operators: !x == -(x + 1). Specifically, the equivalent of -1 is !0. Thus, you can write:

```<code>const SOMETHING: *const c_char = !0 as *const c_char;
</code>```

Body:
I'm trying to get some older Rust code to compile, and on this bit of code:

const SOMETHING: *const c_char = -1 as *const c_char;

I get this error:

error: cannot apply unary operator `-` to type `usize`
  --> src/lib.rs:32:34
   |
32 | const SOMETHING: *const c_char = -1 as *const c_char;
   |

I suspect this is because c_char is unsigned and unsigned can't be negative, but I don't know how to fix it. This code worked with some unknown older version of Rust. I tried changing c_char to i8 just for fun and that didn't work.

Body:
The type of the pointee is irrelevant. When you cast an integer to a pointer, Rust infers that the integer must be a usize, because it's the only type (besides isize, though it's not used as often) that is guaranteed to have the same size as a pointer.

Indeed, in Rust, the unary negation operator is no longer available for unsigned integer types. Instead, you should use the bitwise not operator (which is written !, not ~ as in C).

In two's complement binary, there is a straightforward equivalence between these two operators: !x == -(x + 1). Specifically, the equivalent of -1 is !0. Thus, you can write:

const SOMETHING: *const c_char = !0 as *const c_char;


问:
array of allowUnknownTags doesnt work
I have the latest of JsDoc (3.4.3), and as per the documentation of JsDoc, I added array of unknown tags, but got slapped with error of unknow tag

The @foo: tag is not a known tag.
"allowUnknownTags": [ "foo", "usage", "test" ]

Am I missing something ?

Am I expected to write customTag plugin ?

答:
allowUnknownTags takes a boolean, not an array.

```<code>[...]
"tags": {
    "allowUnknownTags": true,
    "dictionaries": ["jsdoc","closure"]
},
[...]
</code>```

See this question & answer "create custom tags with jsdoc" for more about defining your own tags in a custom dictionary*.

*: Maybe... I don't really know, but it seems about right.

http://usejsdoc.org/about-configuring-jsdoc.html

Title: array of allowUnknownTags doesnt work

Body:
allowUnknownTags takes a boolean, not an array.

[...]
"tags": {
    "allowUnknownTags": true,
    "dictionaries": ["jsdoc","closure"]
},
[...]

See this question & answer "create custom tags with jsdoc" for more about defining your own tags in a custom dictionary*.

*: Maybe... I don't really know, but it seems about right.

http://usejsdoc.org/about-configuring-jsdoc.html


问:
Access mysql remote database from command line
I have a server with Rackspace. I want to access the database from my local machine command line.

I tried like:

```<code>mysql -u username -h my.application.com -ppassword
</code>```

But it gives an error:

ERROR 2003 (HY000):

Can't connect to MySQL server on 'my.application.com' (10061)

What causes this error and how can I connect to the remote database?

答:
I assume you have MySQL installed on your machine. Execute the command below after filling missing details:</p>

```<code>mysql -uUSERNAME -pPASSWORD -hHOSTNAME -P3306
</code>```

Body:
I have a server with Rackspace. I want to access the database from my local machine command line.

I tried like:

mysql -u username -h my.application.com -ppassword

But it gives an error:

ERROR 2003 (HY000):

Can't connect to MySQL server on 'my.application.com' (10061)

What causes this error and how can I connect to the remote database?

Body:
I assume you have MySQL installed on your machine. Execute the command below after filling missing details:

mysql -uUSERNAME -pPASSWORD -hHOSTNAME -P3306


问:
ordering VirtualHosts in Apache conf
I'm having issues with my apache configuration.  The expected outcome is to allow all traffic to go to the default site trekfederation.com, UNLESS the subdomain is specified and matched otherwise.  My problem is that some of my subdomains still default to the main site.

I have two files as part of my configuration:

```<code> httpd.conf
 ships.conf
</code>```

here's httpd.conf's portion for virtualhost:

```<code>#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
#<VirtualHost *:80>
#    ServerAdmin webmaster@dummy-host.example.com
#    DocumentRoot /www/docs/dummy-host.example.com
#    ServerName dummy-host.example.com
#    ErrorLog logs/dummy-host.example.com-error_log
#    CustomLog logs/dummy-host.example.com-access_log common
#</VirtualHost>

<VirtualHost *:80>
    ServerName weather.trekfederation.com
    ServerAlias weather.trekfederation.com
    DocumentRoot "/var/www/html/weather"
</VirtualHost>

<VirtualHost *:80>
    ServerName oldsite.trekfederation.com
    ServerAlias oldstore.trekfederation.com
    DocumentRoot "/var/www/html/trekfed"
</VirtualHost>

<VirtualHost *:80>
    ServerName promenade.trekfederation.com
    Redirect / http://trekfederation.com/shop
</VirtualHost>

<VirtualHost *:80>
    ServerName donations.trekfederation.com
    Redirect / http://trekfederation.com/product-category/donations/
</VirtualHost>

Include conf.d/ships.conf

<VirtualHost *:80>
    ServerName trekfederation.com
    ServerAlias trekfederation.com www.trekfederation.com

Alias /phpmyadmin "/usr/share/phpMyAdmin"
<Directory "/usr/share/phpMyAdmin">
    DirectoryIndex index.php
    AllowOverride All
    Options FollowSymlinks
    Order allow,deny
    Allow from all
</Directory>

    ServerAlias www.iftcommand.com
    DocumentRoot "/var/www/html/trekweb"

</VirtualHost>

# Include conf.d/personal.conf

<VirtualHost *:80>
    ServerName ccc.trekfederation.com
    DocumentRoot "/var/www/html/ccc"
</VirtualHost>
</code>```

Ships.conf:

```<code><VirtualHost *:80>
    ServerName ussgeorgewashington.trekfederation.com
    ServerAlias ussgeorgewashington.trekfederation.net
    ServerAlias nfc1773a.trekfederation.com
    ServerAlias nfc1773a.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_GEORGE_WASHINGTON
</VirtualHost>

<VirtualHost *:80>
    ServerName ussfarragut.trekfederation.com
    ServerAlias ussfarragut.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_FARRAGUT
</VirtualHost>

<VirtualHost *:80>
    ServerName ussvortex.trekfederation.com
    ServerAlias ussvortex.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_VORTEX
</VirtualHost>

<VirtualHost *:80>
    ServerName ussvictory.trekfederation.com
    ServerAlias ussvictory.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_VICTORY
</VirtualHost>

<VirtualHost *:80>
    ServerName ussnavigator.trekfederation.com
    ServerAlias ussnavigator.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_NAVIGATOR
</VirtualHost>

<VirtualHost *:80>
    ServerName ussfirelace.trekfederation.com
    ServerAlias ussfirelace.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_FIRELACE
</VirtualHost>
</code>```

the site i'm working on is ussfirelace.trekfederation.com.  it still routes to trekfederation.com.

it does register with apache -S:

```<code>     port 80 namevhost ussfirelace.trekfederation.com (/etc/httpd/conf.d/ships.conf:34)
             alias ussfirelace.trekfederation.net
</code>```

what am I missing?
Thanks.

答:
The configs look good to me. Possible solutions / problems:

a) Did you restart your apache to load the new virtual host?

b) Have you checked that the DNS record points as A Record (or CNAME) to your server and no redirect is configured with your NS provider?

c) Have you checked your code, that it does not trigger a redirect (e.g. 301, or javascript...)?

d) Clearing browser cache is also some thing that you should take care of.

e) Doublecheck the URL you type for typos.

Title: ordering VirtualHosts in Apache conf

Body:
I'm having issues with my apache configuration.  The expected outcome is to allow all traffic to go to the default site trekfederation.com, UNLESS the subdomain is specified and matched otherwise.  My problem is that some of my subdomains still default to the main site.

I have two files as part of my configuration:

 httpd.conf
 ships.conf

here's httpd.conf's portion for virtualhost:

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
#<VirtualHost *:80>
#    ServerAdmin webmaster@dummy-host.example.com
#    DocumentRoot /www/docs/dummy-host.example.com
#    ServerName dummy-host.example.com
#    ErrorLog logs/dummy-host.example.com-error_log
#    CustomLog logs/dummy-host.example.com-access_log common
#</VirtualHost>

<VirtualHost *:80>
    ServerName weather.trekfederation.com
    ServerAlias weather.trekfederation.com
    DocumentRoot "/var/www/html/weather"
</VirtualHost>

<VirtualHost *:80>
    ServerName oldsite.trekfederation.com
    ServerAlias oldstore.trekfederation.com
    DocumentRoot "/var/www/html/trekfed"
</VirtualHost>

<VirtualHost *:80>
    ServerName promenade.trekfederation.com
    Redirect / http://trekfederation.com/shop
</VirtualHost>

<VirtualHost *:80>
    ServerName donations.trekfederation.com
    Redirect / http://trekfederation.com/product-category/donations/
</VirtualHost>

Include conf.d/ships.conf

<VirtualHost *:80>
    ServerName trekfederation.com
    ServerAlias trekfederation.com www.trekfederation.com

Alias /phpmyadmin "/usr/share/phpMyAdmin"
<Directory "/usr/share/phpMyAdmin">
    DirectoryIndex index.php
    AllowOverride All
    Options FollowSymlinks
    Order allow,deny
    Allow from all
</Directory>

    ServerAlias www.iftcommand.com
    DocumentRoot "/var/www/html/trekweb"

</VirtualHost>

# Include conf.d/personal.conf

<VirtualHost *:80>
    ServerName ccc.trekfederation.com
    DocumentRoot "/var/www/html/ccc"
</VirtualHost>

Ships.conf:

<VirtualHost *:80>
    ServerName ussgeorgewashington.trekfederation.com
    ServerAlias ussgeorgewashington.trekfederation.net
    ServerAlias nfc1773a.trekfederation.com
    ServerAlias nfc1773a.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_GEORGE_WASHINGTON
</VirtualHost>

<VirtualHost *:80>
    ServerName ussfarragut.trekfederation.com
    ServerAlias ussfarragut.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_FARRAGUT
</VirtualHost>

<VirtualHost *:80>
    ServerName ussvortex.trekfederation.com
    ServerAlias ussvortex.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_VORTEX
</VirtualHost>

<VirtualHost *:80>
    ServerName ussvictory.trekfederation.com
    ServerAlias ussvictory.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_VICTORY
</VirtualHost>

<VirtualHost *:80>
    ServerName ussnavigator.trekfederation.com
    ServerAlias ussnavigator.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_NAVIGATOR
</VirtualHost>

<VirtualHost *:80>
    ServerName ussfirelace.trekfederation.com
    ServerAlias ussfirelace.trekfederation.net
    DocumentRoot /var/www/html/NOVA/USS_FIRELACE
</VirtualHost>

the site i'm working on is ussfirelace.trekfederation.com.  it still routes to trekfederation.com.

it does register with apache -S:

     port 80 namevhost ussfirelace.trekfederation.com (/etc/httpd/conf.d/ships.conf:34)
             alias ussfirelace.trekfederation.net

what am I missing?
Thanks.


问:
Prevent appspec from running scripts (disable hooks)
I'm new to codedeploy. I managed to make a deployment to an ec2 instance successfully (and using git to manage code so everything works beautifully now).

I want some other people besides myself working in the project to be able to deploy source code to the instance but not be able to run a script (especially because codedeploy seems to be running as root). Think of it as an admin/webmaster scenario.

In other words, appspec.yml has the "hooks" section under it and you can run any scripts as part of the deployment. I want to prevent this, the instance has all the software ready for the deployment so won't be needing this.

2 questions:
1) Does this make sense or am I grossly misunderstanding something/am I overkilling by using codedeploy altogether?
2) If it makes sense, how can I achieve this?

答: This doesn't seem to be something that CodeDeploy is able to do at this moment. But do you want to disable the auto deploy from Github to CodeDeploy? And if anyone else push a code change, it'll exist on Github. When you are ok with the changes, you can do a manually deployment from Github on CodeDeploy console.</p>


问:
Visual Studio wont download
I wanted to install C++ from Visual Studio 2017, but it wouldn't.
So, I uninstalled Visual Studio 2017, then tried to install it again, but always goes to this

So then I clicked on "view log" and this is what I saw this

答: OH!  I just deleted anyTHING that even knows Visual Studio.  Now I can run the installer again!</p>

Title: Visual Studio wont download


问:
Overlay effect works with mouse but not with keyboard
Here is my problem. I'm building portfolio page, and now I want to make it easy to navigate for people that can't use the mouse.

What does the outline property do? It provides visual feedback for
  links that have "focus" when navigating a web document using the TAB
  key (or equivalent). This is especially useful for folks who can't use
  a mouse or have a visual impairment. If you remove the outline you are
  making your site inaccessible to these people.

I built it so you can navigate all the links on my page using TAB key and you can open that link using ENTER key.

But...

I have nice visual effect with overlay. You can see images of apps, and only when you hover the mouse above that picture you can see links.

So TAB is working and you can select a link using keyboard but you can't see active links, because that overlay effect works only with the mouse (while mouse is hovering above particular picture).

It is hard to explain by words, so I recorded a short video:
https://youtu.be/IQbXL7iyG6w?t=5

Any idea how to fix this? Overlay effect should be tiggered by TAB navigation as well.

GitHub code:
https://github.com/elminsterrr/portfolio

答:
You're showing your overlay on :hover when using TAB the elements get focused, so you have to add the :focus selector to your css for your overlay to show.

.my-class:hover .my-overlay { ... } => .my-class:focus .my-overlay, .my-class:hover .my-overlay { ... }


问:
How to initialize msvcrt.dll?
If I do a LoadLibrary("msvcrt.dll") do I need to initialize the CRT somehow? Section 2 in the following document seems to say that I do, but I just get an undefined symbol error for _CRT_INIT when I try to call _CRT_INIT:

http://support.microsoft.com/kb/94248

Edit: I should have said that this is for a program that dynamically loads all the dlls that it uses, hence the call to LoadLibrary("msvcrt.dll").

答: The link you referenced refers to using CRT_INIT() only when "Using the CRT Libraries When Building a DLL", and even then it is only one of two alternatives; the first probably being preferable in most cases.

Title: How to initialize msvcrt.dll?


问:
how to access object properties from TypeScript?
I'm new to Angular and TypeScript and just started working on a project using MEAN stack (MongoDB, Express, Angular, Node.js).

I created this mongoose module :

```<code>import * as mongoose from 'mongoose';

var Schema = mongoose.Schema;
const entrepriseSchema = new mongoose.Schema({
  name: {type: String, unique: true, required : true},
  telephone: Number,
  logo: String,
  web_site: String,
  sites: [
    {site_id: {type: Schema.Types.ObjectId, ref: 'Site'}}
  ]
});

const Entreprise = mongoose.model('Entreprise', entrepriseSchema);

export default Entreprise;
</code>```

and this is my entreprise.component.ts :

```<code>import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import { EntrepriseService } from '../services/entreprise.service';
import { SiteService } from '../services/site.service';

@Component({
  selector: 'app-entreprise',
  templateUrl: './entreprise.component.html',
  styleUrls: ['./entreprise.component.scss'],
  providers: [EntrepriseService, SiteService]
})
export class EntrepriseComponent implements OnInit {

  entreprise = {};
  sites = [];
  id: String;

  constructor(private entrepriseService: EntrepriseService,
              private siteService: SiteService,
              private http: Http,
              private route: ActivatedRoute) {
    this.id = route.snapshot.params['id'];
  }

  ngOnInit() {
    this.getEntrepriseById(this.id);
    //not working
    //console.log(this.entreprise.name);
    //console.log(this.entreprise.sites);
    //this.getSitesIn(this.entreprise.sites);
  }

  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => this.entreprise = data,
      error => console.log(error)
    );
  }

  getSitesIn(ids) {
    this.siteService.getSitesIn(ids).subscribe(
      data => this.sites = data,
      error => console.log(error)
    );
  }
}
</code>```

when I try to display the properties of the returned from entreprise.component.html it works fine and displays all the properties :

```<code>  <h3>{{entreprise.name}}</h3>
       <div *ngFor="let site of entreprise.sites">
         {{site.site_id}}
       </div>
         {{entreprise.logo}}
         {{entreprise.web_site}}
</code>```

but how can I access the same properties on the TypeScript side ?
The commented code in the EntrepriseComponent is what I'm trying to accomplish but it's not working since this.entreprise is type {} .

答:
The Enterprise model/schema that you created in Mongoose in Node.js resides on the server side. If you want the TypeScript code on the UI to recognize the properties in Enterprise, you will have to create a class in your angular codebase.

Create a folder named, say, models at the same level as your services folder. (Optional)

Create two files named site.ts and enterprise.ts in the models folder created in the previous step (You can put these file at a different location if you want) with the following contents:

site.ts

```<code>export interface Site {
 site_id?: string;
}
</code>```

enterprise.ts

```<code>import { Site } from './site';
export interface Enterprise {
 name?: string;
 telephone?: string;
 logo?: string;
 web_site?: string;
 sites?: Site[];
}
</code>```

Now, inside the EntrepriseComponent file, add the following imports

```<code>import { Enterprise} from '../models/entreprise';
import { Site } from '../models/site';
</code>```

And change the first lines inside the EntrepriseComponent file to

```<code>export class EntrepriseComponent implements OnInit {

  entreprise: Enterprise = {};
  sites: Site[] = [];
</code>```

Now, the enterprise attribute will be of type Enterprise and you will be able to access the properties that we declared in the enterprise.ts file.

Update:
Also, you cannot console.log(this.enterprise.name) immediately after this.getEntrepriseById(this.id); in your ngOnInit() function. This is because the web service you are making to get the enterprise object would not have resolved when you are trying to log it to the console.

If you want to see the enterprise object in the console or you want to run some code that needs to run after the service call has resolved and the this.enterprise object has a value, the best place to do this would be your getEntrepriseById function. Change the getEntrepriseById function to

```<code>  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => {
           this.enterprise = data;
           console.log(this.enterprise.name);
           // Any code to run after this.enterprise resolves can go here.
      },
      error => console.log(error)
    );
  }
</code>```

Body:
I'm new to Angular and TypeScript and just started working on a project using MEAN stack (MongoDB, Express, Angular, Node.js).

I created this mongoose module :

import * as mongoose from 'mongoose';

var Schema = mongoose.Schema;
const entrepriseSchema = new mongoose.Schema({
  name: {type: String, unique: true, required : true},
  telephone: Number,
  logo: String,
  web_site: String,
  sites: [
    {site_id: {type: Schema.Types.ObjectId, ref: 'Site'}}
  ]
});

const Entreprise = mongoose.model('Entreprise', entrepriseSchema);

export default Entreprise;

and this is my entreprise.component.ts :

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import { EntrepriseService } from '../services/entreprise.service';
import { SiteService } from '../services/site.service';

@Component({
  selector: 'app-entreprise',
  templateUrl: './entreprise.component.html',
  styleUrls: ['./entreprise.component.scss'],
  providers: [EntrepriseService, SiteService]
})
export class EntrepriseComponent implements OnInit {

  entreprise = {};
  sites = [];
  id: String;

  constructor(private entrepriseService: EntrepriseService,
              private siteService: SiteService,
              private http: Http,
              private route: ActivatedRoute) {
    this.id = route.snapshot.params['id'];
  }

  ngOnInit() {
    this.getEntrepriseById(this.id);
    //not working
    //console.log(this.entreprise.name);
    //console.log(this.entreprise.sites);
    //this.getSitesIn(this.entreprise.sites);
  }

  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => this.entreprise = data,
      error => console.log(error)
    );
  }

  getSitesIn(ids) {
    this.siteService.getSitesIn(ids).subscribe(
      data => this.sites = data,
      error => console.log(error)
    );
  }
}

when I try to display the properties of the returned from entreprise.component.html it works fine and displays all the properties :

{{entreprise.name}}

         {{site.site_id}}

         {{entreprise.logo}}
         {{entreprise.web_site}}

but how can I access the same properties on the TypeScript side ?
The commented code in the EntrepriseComponent is what I'm trying to accomplish but it's not working since this.entreprise is type {} .

Body:
The Enterprise model/schema that you created in Mongoose in Node.js resides on the server side. If you want the TypeScript code on the UI to recognize the properties in Enterprise, you will have to create a class in your angular codebase.

Create a folder named, say, models at the same level as your services folder. (Optional)

Create two files named site.ts and enterprise.ts in the models folder created in the previous step (You can put these file at a different location if you want) with the following contents:

site.ts

export interface Site {
 site_id?: string;
}

enterprise.ts

import { Site } from './site';
export interface Enterprise {
 name?: string;
 telephone?: string;
 logo?: string;
 web_site?: string;
 sites?: Site[];
}

Now, inside the EntrepriseComponent file, add the following imports

import { Enterprise} from '../models/entreprise';
import { Site } from '../models/site';

And change the first lines inside the EntrepriseComponent file to

export class EntrepriseComponent implements OnInit {

  entreprise: Enterprise = {};
  sites: Site[] = [];

Now, the enterprise attribute will be of type Enterprise and you will be able to access the properties that we declared in the enterprise.ts file.

Update:
Also, you cannot console.log(this.enterprise.name) immediately after this.getEntrepriseById(this.id); in your ngOnInit() function. This is because the web service you are making to get the enterprise object would not have resolved when you are trying to log it to the console.

If you want to see the enterprise object in the console or you want to run some code that needs to run after the service call has resolved and the this.enterprise object has a value, the best place to do this would be your getEntrepriseById function. Change the getEntrepriseById function to

  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => {
           this.enterprise = data;
           console.log(this.enterprise.name);
           // Any code to run after this.enterprise resolves can go here.
      },
      error => console.log(error)
    );
  }


问:
Regular expression to select group of text/bunch of lines based on specific line of text
I have the text in below format

```<code>Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint4 @543fsdf
Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint1 @345277
Scenario: Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt returned correct singular message
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

@Sprint1 @xyz1234
Scenario: At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur
</code>```

I want to select whole scenario based on a line of text in it.

For eg.

based on the line 'Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'

I want the second scenario

```<code>Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla
</code>```

, also the third and fourth scenario - but not the first one

I am trying

```<code>Scenario[\s\S]*?Given sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua[\s\S]*?(?=(@|Scenario))
</code>```

But that gives me first and second scenarios together and third but no fourth scenario. I tried other patterns as well but not a lot of success. Help?

答:
Given that your Scenario always begin on a new line, you can use look-behind to search for that, and you can use look-aheat to search for whitespace followed by @ or end of the string to capture the end of a matched block. So, for your example:

```<code>(?<=\s)Scenario.*?[\r\n]+Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua[\r\n]+.*?(?=\s+@|\s*$)
</code>```

You didn't specify what language are you using so you'll have to do the set up, but from options (if not default) you need to choose that dot matches line breaks, and that ^ and $ don't match line breaks but rather the whole string.

Body:
I have the text in below format

Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint4 @543fsdf
Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

@Sprint1 @345277
Scenario: Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt returned correct singular message
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

@Sprint1 @xyz1234
Scenario: At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
And Duis aute irure dolor in reprehenderit
When Ut enim ad minim veniam, quis nostrud
Then quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur

I want to select whole scenario based on a line of text in it.

For eg.

based on the line 'Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua'

I want the second scenario

Scenario: Lorem ipsum dolor sit amet, consectetur adipiscing elit
Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
When Ut enim ad minim veniam, quis nostrud exercitation
Then In voluptate velit esse cillum dolore eu fugiat nulla

, also the third and fourth scenario - but not the first one

I am trying

Scenario[\s\S]*?Given sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua[\s\S]*?(?=(@|Scenario))

But that gives me first and second scenarios together and third but no fourth scenario. I tried other patterns as well but not a lot of success. Help?

Body:
Given that your Scenario always begin on a new line, you can use look-behind to search for that, and you can use look-aheat to search for whitespace followed by @ or end of the string to capture the end of a matched block. So, for your example:

(?<=\s)Scenario.*?[\r\n]+Given sed do eiusmod tempor incididunt ut labore et dolore magna aliqua[\r\n]+.*?(?=\s+@|\s*$)

You didn't specify what language are you using so you'll have to do the set up, but from options (if not default) you need to choose that dot matches line breaks, and that ^ and $ don't match line breaks but rather the whole string.


答:
If you truly want to set a pointer to -1, you can, you just need to be explicit that the integral value is a isize, not a usize:

```<code>const SOMETHING: *const c_char = -1_isize as *const c_char;
</code>```

You can also say that it's the maximum usize value:

```<code>const SOMETHING: *const c_char = std::usize::MAX as *const c_char;
</code>```

Both of these have the same result:

```<code>extern crate libc;

use libc::c_char;

const SOMETHING1: *const c_char = -1_isize as *const c_char;
const SOMETHING2: *const c_char = std::usize::MAX as *const c_char;

fn main() {
    println!("{:p}", SOMETHING1);
    println!("{:p}", SOMETHING2);
}
</code>```

Prints:

0xffffffffffffffff
0xffffffffffffffff
```

Title: Cannot apply unary operator `-` to type `usize`

Body:
If you truly want to set a pointer to -1, you can, you just need to be explicit that the integral value is a isize, not a usize:

const SOMETHING: *const c_char = -1_isize as *const c_char;

You can also say that it's the maximum usize value:

const SOMETHING: *const c_char = std::usize::MAX as *const c_char;

Both of these have the same result:

extern crate libc;

use libc::c_char;

const SOMETHING1: *const c_char = -1_isize as *const c_char;
const SOMETHING2: *const c_char = std::usize::MAX as *const c_char;

fn main() {
    println!("{:p}", SOMETHING1);
    println!("{:p}", SOMETHING2);
}

Prints:

0xffffffffffffffff
0xffffffffffffffff


问:
How to merge specific file in git and manually resolve diffs?
With git, how can I perform a manual merge of specific files? When I say "manual merge" I mean so that git inserts the <<<<HEAD, and =====, etc. lines and requires me to make a selection (please enlighten me if the term for this is not "manual merge").

I read this Q&A so I'm aware that git checkout <branch> <file> <file> ... lets me pull files from my desired source branch; but is there a way to also manually resolve all diffs?

Attempting to combine information from multiple sources, I tried git merge --no-commit source_branch ../file.c, but git's response was merge: ../file.c - not something we can merge.

答:
The git merge command deals in commits (period, full stop, end of options ... well, there are some options, but they still apply to the commit-wide merge).  It:

starts with the current (HEAD) commit;

takes something to specify the other commit, usually a branch name;

automatically finds the merge-base commit using git merge-base --all HEAD other-commit;

and (assuming a single merge base) merges all the files resulting from two diffs: diff -M base HEAD, and diff -M base other.

So unless one or both of those two commit-wide git diff commands only pick out one changed file, you cannot use git merge to do this.

You can use git checkout -p to do an interactive patch to one file, as compared to a second file.  This is not a merge, although some people refer to this as a "two-way merge" operation.

So, the probable solution

You can also use git checkout or git show to extract specific versions of a single file from particular commits.  If you select three such versions—a merge base, the current commit, and some other commit, for instance—you can then instruct Git to perform a three-way merge on that one file, using the git merge-file command.  For instance:

```<code>git show 1234567:foo.txt > /tmp/foo.txt.base
cp foo.txt /tmp/foo.txt.merge
git show 8888888:foo.txt > /tmp/foo.txt.other

(cd /tmp; git merge-file foo.txt.merge foo.txt.base foo.txt.other)
</code>```

You now have a merged file in /tmp/foo.txt.merge, complete with any conflict markers.  Note that this file is independent of a Git repository, but if you like it, you can replace any of the files in your work-tree (such as foo.txt) with it.  Or, of course, you can even just do the merge-file operation directly in your work-tree.

If you replace the first hard-coded commit hash with the other branch name, and the middle (merge base) commit hash with the hash produced by git merge-base --all HEAD otherbranch, you probably get the kind of thing you want.

A possibly-easier alternative

You can also run git merge -n to run a full merge (of all files, automatically finding the merge base commit) but avoid committing the resulting merge even if it all seems to Git to have worked.  You can then finish only the part of the merge you care about, save the result, run git merge --abort to terminate the in-progress merge, and copy the saved result back.

Body:
The git merge command deals in commits (period, full stop, end of options ... well, there are some options, but they still apply to the commit-wide merge).  It:

starts with the current (HEAD) commit;

takes something to specify the other commit, usually a branch name;

automatically finds the merge-base commit using git merge-base --all HEAD other-commit;

and (assuming a single merge base) merges all the files resulting from two diffs: diff -M base HEAD, and diff -M base other.

So unless one or both of those two commit-wide git diff commands only pick out one changed file, you cannot use git merge to do this.

You can use git checkout -p to do an interactive patch to one file, as compared to a second file.  This is not a merge, although some people refer to this as a "two-way merge" operation.

So, the probable solution

You can also use git checkout or git show to extract specific versions of a single file from particular commits.  If you select three such versions—a merge base, the current commit, and some other commit, for instance—you can then instruct Git to perform a three-way merge on that one file, using the git merge-file command.  For instance:

git show 1234567:foo.txt > /tmp/foo.txt.base
cp foo.txt /tmp/foo.txt.merge
git show 8888888:foo.txt > /tmp/foo.txt.other

(cd /tmp; git merge-file foo.txt.merge foo.txt.base foo.txt.other)

You now have a merged file in /tmp/foo.txt.merge, complete with any conflict markers.  Note that this file is independent of a Git repository, but if you like it, you can replace any of the files in your work-tree (such as foo.txt) with it.  Or, of course, you can even just do the merge-file operation directly in your work-tree.

If you replace the first hard-coded commit hash with the other branch name, and the middle (merge base) commit hash with the hash produced by git merge-base --all HEAD otherbranch, you probably get the kind of thing you want.

A possibly-easier alternative

You can also run git merge -n to run a full merge (of all files, automatically finding the merge base commit) but avoid committing the resulting merge even if it all seems to Git to have worked.  You can then finish only the part of the merge you care about, save the result, run git merge --abort to terminate the in-progress merge, and copy the saved result back.


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答: Exceptions are a way for code to notify callers of some kind of failure. The calling code can do whatever they want with it, like display an error message, suppress the exception and degrade gracefully, etc.</p>


答:
I've pulled off something close to what I wanted:

```<code>>git checkout source_branch ../file.c
>git reset HEAD ../file.c
Unstaged changes after reset:
M       utils/file.c
>git add -p ../file.c
</code>```

The above brings me to the interactive hunk editor.

I guess this is sort of, kind of okay, but is there a better answer out there? I.e. one that inserts the <<<<HEAD, and =====, etc. lines and requires my manual resolution on a per-file basis instead of on a per-hunk basis which my workaround requires?

Title: How to merge specific file in git and manually resolve diffs?

Body:
With git, how can I perform a manual merge of specific files? When I say "manual merge" I mean so that git inserts the <<<<HEAD, and =====, etc. lines and requires me to make a selection (please enlighten me if the term for this is not "manual merge").

I read this Q&A so I'm aware that git checkout <branch> <file> <file> ... lets me pull files from my desired source branch; but is there a way to also manually resolve all diffs?

Attempting to combine information from multiple sources, I tried git merge --no-commit source_branch ../file.c, but git's response was merge: ../file.c - not something we can merge.

Body:
I've pulled off something close to what I wanted:

>git checkout source_branch ../file.c
>git reset HEAD ../file.c
Unstaged changes after reset:
M       utils/file.c
>git add -p ../file.c

The above brings me to the interactive hunk editor.

I guess this is sort of, kind of okay, but is there a better answer out there? I.e. one that inserts the <<<<HEAD, and =====, etc. lines and requires my manual resolution on a per-file basis instead of on a per-hunk basis which my workaround requires?


问:
jQuery scrollTop - Issue with wrong hash
I am trying to do scrollTop animation to an anchor that resides inside of a fullscreen
, but does not scroll to right anchor at first click. Here's my code.

```<code><nav id="scroller"> <a href="#subBox1">Scroll me to sub 1</a>
 <a href="#subBox2">Scroll me to sub 2</a>
 <a href="#subBox3">Scroll me to sub 3</a>

</nav>
<section id="boxTop"></section>
<section id="boxMaster">
    <section id="subBox1">
        <p>Hello. I am the Sub 1!</p>
    </section>
    <section id="subBox2">
        <p>Hello. I am the Sub 2!</p>
    </section>
    <section id="subBox3">
        <p>Hello. I am the Sub 3!</p>
    </section>
</section>
</code>```

```<code>$("#scroller a").click(function () {
    $('#boxMaster').animate({
        scrollTop: $(this.hash).offset().top
    }, 700);
    $("#scroller a").removeClass("active");
    $(this).addClass("active");
});
</code>```

fiddle

$("#scroller a").click(function() {
  $('#boxMaster').animate({
    scrollTop: $(this.hash).offset().top
  }, 700);
  $("#scroller a").removeClass("active");
  $(this).addClass("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#scroller {
  position: fixed;
  top: 0;
  height: 30px;
  text-align: center;
}
#scroller a {
  color: #fff;
  margin: 0 20px;
  text-decoration: none;
}
#scroller a.active {
  font-weight: bold;
  text-decoration: underline;
}
#boxTop {
  width: 100%;
  height: 100%;
  background: red;
}
#boxMaster {
  width: 100%;
  height: 100%;
  background: blue;
  overflow: hidden;
}
#boxMaster #subBox1,
#boxMaster #subBox2,
#boxMaster #subBox3 {
  width: 100%;
  height: 100%;
  display: table;
}
p {
  color: #fff;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}</code>```

 Scroll me to sub 1
  Scroll me to sub 2
  Scroll me to sub 3

Hello. I am the Sub 1!

Hello. I am the Sub 2!

Hello. I am the Sub 3!

```

答:
I have a fixed header. I started with w3school's code. However, I've been struggling with this same problem for so long, finally found a workaround for the "first click incorrect" issue:

Just before (outside) of my click event, I simply created a variable "x", initialized:

```<code>var x=1;
</code>```

Then I have a conditional statement inside the click event checking for x:

```<code>    if (x==1) {
        console.log("x is now: " + x);
        x=0;
        console.log("x is now: " + x);
        jQuery("html, body").animate({
            scrollTop: jQuery("div.class-of-element-i-am-scrolling-to" + hash).position().top - jQuery("div.header-container").outerHeight(true) - jQuery("h3.another-element-in-my-way").outerHeight(true)
            }, 2000, function(){
            return false;
        });
    } else {
        jQuery("html, body").animate({
            scrollTop: jQuery("div.class-of-element-i-am-scrolling-to" + hash).position().top
            }, 2000, function(){
            return false;
        });
    }
</code>```

In other words, using "x" as a flag to check if it is the first time the code is run.

If it is, then I am kind of cheating by subtracting the fixed header and the other elements that are pulling my desired div up.  Remember to make "x=0" to "drop" the flag.

If it isn't, then it works fine anyway.

Body:
I am trying to do scrollTop animation to an anchor that resides inside of a fullscreen
, but does not scroll to right anchor at first click. Here's my code.

 Scroll me to sub 1
 Scroll me to sub 2
 Scroll me to sub 3

Hello. I am the Sub 1!

Hello. I am the Sub 2!

Hello. I am the Sub 3!

$("#scroller a").click(function () {
    $('#boxMaster').animate({
        scrollTop: $(this.hash).offset().top
    }, 700);
    $("#scroller a").removeClass("active");
    $(this).addClass("active");
});

fiddle

$("#scroller a").click(function() {
  $('#boxMaster').animate({
    scrollTop: $(this.hash).offset().top
  }, 700);
  $("#scroller a").removeClass("active");
  $(this).addClass("active");
});

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#scroller {
  position: fixed;
  top: 0;
  height: 30px;
  text-align: center;
}
#scroller a {
  color: #fff;
  margin: 0 20px;
  text-decoration: none;
}
#scroller a.active {
  font-weight: bold;
  text-decoration: underline;
}
#boxTop {
  width: 100%;
  height: 100%;
  background: red;
}
#boxMaster {
  width: 100%;
  height: 100%;
  background: blue;
  overflow: hidden;
}
#boxMaster #subBox1,
#boxMaster #subBox2,
#boxMaster #subBox3 {
  width: 100%;
  height: 100%;
  display: table;
}
p {
  color: #fff;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}

 Scroll me to sub 1
  Scroll me to sub 2
  Scroll me to sub 3

Hello. I am the Sub 1!

Hello. I am the Sub 2!

Hello. I am the Sub 3!

Body:
I have a fixed header. I started with w3school's code. However, I've been struggling with this same problem for so long, finally found a workaround for the "first click incorrect" issue:

Just before (outside) of my click event, I simply created a variable "x", initialized:

var x=1;

Then I have a conditional statement inside the click event checking for x:

    if (x==1) {
        console.log("x is now: " + x);
        x=0;
        console.log("x is now: " + x);
        jQuery("html, body").animate({
            scrollTop: jQuery("div.class-of-element-i-am-scrolling-to" + hash).position().top - jQuery("div.header-container").outerHeight(true) - jQuery("h3.another-element-in-my-way").outerHeight(true)
            }, 2000, function(){
            return false;
        });
    } else {
        jQuery("html, body").animate({
            scrollTop: jQuery("div.class-of-element-i-am-scrolling-to" + hash).position().top
            }, 2000, function(){
            return false;
        });
    }

In other words, using "x" as a flag to check if it is the first time the code is run.

If it is, then I am kind of cheating by subtracting the fixed header and the other elements that are pulling my desired div up.  Remember to make "x=0" to "drop" the flag.

If it isn't, then it works fine anyway.


问:
AngularJs best way to repeat html code with the ability to hide it
new to AngularJs. In my html, I have two table rows that are repeated and populated over and over again. I need the second row to appear/disappear if I click a button on the first row. Here is some pseudo-ish, incomplete angular in what I'm aiming for

```<code><tr ng-repeat-start="item in collection" id="firstTr">
  <td>
    <button type="button" ng-click="toggleTheSecondTr">
        toggle visibility for second tr
    </button>
  <td>
  <td>
    {{item.value}}
  </td>
</tr>
<tr ng-Hide="the above button got clicked" id="secondTr" ng-repeat-end>
  <td>
     something goes here, there can be many td's
  </td>
  <td>
    {{item.someOtherValue}}
  </td>
</tr>
</code>```

This block of code is going to be repeated over and over again. But, I need to bind the button in a way that when the button is clicked, the second row is hidden, or if clicked again, it is shown again, almost like a toggle switch. I'm not sure how to do this. I could keep track of it with variables in the typescript code behind (we used typescript, not js) but I have no gaurantee on how many times these two rows will be repeated and therefore no idea how many variables to keep track of. Suggestions on how to solve my issue?

edit: I essentially want the functionality very similar to the table in this page for example, but my number of rows is variable, it can be one or many https://www.visualstudio.com/vs/compare/

答:
Here's the solution mate:

Use a boolean variable in each object of the collection to show or hide the second
 in its respective section:

angular.module('MyApp', [])
  .controller('MyController', ['$scope', function($scope){
    $scope.collection = [];
    $scope.collection.push({value:'Test', someOtherValue:'UAT', hideSecondRow: false});
    $scope.collection.push({value:'Dev', someOtherValue:'Development', hideSecondRow: true});
    $scope.collection.push({value:'Prod', someOtherValue:'PreProd', hideSecondRow: false});
    $scope.toggleTheSecondTr = function(index){
      $scope.collection[index].hideSecondRow = !$scope.collection[index].hideSecondRow;
    }
  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat-start="item in collection" id="firstTr">
        <td>
          <button type="button" ng-click="toggleTheSecondTr($index)">
              toggle visibility for second tr
          </button>
        <td>
        <td>
          {{item.value}}
        </td>
      </tr>
      <tr ng-hide="item.hideSecondRow" id="secondTr" ng-repeat-end>
        <td>
           something goes here, there can be many td's
        </td>
        <td>
          {{item.someOtherValue}}
        </td>
      </tr>
    </table>
  </div>
</div></code>```

Body:
new to AngularJs. In my html, I have two table rows that are repeated and populated over and over again. I need the second row to appear/disappear if I click a button on the first row. Here is some pseudo-ish, incomplete angular in what I'm aiming for

    <button type="button" ng-click="toggleTheSecondTr">
        toggle visibility for second tr
    </button>

    {{item.value}}

     something goes here, there can be many td's

    {{item.someOtherValue}}

This block of code is going to be repeated over and over again. But, I need to bind the button in a way that when the button is clicked, the second row is hidden, or if clicked again, it is shown again, almost like a toggle switch. I'm not sure how to do this. I could keep track of it with variables in the typescript code behind (we used typescript, not js) but I have no gaurantee on how many times these two rows will be repeated and therefore no idea how many variables to keep track of. Suggestions on how to solve my issue?

edit: I essentially want the functionality very similar to the table in this page for example, but my number of rows is variable, it can be one or many https://www.visualstudio.com/vs/compare/

Body:
Here's the solution mate:

Use a boolean variable in each object of the collection to show or hide the second <tr> in its respective section:

angular.module('MyApp', [])
  .controller('MyController', ['$scope', function($scope){
    $scope.collection = [];
    $scope.collection.push({value:'Test', someOtherValue:'UAT', hideSecondRow: false});
    $scope.collection.push({value:'Dev', someOtherValue:'Development', hideSecondRow: true});
    $scope.collection.push({value:'Prod', someOtherValue:'PreProd', hideSecondRow: false});
    $scope.toggleTheSecondTr = function(index){
      $scope.collection[index].hideSecondRow = !$scope.collection[index].hideSecondRow;
    }
  }]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyController">
    <table>
      <tr ng-repeat-start="item in collection" id="firstTr">
        <td>
          <button type="button" ng-click="toggleTheSecondTr($index)">
              toggle visibility for second tr
          </button>
        <td>
        <td>
          {{item.value}}
        </td>
      </tr>
      <tr ng-hide="item.hideSecondRow" id="secondTr" ng-repeat-end>
        <td>
           something goes here, there can be many td's
        </td>
        <td>
          {{item.someOtherValue}}
        </td>
      </tr>
    </table>
  </div>
</div>


问:
PHP - Pull data from JSON
I have a JSON file where I'm struggling getting the data out. Here is the JSON.

```<code>{"data":[
        {"tag":"operatingrevenue","value":215639000000.0},
        {"tag":"totalrevenue","value":215639000000.0},
        {"tag":"operatingcostofrevenue","value":131376000000.0},
        {"tag":"totalcostofrevenue","value":131376000000.0},
        {"tag":"totalgrossprofit","value":84263000000.0},
        {"tag":"sgaexpense","value":14194000000.0},
        {"tag":"rdexpense","value":10045000000.0},
        {"tag":"totaloperatingexpenses","value":24239000000.0},
        {"tag":"totaloperatingincome","value":60024000000.0},
        {"tag":"otherincome","value":1348000000.0},
        {"tag":"totalotherincome","value":1348000000.0},
        {"tag":"totalpretaxincome","value":61372000000.0},
        {"tag":"incometaxexpense","value":15685000000.0},
        {"tag":"netincomecontinuing","value":45687000000.0},
        {"tag":"netincome","value":45687000000.0},
        {"tag":"netincometocommon","value":45687000000.0},
        {"tag":"weightedavebasicsharesos","value":5470820000.0},
        {"tag":"basiceps","value":8.35},
        {"tag":"weightedavedilutedsharesos","value":5500281000.0},
        {"tag":"dilutedeps","value":8.31},
        {"tag":"weightedavebasicdilutedsharesos","value":5471500000.0},
        {"tag":"basicdilutedeps","value":8.35},
        {"tag":"cashdividendspershare","value":2.18}]
</code>```

I'm converting it to an array using

```<code>$data = json_decode($jsondata, true);
</code>```

I can then pull the data by:

```<code>$operatingRevenue = $data['data'][0]['value'];
$totalrevenue = $data['data'][1]['value'];
</code>```

etc, however, I want to use the tag name and not just the order just in case the order changes in the JSON. Something like

```<code>$operatingRevenue = $data['data']['operatingRevenue'];
</code>```

答:
Iterate the $data array, and set the key of a new element in the array to the tag element, and it's value to the value element.

```<code>foreach($data['data'] as $v)
    $array[$v['tag']] = $v['value'];
</code>```

$array contains what you want, access like this: $array['operatingRevenue']

Title: PHP - Pull data from JSON

Body:
I have a JSON file where I'm struggling getting the data out. Here is the JSON.

{"data":[
        {"tag":"operatingrevenue","value":215639000000.0},
        {"tag":"totalrevenue","value":215639000000.0},
        {"tag":"operatingcostofrevenue","value":131376000000.0},
        {"tag":"totalcostofrevenue","value":131376000000.0},
        {"tag":"totalgrossprofit","value":84263000000.0},
        {"tag":"sgaexpense","value":14194000000.0},
        {"tag":"rdexpense","value":10045000000.0},
        {"tag":"totaloperatingexpenses","value":24239000000.0},
        {"tag":"totaloperatingincome","value":60024000000.0},
        {"tag":"otherincome","value":1348000000.0},
        {"tag":"totalotherincome","value":1348000000.0},
        {"tag":"totalpretaxincome","value":61372000000.0},
        {"tag":"incometaxexpense","value":15685000000.0},
        {"tag":"netincomecontinuing","value":45687000000.0},
        {"tag":"netincome","value":45687000000.0},
        {"tag":"netincometocommon","value":45687000000.0},
        {"tag":"weightedavebasicsharesos","value":5470820000.0},
        {"tag":"basiceps","value":8.35},
        {"tag":"weightedavedilutedsharesos","value":5500281000.0},
        {"tag":"dilutedeps","value":8.31},
        {"tag":"weightedavebasicdilutedsharesos","value":5471500000.0},
        {"tag":"basicdilutedeps","value":8.35},
        {"tag":"cashdividendspershare","value":2.18}]

I'm converting it to an array using

$data = json_decode($jsondata, true);

I can then pull the data by:

$operatingRevenue = $data['data'][0]['value'];
$totalrevenue = $data['data'][1]['value'];

etc, however, I want to use the tag name and not just the order just in case the order changes in the JSON. Something like

$operatingRevenue = $data['data']['operatingRevenue'];

Body:
Iterate the $data array, and set the key of a new element in the array to the tag element, and it's value to the value element.

foreach($data['data'] as $v)
    $array[$v['tag']] = $v['value'];

$array contains what you want, access like this: $array['operatingRevenue']