问:
Trouble choosing names from dropdown options
I've written some code in python in combination with selenium to select few options from three different dropdown boxes to reach the destination page. First off the browser is needed to click on a link in the first page to reach the page where dropdown item options are located. My script can click on the first page link but when it comes to choose the item from dropdown options then it fails to do that.

Site address URL

The link titled Search by Selecting a Plan or Network available in the first page (when clicked) leads to the second page where dropdown options can be found.

Options I wanna choose from three different dropdowns (from second page):

Medical

Arizona

All plans/networks

Here is what I've tried so far:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get("use_above_link")
wait.until(EC.presence_of_element_located((By.ID, "lnkGuestPlanSearch"))).click()

Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanC')).select_by_visible_text('Medical')
Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlState')).select_by_visible_text('Arizona')
Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanN')).select_by_visible_text('All plans/networks')

driver.quit()
</code>```

Elements within which dropdown options are embedded:

```<code></select><div class="chosen-container chosen-container-single pf-field-320-30" style="width: 0px;" title="" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanC_chosen"><a class="chosen-single"><span tabindex="0">Enter or select type of care</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanC_chosen_input" type="text" autocomplete="off" title="auto"></div><ul class="chosen-results"></ul></div></div>
    </div>

    <div id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_divMedicalCareText" style="display:none">
       <table class="AlertBox" style="width:320px"><tbody><tr>
         <td class="AlertIcon"> <img alt="Find more information about Behavioural Health Providers" src="https://www.providerfinder.anthem.com/images/ProviderFinder/SearchResults/15_Info.png"></td>
         <td class="AlertBoxText" style="width:298px">Providers for Behavioral Health & Substance Use Disorder Services are listed under Medical Care.</td></tr>
      </tbody></table>
    </div>

    <div id="divState" class="paddingtop35 paddingbottom20" style="display: block;">
    <div class="headerstyle-item">
        <label for="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState_chosen_input" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_Label1">What state do you want to search in?</label>
    </div>
    <select name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlState" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState" tabindex="0" class="pf-field" aria-labelledby="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelectPlanUnkwn_Label1" disabled="" style="display: none;">
    <option value="Enter or select a state">Enter or select a state</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
</select>

<div class="chosen-container chosen-container-single pf-field-320-30 chosen-disabled" style="width: 0px;" title="" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState_chosen"><a class="chosen-single"><span tabindex="0">Enter or select a state</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState_chosen_input" type="text" autocomplete="off" title="auto" disabled=""></div><ul class="chosen-results"></ul></div></div>
    </div>

    <div class="headerstyle-item paddingtop35" id="divPlanName">
            <label for="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN_chosen_input" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_Label6">Select a plan/network</label>
    </div>
    <div id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_divPlanFocus" class="paddingbottom20">
        <select name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanN" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN" class="pf-field" aria-labelledby="ctl00_MainContent_maincontent_pfPlanSelection_Label2" disabled="" style="display: none;"><option value="">Select a plan/network</option></select><div class="chosen-container chosen-container-single pf-field-320-30 chosen-disabled" style="width: 0px;" title="" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN_chosen"><a class="chosen-single"><span tabindex="0">Select a plan/network</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN_chosen_input" type="text" autocomplete="off" title="auto" disabled=""></div><ul class="chosen-results"></ul></div></div>
    </div>

    <div class="paddingtop50 paddingbottom50">
        <span>
            <input type="submit" name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$btnPlanCancel" value="Cancel" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_btnPlanCancel" class="secondaryButton buttonwidth150">
        </span>
          <span>
           <input type="submit" name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$btnPlanContinue" value="Continue" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_btnPlanContinue" class="primaryButton buttonwidth150">
        </span>
    </div>
</div>
</code>```

Btw, when clicking on the first page link, it is necessary to wait few seconds so that the first page can load it's content.

答:
It seem that you're trying to handle wrong elements. Those select nodes are not what you actually need. You can do, for example,

```<code>type_of_care = driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanC')
driver.execute_script('arguments[0].style.display="block";', type_of_care)
</code>```

to see that it's totally different drop-down

Try below solution

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get("https://www.anthem.com/health-insurance/provider-directory/searchcriteria")
wait.until(EC.presence_of_element_located((By.ID, "lnkGuestPlanSearch"))).click()

type_of_care = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Enter or select type of care')))
type_of_care.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="Medical"]'))).click()

state = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Enter or select a state')))
state.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="Arizona"]'))).click()

network_plan = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Select a plan/network')))
network_plan.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="All plans/networks"]'))).click()
</code>```

Body:
I've written some code in python in combination with selenium to select few options from three different dropdown boxes to reach the destination page. First off the browser is needed to click on a link in the first page to reach the page where dropdown item options are located. My script can click on the first page link but when it comes to choose the item from dropdown options then it fails to do that.

Site address URL

The link titled Search by Selecting a Plan or Network available in the first page (when clicked) leads to the second page where dropdown options can be found.

Options I wanna choose from three different dropdowns (from second page):

Medical

Arizona

All plans/networks

Here is what I've tried so far:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get("use_above_link")
wait.until(EC.presence_of_element_located((By.ID, "lnkGuestPlanSearch"))).click()

Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanC')).select_by_visible_text('Medical')
Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlState')).select_by_visible_text('Arizona')
Select(driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanN')).select_by_visible_text('All plans/networks')

driver.quit()

Elements within which dropdown options are embedded:

</select>
Enter or select type of care

<input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanC_chosen_input" type="text" autocomplete="off" title="auto">

         Providers for Behavioral Health & Substance Use Disorder Services are listed under Medical Care.

        What state do you want to search in?

    <select name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlState" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState" tabindex="0" class="pf-field" aria-labelledby="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelectPlanUnkwn_Label1" disabled="" style="display: none;">
    <option value="Enter or select a state">Enter or select a state</option>
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
</select>

Enter or select a state

<input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlState_chosen_input" type="text" autocomplete="off" title="auto" disabled="">

            Select a plan/network

        <select name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanN" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN" class="pf-field" aria-labelledby="ctl00_MainContent_maincontent_pfPlanSelection_Label2" disabled="" style="display: none;"><option value="">Select a plan/network</option></select>
Select a plan/network

<input id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_ddlPlanN_chosen_input" type="text" autocomplete="off" title="auto" disabled="">

            <input type="submit" name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$btnPlanCancel" value="Cancel" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_btnPlanCancel" class="secondaryButton buttonwidth150">

           <input type="submit" name="ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$btnPlanContinue" value="Continue" id="ctl00_MainContent_maincontent_pfSearchMain_pfSelfPlanSelection_btnPlanContinue" class="primaryButton buttonwidth150">

Btw, when clicking on the first page link, it is necessary to wait few seconds so that the first page can load it's content.

Body:
It seem that you're trying to handle wrong elements. Those select nodes are not what you actually need. You can do, for example,

type_of_care = driver.find_element_by_name('ctl00$MainContent$maincontent$pfSearchMain$pfSelfPlanSelection$ddlPlanC')
driver.execute_script('arguments[0].style.display="block";', type_of_care)

to see that it's totally different drop-down

Try below solution

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get("https://www.anthem.com/health-insurance/provider-directory/searchcriteria")
wait.until(EC.presence_of_element_located((By.ID, "lnkGuestPlanSearch"))).click()

type_of_care = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Enter or select type of care')))
type_of_care.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="Medical"]'))).click()

state = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Enter or select a state')))
state.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="Arizona"]'))).click()

network_plan = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Select a plan/network')))
network_plan.click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//li[.="All plans/networks"]'))).click()


来源: stackexchange

问:
NSUserDefaults synchronize-method
```<code> NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"xxxxxxxx" forKey:@"name"];

[defaults synchronize];
</code>```

I need to know why do i have to use the last line of the above code [defaults synchronize] ? What is the purpose of using it? Is it a must ?

答:
You don't have to write that line anymore.

The method reference from the updated documentation

Waits for any pending asynchronous updates to the defaults database
  and returns; this method is unnecessary and shouldn't be used.

Comments to the method explaining what to do.

```<code>     /*!
     -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.

     -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
     - ...before reading in order to fetch updated values: remove the synchronize call
     - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
     - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
     - ...for any other reason: remove the synchronize call
      */
     open func synchronize() -> Bool
</code>```

ContentLicense: CC BY-SA 3.0

Title: NSUserDefaults synchronize-method

Body:
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"xxxxxxxx" forKey:@"name"];

[defaults synchronize];

I need to know why do i have to use the last line of the above code [defaults synchronize] ? What is the purpose of using it? Is it a must ?

Body:
You don't have to write that line anymore.

The method reference from the updated documentation

Waits for any pending asynchronous updates to the defaults database
  and returns; this method is unnecessary and shouldn't be used.

Comments to the method explaining what to do.

     /*!
     -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.

     -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
     - ...before reading in order to fetch updated values: remove the synchronize call
     - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
     - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
     - ...for any other reason: remove the synchronize call
      */
     open func synchronize() -> Bool


问:
React native Stack navigator Back Handler
React native Stack Navigator goes to the home page the default route (initialroutename) from every page of the app I want to go to previous pages from few pages and disable going to the back page from few pages. Back Handler is not even helping in this case. How can I achieve this

```<code>     class AppNavigator extends Component {

      constructor(props) {
        super(props)
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
    }

    componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
    }

    handleBackButtonClick() {
        this.props.navigation.goBack();
        return true;
    }

      render() {
        return;
      }
    }

    export default AppNavigator;
</code>```

Code for Drawer Navigator. All routes are also defined here.

```<code>        import React from "react";
    import { DrawerNavigator } from "react-navigation";

    import Home from "./components/home/";
    import SideBar from "./components/sidebar";
    import Dashboard from "./components/Dashboard/";
    import Profile from "./components/Profile"
    import Contact from "./components/Contact"
    import Terms from "./components/terms"
    import Links from "./components/Links"
    import Register from "./components/Register"
    import Discover from "./components/Discover/";

    const Drawer = DrawerNavigator(
      {
        Home: { screen: Home },
        Dashboard: { screen: Dashboard },
        Discover: { screen: Discover }
        Profile : {screen: Profile},
        Contact: { screen: Contact},
        Terms: { screen: Terms},
        Links: { screen: Links},
        Register: { screen: Register,
          navigationOptions: {
            title: "FirstPage",
            header: {
              left: null,
            }
          }, },

      },
      {
        initialRouteName: "Home",
        contentOptions: {
          activeTintColor: "#e91e63"
        },
        drawerPosition: 'right',
        contentComponent: props => <SideBar {...props} />
      }
    );

    export default Drawer;
</code>```

答: Why are you handling a back event?  instead, use navigation reset property that will reset your route to 0 and user will never go back because stake is empty

Body:
React native Stack Navigator goes to the home page the default route (initialroutename) from every page of the app I want to go to previous pages from few pages and disable going to the back page from few pages. Back Handler is not even helping in this case. How can I achieve this

     class AppNavigator extends Component {

      constructor(props) {
        super(props)
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
    }

    componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
    }

    handleBackButtonClick() {
        this.props.navigation.goBack();
        return true;
    }

      render() {
        return;
      }
    }

    export default AppNavigator;

Code for Drawer Navigator. All routes are also defined here.

        import React from "react";
    import { DrawerNavigator } from "react-navigation";

    import Home from "./components/home/";
    import SideBar from "./components/sidebar";
    import Dashboard from "./components/Dashboard/";
    import Profile from "./components/Profile"
    import Contact from "./components/Contact"
    import Terms from "./components/terms"
    import Links from "./components/Links"
    import Register from "./components/Register"
    import Discover from "./components/Discover/";

    const Drawer = DrawerNavigator(
      {
        Home: { screen: Home },
        Dashboard: { screen: Dashboard },
        Discover: { screen: Discover }
        Profile : {screen: Profile},
        Contact: { screen: Contact},
        Terms: { screen: Terms},
        Links: { screen: Links},
        Register: { screen: Register,
          navigationOptions: {
            title: "FirstPage",
            header: {
              left: null,
            }
          }, },

      },
      {
        initialRouteName: "Home",
        contentOptions: {
          activeTintColor: "#e91e63"
        },
        drawerPosition: 'right',
        contentComponent: props => <SideBar {...props} />
      }
    );

    export default Drawer;


问:
Developing for iphone under unix
My question is very simple:

Is there any solution to install xCode, or equivalent, under unix OS, like ubuntu ?

Indeed, i don't want to buy an expensive macbook to develop my private iPhone applications.

答:
Martin,

I am doing some apps development for an iPhone and I have a Windows 7.  You can install VMWare and install the Mac OS 10.6 through this and load xCode from Mac.  The key is in finding the correct place to download VMWare and Mac OS.

Good Luck.

Title: Developing for iphone under unix

ContentLicense: CC BY-SA 2.5


问:
WCF Client Certificate Validation + Windows Authentication
I've successfully created a WCF service which validates the incoming client certificate against the chain configured in IIS. However, as this is only a security mechanism to support authentication, I also need the Windows user calling my WCF service to handle authorization.

Normally when extracting the Windows User, you would do it like this

```<code>ServiceSecurityContext.Current.WindowsIdentity.Name
</code>```

When my service is configured with security mode TransportWithMessageCredentials, the PrimaryIdentity in the ServiceSecurityContext will return the certificate's SubjectName and the WindowsIdentity will be empty.

To look at the client configuration, I've specified the WsHttpBinding like this

```<code>private static Binding GetHttpsBinding()
{
    var binding = new WSHttpBinding();
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;

    return binding;
}
</code>```

The client certificate is added like to the proxy client like this:

```<code>private static void ApplyClientCertificate(HelloServiceClient client)
{
    client.ClientCredentials.ClientCertificate.SetCertificate(

        storeLocation: StoreLocation.CurrentUser,
        storeName: StoreName.My,
        findType: X509FindType.FindBySubjectName,
        findValue: "ClientCertificatesTest"

   );
}
</code>```

Switching the two ClientCredentialType values so the binding looks like this

```<code>private static Binding GetHttpsBinding()
{
    var binding = new WSHttpBinding();
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;

    return binding;
}
</code>```

will work for extracting the Windows Credentials as described above, but when presenting an invalid certificate or no certificate at all are also accepted! Therefore the authentication requirement is not fulfilled. I can also add that when configured this way my implementation of X509CertificateValidator on the server-side will not trigger, hence my suspicion that the client certificate is not added.

Surely there must be some way to add a client certificate for authentication and add Windows Credentials to handle authorization in WCF? Is there any other way that I can add the certificate than adding it to the client credentials?

Thanks in advance!

答: So the answer to this question will be to create your own CustomBinding to get both Windows Credentails and Certificate validation.

Body:
I've successfully created a WCF service which validates the incoming client certificate against the chain configured in IIS. However, as this is only a security mechanism to support authentication, I also need the Windows user calling my WCF service to handle authorization.

Normally when extracting the Windows User, you would do it like this

ServiceSecurityContext.Current.WindowsIdentity.Name

When my service is configured with security mode TransportWithMessageCredentials, the PrimaryIdentity in the ServiceSecurityContext will return the certificate's SubjectName and the WindowsIdentity will be empty.

To look at the client configuration, I've specified the WsHttpBinding like this

private static Binding GetHttpsBinding()
{
    var binding = new WSHttpBinding();
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;

    return binding;
}

The client certificate is added like to the proxy client like this:

private static void ApplyClientCertificate(HelloServiceClient client)
{
    client.ClientCredentials.ClientCertificate.SetCertificate(

        storeLocation: StoreLocation.CurrentUser,
        storeName: StoreName.My,
        findType: X509FindType.FindBySubjectName,
        findValue: "ClientCertificatesTest"

   );
}

Switching the two ClientCredentialType values so the binding looks like this

private static Binding GetHttpsBinding()
{
    var binding = new WSHttpBinding();
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;

    return binding;
}

will work for extracting the Windows Credentials as described above, but when presenting an invalid certificate or no certificate at all are also accepted! Therefore the authentication requirement is not fulfilled. I can also add that when configured this way my implementation of X509CertificateValidator on the server-side will not trigger, hence my suspicion that the client certificate is not added.

Surely there must be some way to add a client certificate for authentication and add Windows Credentials to handle authorization in WCF? Is there any other way that I can add the certificate than adding it to the client credentials?

Thanks in advance!


问:
Destroy the session file in Laravel
As we all know, we can use the function session_destory() to delete the session file in PHP.But I do not know how to delete session file in Laravel due to the reason that the author rewrites the session module. Expecting your answers. </p>

答:
A handy route I use while in development only:

```<code>Route::get('/flush', function () {
    Session::flush();
    return redirect('/login');
})->name('flush');
</code>```

Title: Destroy the session file in Laravel

Body:
A handy route I use while in development only:

Route::get('/flush', function () {
    Session::flush();
    return redirect('/login');
})->name('flush');


问:
AWS Elastic Beanstalk environment variables in ASP.NET Core 1.0
How do I get environment variables from elastic beanstalk into an asp.net core mvc application? I have added a .ebextensions folder with app.config file in it with the following:

```<code>option_settings:
- option_name: HelloWorld
  value: placeholder

- option_name: ASPNETCORE_ENVIRONMENT
  value: placeholder
</code>```

The .ebextensions folder is included in the publish package.

On deployment, both the variables are visible in the aws elasticbeanstalk console at Configuration > Software Configuration > Environment Variables

However, when I try to read the variables in the application, none of the below options are working:

```<code>Environment.GetEnvironmentVariable("HelloWorld") // In controller
Configuration["HelloWorld"] // In startup.cs
</code>```

Any ideas on what I could be missing? Thanks.

答:
I just implemented a slightly other solution which injects the beanstalk environment variables to the program so that you may access them by Environment.GetEnvironmentVariable():

```<code>private static void SetEbConfig()
{
    var tempConfigBuilder = new ConfigurationBuilder();

    tempConfigBuilder.AddJsonFile(
        @"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration",
        optional: true,
        reloadOnChange: true
    );

    var configuration = tempConfigBuilder.Build();

    var ebEnv =
        configuration.GetSection("iis:env")
            .GetChildren()
            .Select(pair => pair.Value.Split(new[] { '=' }, 2))
            .ToDictionary(keypair => keypair[0], keypair => keypair[1]);

    foreach (var keyVal in ebEnv)
    {
        Environment.SetEnvironmentVariable(keyVal.Key, keyVal.Value);
    }
}
</code>```

Simply call SetEbConfig(); before building your webhost. With this solution, also AWS SDK does read it's settings like AWS_ACCESS_KEY_ID correctly.

Body:
How do I get environment variables from elastic beanstalk into an asp.net core mvc application? I have added a .ebextensions folder with app.config file in it with the following:

option_settings:
- option_name: HelloWorld
  value: placeholder

- option_name: ASPNETCORE_ENVIRONMENT
  value: placeholder

The .ebextensions folder is included in the publish package.

On deployment, both the variables are visible in the aws elasticbeanstalk console at Configuration > Software Configuration > Environment Variables

However, when I try to read the variables in the application, none of the below options are working:

Environment.GetEnvironmentVariable("HelloWorld") // In controller
Configuration["HelloWorld"] // In startup.cs

Any ideas on what I could be missing? Thanks.

Body:
I just implemented a slightly other solution which injects the beanstalk environment variables to the program so that you may access them by Environment.GetEnvironmentVariable():

private static void SetEbConfig()
{
    var tempConfigBuilder = new ConfigurationBuilder();

    tempConfigBuilder.AddJsonFile(
        @"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration",
        optional: true,
        reloadOnChange: true
    );

    var configuration = tempConfigBuilder.Build();

    var ebEnv =
        configuration.GetSection("iis:env")
            .GetChildren()
            .Select(pair => pair.Value.Split(new[] { '=' }, 2))
            .ToDictionary(keypair => keypair[0], keypair => keypair[1]);

    foreach (var keyVal in ebEnv)
    {
        Environment.SetEnvironmentVariable(keyVal.Key, keyVal.Value);
    }
}

Simply call SetEbConfig(); before building your webhost. With this solution, also AWS SDK does read it's settings like AWS_ACCESS_KEY_ID correctly.


问:
Error com.android.dx.command.Main in Android Studio 2.3
I have error when building project. Anybody have this error before. I updated to Android Studion2.3 and build normally, but now I don't know why having this error. Clean, Rebuild but still have this error.

My gradle

```<code> compileSdkVersion 25
    buildToolsVersion '25'
</code>```

Error:Execution failed for task
  ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException:
    com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException: Error while executing
    java process with main class com.android.dx.command.Main with
    arguments {--dex --force-jumbo --num-threads=4 --multi-dex --output
    D:\GIT
    TECHUB\pocca_android.git\app\build\intermediates\transforms\dex\debug\folders\1000\5\slice_2
    D:\GIT
    TECHUB\pocca_android.git\app\build\intermediates\transforms\instantRunSlicer\debug\folders\1\5\slice_2}

答: Try to disable instant run option, it's worked for me.</p>

Body:
I have error when building project. Anybody have this error before. I updated to Android Studion2.3 and build normally, but now I don't know why having this error. Clean, Rebuild but still have this error.

My gradle

 compileSdkVersion 25
    buildToolsVersion '25'

Error:Execution failed for task
  ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException:
    com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException: Error while executing
    java process with main class com.android.dx.command.Main with
    arguments {--dex --force-jumbo --num-threads=4 --multi-dex --output
    D:\GIT
    TECHUB\pocca_android.git\app\build\intermediates\transforms\dex\debug\folders\1000\5\slice_2
    D:\GIT
    TECHUB\pocca_android.git\app\build\intermediates\transforms\instantRunSlicer\debug\folders\1\5\slice_2}


答:
You have to use Session flush as shown below:

Session::flush(); // destroy all the session.

Title: Destroy the session file in Laravel

Body: As we all know, we can use the function session_destory() to delete the session file in PHP.But I do not know how to delete session file in Laravel due to the reason that the author rewrites the session module. Expecting your answers.


问:
Java generic array from null generic type
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

```<code>/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}
</code>```

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

```<code>String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException
</code>```

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks

答:
Maybe this is useful.</p>

```<code>public static <T> T[] create(Class<T> clazz, int length)
{
   T[] result = (T[]) Array.newInstance(clazz, length);
   return result;
}
</code>```

Body:
Consider the Array.newInstance static method as a way of creating a generic type array in Java.
What I'm failing to see how to do is create a generic array from a null generic type argument:

/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
   T[] result = (T[]) Array.newInstance(item.getClass(), length);

   for(int i = 0; i < length; i++)
      result[i] = item;

   return result;
}

The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array.
But how could I make a null string argument return a String array of length 10 and null in all positions?

e.g.

String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException

Is there perhaps a  way to get the class of "item" without using one of its members (as it's null)?

I know I can just new up an array String[] array = new String[10], but that's not the point.

Thanks

Body:
Maybe this is useful.

public static <T> T[] create(Class<T> clazz, int length)
{
   T[] result = (T[]) Array.newInstance(clazz, length);
   return result;
}


问:
Create Personal VPN connection using NEVPNManager
I am trying to create VPN connection in my app. I go through this link
https://developer.apple.com/documentation/networkextension/nevpnmanager
but did not find any official code to use NEVPNManager and even not found any tutorial to use this NEVPNManager.

I am new to VPN concept and don't know that much about it. so Can anyone give some solutions?

答:
This tutorial help me to create VPN connection.

http://blog.moatazthenervous.com/create-a-vpn-connection-with-apple-swift/

VPN file for connection and disconnection

```<code>import Foundation
import NetworkExtension

  // MARK: - NEVPNManager
    // MARK: -

    private var vpnLoadHandler: (Error?) -> Void { return
    { (error:Error?) in
        if ((error) != nil) {
            print("Could not load VPN Configurations")
            self.removeToast()
            return;
        }

        self.showToast(msg: STRINGVALUES.kCreatingConnection)

        //VPN connection via Username password
        let p = NEVPNProtocolIPSec()
        let kcs = KeychainService()
        p.authenticationMethod = NEVPNIKEAuthenticationMethod.sharedSecret

        //For the security purpose added word xyz in password .so it should be remove while connecting

        if self.selectedSever != nil{
            self.selectedSever?.password = (self.selectedSever?.password.replacingOccurrences(of: "xyz", with: ""))!
            p.username = self.selectedSever?.userName
            p.serverAddress = self.selectedSever?.serverAddress
            kcs.save(key: "SHARED", value: (self.selectedSever?.password)!)

            kcs.save(key: "VPN_PASSWORD", value: (self.selectedSever?.password)!)
            p.sharedSecretReference = kcs.load(key: STRINGVALUES.kShared)
            p.passwordReference = kcs.load(key: STRINGVALUES.kVPN_Pswd)
            p.useExtendedAuthentication = true
            p.disconnectOnSleep = false

            // Check for free subscriber
            if self.selectedSever?.serverType == STRINGVALUES.VIP.lowercased() && !Singleton.checkForPaidReciept(){

                self.disconnectVPN()
                Helper.showAlert(sender: self, title: STRINGVALUES.AppName, message: AlertMessage.kValidateSubscription)
                return

            }

            self.vpnManager.protocolConfiguration = p
            self.vpnManager.localizedDescription = STRINGVALUES.AppName
            self.vpnManager.isEnabled = true

            self.vpnManager.saveToPreferences(completionHandler: self.vpnSaveHandler)
        }else{

        }

        }

    }

    private var vpnSaveHandler: (Error?) -> Void { return
    { (error:Error?) in
        if (error != nil) {
            print("Could not save VPN Configurations")
            self.removeToast()
            return
        } else {
            do {
                try self.vpnManager.connection.startVPNTunnel()
            } catch let error {
                print("Error starting VPN Connection \(error.localizedDescription)");
                self.removeToast()
            }
        }
        }
        //self.vpnlock = false
    }

    public func connectVPN() {
        //For no known reason the process of saving/loading the VPN configurations fails.On the 2nd time it works
        do {
            try self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)

        } catch let error {
            print("Could not start VPN Connection: \(error.localizedDescription)" )
            self.removeToast()
        }
    }

    public func disconnectVPN() ->Void {
        vpnManager.connection.stopVPNTunnel()

    }

    func vpnConnectionStatusChanged(){

       let status = self.vpnManager.connection.status
        print("VPN connection status = \(status)")

        switch status {
        case NEVPNStatus.connected:

            showToast(msg: STRINGVALUES.kConnected)

        case NEVPNStatus.invalid, NEVPNStatus.disconnected :

            showToast(msg: STRINGVALUES.kDisconnected)

        case NEVPNStatus.connecting , NEVPNStatus.reasserting:

            showToast(msg: STRINGVALUES.kConnecting)

        case NEVPNStatus.disconnecting:
            showToast(msg: STRINGVALUES.kDisconnecting)

        default:
            print("Unknown VPN connection status")
        }

    }

</code>```

Body:
This tutorial help me to create VPN connection.

http://blog.moatazthenervous.com/create-a-vpn-connection-with-apple-swift/

VPN file for connection and disconnection

import Foundation
import NetworkExtension

  // MARK: - NEVPNManager
    // MARK: -

    private var vpnLoadHandler: (Error?) -> Void { return
    { (error:Error?) in
        if ((error) != nil) {
            print("Could not load VPN Configurations")
            self.removeToast()
            return;
        }

        self.showToast(msg: STRINGVALUES.kCreatingConnection)

        //VPN connection via Username password
        let p = NEVPNProtocolIPSec()
        let kcs = KeychainService()
        p.authenticationMethod = NEVPNIKEAuthenticationMethod.sharedSecret

        //For the security purpose added word xyz in password .so it should be remove while connecting

        if self.selectedSever != nil{
            self.selectedSever?.password = (self.selectedSever?.password.replacingOccurrences(of: "xyz", with: ""))!
            p.username = self.selectedSever?.userName
            p.serverAddress = self.selectedSever?.serverAddress
            kcs.save(key: "SHARED", value: (self.selectedSever?.password)!)

            kcs.save(key: "VPN_PASSWORD", value: (self.selectedSever?.password)!)
            p.sharedSecretReference = kcs.load(key: STRINGVALUES.kShared)
            p.passwordReference = kcs.load(key: STRINGVALUES.kVPN_Pswd)
            p.useExtendedAuthentication = true
            p.disconnectOnSleep = false

            // Check for free subscriber
            if self.selectedSever?.serverType == STRINGVALUES.VIP.lowercased() && !Singleton.checkForPaidReciept(){

                self.disconnectVPN()
                Helper.showAlert(sender: self, title: STRINGVALUES.AppName, message: AlertMessage.kValidateSubscription)
                return

            }

            self.vpnManager.protocolConfiguration = p
            self.vpnManager.localizedDescription = STRINGVALUES.AppName
            self.vpnManager.isEnabled = true

            self.vpnManager.saveToPreferences(completionHandler: self.vpnSaveHandler)
        }else{

        }

        }

    }

    private var vpnSaveHandler: (Error?) -> Void { return
    { (error:Error?) in
        if (error != nil) {
            print("Could not save VPN Configurations")
            self.removeToast()
            return
        } else {
            do {
                try self.vpnManager.connection.startVPNTunnel()
            } catch let error {
                print("Error starting VPN Connection \(error.localizedDescription)");
                self.removeToast()
            }
        }
        }
        //self.vpnlock = false
    }

    public func connectVPN() {
        //For no known reason the process of saving/loading the VPN configurations fails.On the 2nd time it works
        do {
            try self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)

        } catch let error {
            print("Could not start VPN Connection: \(error.localizedDescription)" )
            self.removeToast()
        }
    }

    public func disconnectVPN() ->Void {
        vpnManager.connection.stopVPNTunnel()

    }

    func vpnConnectionStatusChanged(){

       let status = self.vpnManager.connection.status
        print("VPN connection status = \(status)")

        switch status {
        case NEVPNStatus.connected:

            showToast(msg: STRINGVALUES.kConnected)

        case NEVPNStatus.invalid, NEVPNStatus.disconnected :

            showToast(msg: STRINGVALUES.kDisconnected)

        case NEVPNStatus.connecting , NEVPNStatus.reasserting:

            showToast(msg: STRINGVALUES.kConnecting)

        case NEVPNStatus.disconnecting:
            showToast(msg: STRINGVALUES.kDisconnecting)

        default:
            print("Unknown VPN connection status")
        }

    }

ContentLicense: CC BY-SA 4.0


问:
While trying to fill the null values in my dataframe df 's "item_weight" column accord. to "Item_Identifier " .error is coming
```<code>avg_weight = df.pivot_table(index = "Item_Identifier",values = "Item_Weight")
df_bool =df[df["Item_Weight"].isnull()]
df.loc[df_bool,'Item_Weight'] = df.loc[df_bool,'Item_Identifier'].apply(lambda x: avg_weight[x])
</code>```

答:
I would use fillna if I were you:</p>

```<code>df["Item_Weight"] = df["Item_Weight"].fillna(df["Item_Weight"].mean())
</code>```

Body:
I would use fillna if I were you:

df["Item_Weight"] = df["Item_Weight"].fillna(df["Item_Weight"].mean())


问:
Trigger input file click event in AngularJS
I am trying to emulate a click event on a file input in AngularJS. I have seen working jQuery examples, but I don't want to use jQuery.

'use strict';

angular.module('MyApp', []).

controller('MyCtrl', function($scope) {
  $scope.click = function() {
    setTimeout(function() {
      var element = angular.element(document.getElementById('input'));
      element.triggerHandler('click');
      $scope.clicked = true;
    }, 0);
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.angularjs.org/1.3.14/angular.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
  <input id="input" type="file"/>
  <button ng-click="click()">Click me!</button>
  <div ng-if="clicked">Clicked</div>
</div></code>```

Note: For some reason the button needs to be pressed twice in order to trigger the timeout function.

I am using setTimeout because of this post.

How do I programmatically click a file input with just AngularJS / vanilla JavaScript?

答:
Here's how to trigger file of type 'file' or open select-file window when click on icon, button or span as you like ;)

css :

```<code>.attachImageForCommentsIcon{
  padding-top: 14px;
  padding-right: 6px;
  outline:none;
  cursor:pointer;
}
</code>```

HTML :

```<code><input id="myInput" type="file" style="visibility:hidden" ng-file-model=""/>
<i onclick="$('#myInput').click();" class="attachImageForCommentsIcon blue-2 right-position material-icons">image</i>
</code>```

all credits goes for this answer :
https://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box

Thus, we customized file input tag using this way.

Body:
I am trying to emulate a click event on a file input in AngularJS. I have seen working jQuery examples, but I don't want to use jQuery.

'use strict';

angular.module('MyApp', []).

controller('MyCtrl', function($scope) {
  $scope.click = function() {
    setTimeout(function() {
      var element = angular.element(document.getElementById('input'));
      element.triggerHandler('click');
      $scope.clicked = true;
    }, 0);
  };
});

  <input id="input" type="file"/>
  <button ng-click="click()">Click me!</button>

Clicked

Note: For some reason the button needs to be pressed twice in order to trigger the timeout function.

I am using setTimeout because of this post.

How do I programmatically click a file input with just AngularJS / vanilla JavaScript?

Body:
Here's how to trigger file of type 'file' or open select-file window when click on icon, button or span as you like ;)

css :

.attachImageForCommentsIcon{
  padding-top: 14px;
  padding-right: 6px;
  outline:none;
  cursor:pointer;
}

HTML :

<input id="myInput" type="file" style="visibility:hidden" ng-file-model=""/>
<i onclick="$('#myInput').click();" class="attachImageForCommentsIcon blue-2 right-position material-icons">image</i>

all credits goes for this answer :
https://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box

Thus, we customized file input tag using this way.


问:
Taking screen shot of a SurfaceView in android
I am using following method to taking screen shot of a particular view which is a SurfaceView.

```<code>public void takeScreenShot(View surface_view){

    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = surface_view;
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, bos);
    byte[] imageData = bos.toByteArray();

}
</code>```

the problem is its giving me the whole activity screen image. But I need to take screen shot of the particular view. I tried other ways but those give me a black screen as screen shot, some posts says that it requires rooted device.
Can any one help me please. I'm in need of this solution. Help me....

答:
use this method its works fine for me actually surfaceview does not work with v1.setDrawingCacheEnabled(true);  i do this by using this code.</p>

```<code> jpegCallback = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {

            camera.startPreview();
            Bitmap cameraBitmap = BitmapFactory.decodeByteArray
                    (data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setTitle("Wait!");
            pd.setMessage("capturing image.........");
            pd.setIndeterminate(false);
            pd.show();

            progressStatus = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (progressStatus < 100) {
                        // Update the progress status
                        progressStatus += 1;

                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                // Update the progress status
                                pd.setProgress(progressStatus);
                                // If task execution completed
                                if (progressStatus == 100) {
                                    // Dismiss/hide the progress dialog
                                    pd.dismiss();
                                }
                            }
                        });
                    }
                }
            }).start();

            Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
            if (rotatedBitmap != null) {
                rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
                Random num = new Random();
                int nu = num.nextInt(1000);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] bitmapdata = bos.toByteArray();
                ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
                String picId = String.valueOf(nu);
                String myfile = "Ghost" + picId + ".jpeg";
                File dir_image = new File(Environment.getExternalStorageDirectory() +//<---
                        File.separator + "LiveCamera");          //<---
                dir_image.mkdirs();                                                  //<---

                try {
                    File tmpFile = new File(dir_image, myfile);
                    FileOutputStream fos = new FileOutputStream(tmpFile);

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = fis.read(buf)) > 0) {
                        fos.write(buf, 0, len);
                    }
                    fis.close();
                    fos.close();
                    Toast.makeText(getApplicationContext(),
                            " Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
                    camera.startPreview();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                MediaScannerConnection.scanFile(MainActivity.this,
                        new String[]{dir_image.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });

                safeToTakePicture = true;

            }

        }

    };
</code>```

Body:
I am using following method to taking screen shot of a particular view which is a SurfaceView.

public void takeScreenShot(View surface_view){

    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = surface_view;
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, bos);
    byte[] imageData = bos.toByteArray();

}

the problem is its giving me the whole activity screen image. But I need to take screen shot of the particular view. I tried other ways but those give me a black screen as screen shot, some posts says that it requires rooted device.
Can any one help me please. I'm in need of this solution. Help me....

Body:
use this method its works fine for me actually surfaceview does not work with v1.setDrawingCacheEnabled(true);  i do this by using this code.

 jpegCallback = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {

            camera.startPreview();
            Bitmap cameraBitmap = BitmapFactory.decodeByteArray
                    (data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            pd = new ProgressDialog(MainActivity.this);
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setTitle("Wait!");
            pd.setMessage("capturing image.........");
            pd.setIndeterminate(false);
            pd.show();

            progressStatus = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (progressStatus < 100) {
                        // Update the progress status
                        progressStatus += 1;

                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                // Update the progress status
                                pd.setProgress(progressStatus);
                                // If task execution completed
                                if (progressStatus == 100) {
                                    // Dismiss/hide the progress dialog
                                    pd.dismiss();
                                }
                            }
                        });
                    }
                }
            }).start();

            Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
            if (rotatedBitmap != null) {
                rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
                Random num = new Random();
                int nu = num.nextInt(1000);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] bitmapdata = bos.toByteArray();
                ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
                String picId = String.valueOf(nu);
                String myfile = "Ghost" + picId + ".jpeg";
                File dir_image = new File(Environment.getExternalStorageDirectory() +//<---
                        File.separator + "LiveCamera");          //<---
                dir_image.mkdirs();                                                  //<---

                try {
                    File tmpFile = new File(dir_image, myfile);
                    FileOutputStream fos = new FileOutputStream(tmpFile);

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = fis.read(buf)) > 0) {
                        fos.write(buf, 0, len);
                    }
                    fis.close();
                    fos.close();
                    Toast.makeText(getApplicationContext(),
                            " Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
                    camera.startPreview();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                MediaScannerConnection.scanFile(MainActivity.this,
                        new String[]{dir_image.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, Uri uri) {
                            }
                        });

                safeToTakePicture = true;

            }

        }

    };


问:
Recursive function to add all the digits

I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

```<code>def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10
</code>```

答:
You can use your approach with minor modifications:

```<code>def digit_sum(n):
    if n<10:
         return n
    return (digit_sum(n//10) + n%10 - 1) % 9 + 1
</code>```

Or ignoring the recursion requirement:

```<code>def digit_sum(n):
    return n if n<10 else (n-1) % 9 + 1
</code>```

Or even shorter (thanks @thanasisp):

```<code>def digit_sum(n):
    return n and n%9 or 9
</code>```

Body:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Body:
You can use your approach with minor modifications:

def digit_sum(n):
    if n<10:
         return n
    return (digit_sum(n//10) + n%10 - 1) % 9 + 1

Or ignoring the recursion requirement:

def digit_sum(n):
    return n if n<10 else (n-1) % 9 + 1

Or even shorter (thanks @thanasisp):

def digit_sum(n):
    return n and n%9 or 9


问:
Multiple if statements, it deletes what is already in cells when if is not fulfilled
I am trying to get Excel to copy some values if the active sheet is a specific sheet. The problem I am having is that if the values from one sheet is transferred to the sheet it needs to be on, it overwrites the cells mentioned in the other if statements, but I need those values not to be overwritten. Can anybody help me solve this problem?</p>

```<code>If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("INTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for renovation") Then
    Sheets("EXTERNAL").Cells(29, 4) = Sheets("Parts for renovation").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("EXTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("EXTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 2 - n, 17)
    Else
End If
</code>```

答:
You can try the below:

```<code>Sub MySub()

Select Case ActiveSheet.Name

    Case "Parts for site"
        Sheets("INTERNAL").Cells(35, 4) = Sheets("INTERNAL").Cells(35, 4) & "||" & Sheets("Parts for site").Cells(i + 3 - n, 17)

    Case "Parts for options":
        Sheets("INTERNAL").Cells(52, 4) =  Sheets("INTERNAL").Cells(52, 4) & "||" & Sheets("Parts for options").Cells(i + 3 - n, 17)

    Case "Parts for renovation"
        Sheets("EXTERNAL").Cells(29, 4) = Sheets("EXTERNAL").Cells(29, 4) & "||" & Sheets("Parts for renovation").Cells(i + 2 - n, 17)

    Case "Parts for site"
        Sheets("EXTERNAL").Cells(35, 4) = Sheets("EXTERNAL").Cells(35, 4) &"||" & Sheets("Parts for site").Cells(i + 2 - n, 17)

    Case "Parts for options"
        Sheets("EXTERNAL").Cells(52, 4) = Sheets("EXTERNAL").Cells(52, 4) & "||" & Sheets("Parts for options").Cells(i + 2 - n, 17)

End If

End Sub
</code>```

Is This you want, this will not clear the original values but will also have the old values too.

Body:
I am trying to get Excel to copy some values if the active sheet is a specific sheet. The problem I am having is that if the values from one sheet is transferred to the sheet it needs to be on, it overwrites the cells mentioned in the other if statements, but I need those values not to be overwritten. Can anybody help me solve this problem?

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("INTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("INTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 3 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for renovation") Then
    Sheets("EXTERNAL").Cells(29, 4) = Sheets("Parts for renovation").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for site") Then
    Sheets("EXTERNAL").Cells(35, 4) = Sheets("Parts for site").Cells(i + 2 - n, 17)
    Else
End If

If ActiveSheet = Sheets("Parts for options") Then
    Sheets("EXTERNAL").Cells(52, 4) = Sheets("Parts for options").Cells(i + 2 - n, 17)
    Else
End If

Body:
You can try the below:

Sub MySub()

Select Case ActiveSheet.Name

    Case "Parts for site"
        Sheets("INTERNAL").Cells(35, 4) = Sheets("INTERNAL").Cells(35, 4) & "||" & Sheets("Parts for site").Cells(i + 3 - n, 17)

    Case "Parts for options":
        Sheets("INTERNAL").Cells(52, 4) =  Sheets("INTERNAL").Cells(52, 4) & "||" & Sheets("Parts for options").Cells(i + 3 - n, 17)

    Case "Parts for renovation"
        Sheets("EXTERNAL").Cells(29, 4) = Sheets("EXTERNAL").Cells(29, 4) & "||" & Sheets("Parts for renovation").Cells(i + 2 - n, 17)

    Case "Parts for site"
        Sheets("EXTERNAL").Cells(35, 4) = Sheets("EXTERNAL").Cells(35, 4) &"||" & Sheets("Parts for site").Cells(i + 2 - n, 17)

    Case "Parts for options"
        Sheets("EXTERNAL").Cells(52, 4) = Sheets("EXTERNAL").Cells(52, 4) & "||" & Sheets("Parts for options").Cells(i + 2 - n, 17)

End If

End Sub

Is This you want, this will not clear the original values but will also have the old values too.


问:
How to read a text file in python using open method
I have a text file mycontacts.txt

I need to read content of this file.
Location path is: C:\Users\myusername\Documents\SQL_NeedToKnow\Python
I am using example from here: https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
def get_contacts(filename):
    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

So for my case, seems like I need to change the directory first.
For that I am using os.chdir method.
Not sure where should I place it exactly, but I dont even have an error.
I am using Jupyter.
I am trying to do this:

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open("mycontacts.txt", mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

I also tried usin Open with full path:

```<code># Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
#os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''', mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails
</code>```

答:
In the function, you are trying to open the actual file and you are not using the function parameter.

Rewriting the function:

```<code>def get_contacts(filename):
    names = []
    emails = []

    with open(filename) as contacts_file:
        for a_contact in contacts_file.readlines():
            name, email = a_contact.strip().split(', ')
            names.append(name)
            emails.append(email)

    return names, emails

# When you call the function, pass the file path as an argument
print(get_contacts('test.txt'))

(['Abc', 'Xyz'], ['abc@email.com', 'xyz@email.com'])
>>>
</code>```

Body:
I have a text file mycontacts.txt

I need to read content of this file.
Location path is: C:\Users\myusername\Documents\SQL_NeedToKnow\Python
I am using example from here: https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
def get_contacts(filename):
    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

So for my case, seems like I need to change the directory first.
For that I am using os.chdir method.
Not sure where should I place it exactly, but I dont even have an error.
I am using Jupyter.
I am trying to do this:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open("mycontacts.txt", mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

I also tried usin Open with full path:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
#os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''', mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

Body:
In the function, you are trying to open the actual file and you are not using the function parameter.

Rewriting the function:

def get_contacts(filename):
    names = []
    emails = []

    with open(filename) as contacts_file:
        for a_contact in contacts_file.readlines():
            name, email = a_contact.strip().split(', ')
            names.append(name)
            emails.append(email)

    return names, emails

# When you call the function, pass the file path as an argument
print(get_contacts('test.txt'))

(['Abc', 'Xyz'], ['abc@email.com', 'xyz@email.com'])
>>>


问:
How to properly overload the << operator for an ostream?
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

```<code>namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}
</code>```

And the "implementation":

```<code>using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}
</code>```

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

答:
To add to Mehrdad answer ,

```<code>namespace Math
{
    class Matrix
    {
       public:

       [...]

    }
    std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}
</code>```

In your implementation

```<code>std::ostream& operator<<(std::ostream& stream,
                     const Math::Matrix& matrix) {
    matrix.print(stream); //assuming you define print for matrix
    return stream;
 }
</code>```

OwnerDisplayName: Matthias van der Vlies

Body:
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

LastEditorDisplayName: Mehrdad Afshari

Body:
To add to Mehrdad answer ,

namespace Math
{
    class Matrix
    {
       public:

       [...]

    }
    std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}

In your implementation

std::ostream& operator<<(std::ostream& stream,
                     const Math::Matrix& matrix) {
    matrix.print(stream); //assuming you define print for matrix
    return stream;
 }


问:
How can I disable a jquery include for low bandwidth connections
I have a simple website which makes a little use of jquery but it is not essential so I would like to skip the jquery download if the users connection is slow.

Ideally I would detect a slow connection but I suppose detecting a mobile phone might be a reasonable proxy for this.

If this is possible I would then remove the parts of the page which use jquery and add them dynamically if jquery is loaded.

Options I have considered are:

Test the connection speed by downloading a small image

Download jquery but timeout after a second or so (I searched for cancelling downloads but found nothing)

Drop jquery all together and just write the javascript I need (I'll probably get it wrong for some browsers though)

Wrap the jquery download in some javascript which checks the useragent for andriod or iphone

Try to use css media selectors to control the jquery download

but I am not sure which to persue.

Also, I can't use server side tricks as it is a static page (to avoid the appengine cold start issue).

答:
I tend to say forget it.

Any serious speed test will need to transfer more data than the jQuery library weighs.

You could give users a choice (like "open low-bandwidth web site") and store that choice in a cookie. You could then check the cookie's value, and embed or not embed jQuery dynamically on server side, or using JavaScript as shown in @banjomonster's answer to this question.

Other than that,  I would just go ahead and include it. If you include it from Google's CDN, chances are it is in the user's browser already anyway, and doesn't have to be loaded again.


问:
Vec::dedup does not work — how do I deduplicate a vector of strings?
I've parsed a file, split the string by lines and want to leave only unique elements in each vector. I expect vec.dedup() to work like this:

```<code>let mut vec = vec!["a", "b", "a"];
vec.dedup();
assert_eq!(vec, ["a", "b"]);
</code>```

But it fails:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `["a", "b", "a"]`,
 right: `["a", "b"]`', src/main.rs:4:4
```

How can I remove duplicates?

答:
The other answer points out that a HashSet is a better choice for a collection without duplicates, which I agree with. This shows how to directly deduplicate a Vec using that property of HashMap and without sorting the Vec first to use std::vec::Vec::dedup.

```<code>use std::hash::Hash;
use std::collections::HashSet;

fn dedup<T: Eq + Hash + Copy>(v: &mut Vec<T>) { // note the Copy constraint
    let mut uniques = HashSet::new();
    v.retain(|e| uniques.insert(*e));
}

fn main() {
    let mut v = vec!["a", "b", "a"];
    dedup(&mut v);

    assert_eq!(&v, &vec!["a", "b"]);
}
</code>```

This is a fast (O(n)) solution, but creating the HashSet requires some extra memory.

Body:
I've parsed a file, split the string by lines and want to leave only unique elements in each vector. I expect vec.dedup() to work like this:

let mut vec = vec!["a", "b", "a"];
vec.dedup();
assert_eq!(vec, ["a", "b"]);

But it fails:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `["a", "b", "a"]`,
 right: `["a", "b"]`', src/main.rs:4:4

How can I remove duplicates?

Body:
The other answer points out that a HashSet is a better choice for a collection without duplicates, which I agree with. This shows how to directly deduplicate a Vec using that property of HashMap and without sorting the Vec first to use std::vec::Vec::dedup.

use std::hash::Hash;
use std::collections::HashSet;

fn dedup<T: Eq + Hash + Copy>(v: &mut Vec<T>) { // note the Copy constraint
    let mut uniques = HashSet::new();
    v.retain(|e| uniques.insert(*e));
}

fn main() {
    let mut v = vec!["a", "b", "a"];
    dedup(&mut v);

    assert_eq!(&v, &vec!["a", "b"]);
}

This is a fast (O(n)) solution, but creating the HashSet requires some extra memory.


问:
What's the workaround to get the map between volume label and drive letter in java instead of FileSystemView
It's feasible to get the map between volume label and drive letter in java by code below:

```<code>import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class Test{

    public void listMap(){
        File[] files = File.listRoots();
        System.out.println("The map between volume label and drive is: " );
        for(File file: files){
            String theMap = FileSystemView.getFileSystemView().getSystemDisplayName(file);
            System.out.println(theMap);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.listMap();
    }
}
</code>```

However, it's not a workable solution for me since this thread,  the usage of FileSystemView will lead to the NPE in my scenario. So here comes my question, how to get the map between volume lavel and drive letter in java instead of FileSystemView? I have googled a lot but found nothing without the usage of FileSystemView. Maybe the last workaround is to write the native code to get the map and using JNI to calling from java.

答:
Finally chosen to implement it in native side and used JNI(Java Native Interface) to get the map.

I wants the function on Windows so GetLogicalDrives is served as File[] files = File.listRoots();, after that, GetVolumeInformation is used to get the volume label from drive.

Post the solution for those who might meet the same issue.

Body:
It's feasible to get the map between volume label and drive letter in java by code below:

import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class Test{

    public void listMap(){
        File[] files = File.listRoots();
        System.out.println("The map between volume label and drive is: " );
        for(File file: files){
            String theMap = FileSystemView.getFileSystemView().getSystemDisplayName(file);
            System.out.println(theMap);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.listMap();
    }
}

However, it's not a workable solution for me since this thread,  the usage of FileSystemView will lead to the NPE in my scenario. So here comes my question, how to get the map between volume lavel and drive letter in java instead of FileSystemView? I have googled a lot but found nothing without the usage of FileSystemView. Maybe the last workaround is to write the native code to get the map and using JNI to calling from java.


问:
What is the best way to disable horizontal scroll of UIScrollView?
In UIScrollView, I have content height and width greater than scrollview's size. So basically it can scroll horizontally and vertically. What I want is to scroll vertically only and I manage horizontally scroll using an UIButton by using below code.

```<code> [scrlViewQuestion setContentOffset:CGPointMake(questionWidth, 0) animated:YES];
</code>```

Preventing horizontal scrollview, one can just set scrollview content width lesser than scrollview size but in my case scrollview content width is greater than its size? So what is the best way to solve this?

答:
You can do this in storyboard.

Disable the Show Horizontal Indicator tab from the Scroll View's Identity Inspector.It will disable your horizontal scrolling.

Body:
In UIScrollView, I have content height and width greater than scrollview's size. So basically it can scroll horizontally and vertically. What I want is to scroll vertically only and I manage horizontally scroll using an UIButton by using below code.

 [scrlViewQuestion setContentOffset:CGPointMake(questionWidth, 0) animated:YES];

Preventing horizontal scrollview, one can just set scrollview content width lesser than scrollview size but in my case scrollview content width is greater than its size? So what is the best way to solve this?


问:
accurately timing an execution of a system call using perl
Is there a better way programmatically using perl to track the timing of a unix process (start time, end time)??

For example, I have a perl script that launches a unix command using system(). I print the timestamp before the system() and after.

My log of the start time and end time are the same. I know for sure that when the process completes its a matter of minutes, so its not accurate.

Here's my code thus far:

```<code>my $dt  = strftime('%Y%m%d', localtime(time));
my $dt2 = strftime('%Y%m%d-%H:%M:%S', localtime(time));
my @tbls = qx(mysql -u foo -pmypw --database $dbsrc -h $node -ss -e "show tables");

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => $dt2\n";
   my $crfile = qq{mysql -u foo -pmypw --database $dbsrc -h $node.test.com -ss -e "SELECT 'a','b','c' UNION SELECT 1,2,3 FROM $tbls"| tr "\t" ",">$node-$tbls.$dt.csv};   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => $dt2\n";
};
close (CRLOG);
</code>```

答:
$dt2 is a constant, but it looks like you want it to recompute the timestamp every time it is used. For that purpose, you should use a function.

```<code>sub dt2 {
    return strftime('%Y%m%d-%H:%M:%S', localtime(time))
}

...

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => ", &dt2, "\n";
   my $crfile = qq{mysql -u foo -pmypw ...};
   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => ", &dt2, "\n";
};
close (CRLOG);
</code>```

Body:
Is there a better way programmatically using perl to track the timing of a unix process (start time, end time)??

For example, I have a perl script that launches a unix command using system(). I print the timestamp before the system() and after.

My log of the start time and end time are the same. I know for sure that when the process completes its a matter of minutes, so its not accurate.

Here's my code thus far:

my $dt  = strftime('%Y%m%d', localtime(time));
my $dt2 = strftime('%Y%m%d-%H:%M:%S', localtime(time));
my @tbls = qx(mysql -u foo -pmypw --database $dbsrc -h $node -ss -e "show tables");

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => $dt2\n";
   my $crfile = qq{mysql -u foo -pmypw --database $dbsrc -h $node.test.com -ss -e "SELECT 'a','b','c' UNION SELECT 1,2,3 FROM $tbls"| tr "\t" ",">$node-$tbls.$dt.csv};   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => $dt2\n";
};
close (CRLOG);

Body:
$dt2 is a constant, but it looks like you want it to recompute the timestamp every time it is used. For that purpose, you should use a function.

sub dt2 {
    return strftime('%Y%m%d-%H:%M:%S', localtime(time))
}

...

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => ", &dt2, "\n";
   my $crfile = qq{mysql -u foo -pmypw ...};
   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => ", &dt2, "\n";
};
close (CRLOG);


问:
Haproxy acl rules for SSL
I  need to configure Haproxy for SSL such that if certain keyword match in URL then it should go to non SSL port (8080) and for rest of calls, it should  go to SSL port 8443.

I have assigned 127.0.0.1 for example.com, if URL example.com entered in browser then it pointing localhost in my machine.

In Frontend SSL, acl rules are not working as desired because URL with action 'reporting' or 'account_management' are not referring to backend proxybackend. All traffic going through default_backend SSLappAPI even if URL having action=reporting.

Is acl not  working because i am trying to use non-SSL port  for  SSL traffic or am i having any issue in below haproxy configuration.

Any help will be much appreciated

Example URL: https://example.com/api/?uid=NrpB1vfSR01KVsxw1YI5H4&action=reporting

```<code>frontend  main *:80

    acl is_api url_param(action) -i host_check
    use_backend appAPI      if is_api
    default_backend             appUI
    option             forwardfor

frontend ssl
    mode tcp
    bind *:443
    option tcplog
    acl server_ssl urlp_sub(action) -i reporting
    acl server_ssl urlp_sub(action) -i account_management
    acl server_ssl hdr(host) -i example.com
    acl server_ssl hdr_sub(host) -i example.com

    use_backend proxybackend if server_ssl
    default_backend             SSLappAPI
    option             forwardfor

backend appUI
    server      ui-server 127.0.0.1:8080 check maxconn 50#ui <- leave this format to allow for selective script replacement

backend appAPI
    server  api-server 127.0.0.1:8080 check maxconn 750#api <- leave this format to allow for selective script replacement
    timeout http-keep-alive 0s

backend SSLappAPI
    mode tcp
    server  api-server 127.0.0.1:8443 check maxconn 800#ssl <- leave this format to allow for selective script replacement

backend proxybackend
    server proxyserver 127.0.0.1:8080
</code>```

答:
Rule 'req_ssl_sni' did the trick. Seems  like normal ACL not working for SSL and here 'req_ssl_sni' will come for rescue.

Working code is below for 2 SSL servers using same haproxy. Also below code will work for SSL certificates also, no need to install combined .PEM certificates at haproxy server.

frontend ssl
    mode tcp ssl
    bind *:443
    option tcplog

```<code>tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }

use_backend SSLappAPI if { req_ssl_sni -i anoexample.com }
use_backend proxybackend if { req_ssl_sni -i example.com }

default_backend             SSLappAPI

backend SSLappAPI
mode tcp
server  api-server 127.0.0.1:8443 check maxconn 800#ssl <- leave this format to allow for selective script replacement

backend proxybackend
mode tcp
#option nolinger
option tcplog
balance roundrobin
hash-type consistent
option srvtcpka

# maximum SSL session ID length is 32 bytes.
stick-table type binary len 32 size 30k expire 30m

# make sure we cover type 1 (fallback)
acl clienthello req_ssl_hello_type 1
acl serverhello rep_ssl_hello_type 2

# use tcp content accepts to detects ssl client and server hello.
tcp-request inspect-delay 5s
tcp-request content accept if clienthello

# no timeout on response inspect delay by default.
tcp-response content accept if serverhello

# SSL session ID (SSLID) may be present on a client or server hello.
# Its length is coded on 1 byte at offset 43 and its value starts
# at offset 44.
# Match and learn on request if client hello.
stick on payload_lv(43,1) if clienthello

# Learn on response if server hello.
stick store-response payload_lv(43,1) if serverhello

#option ssl-hello-chk

server proxyserver 127.0.0.2:443
</code>```

Title: Haproxy acl rules for SSL

Body:
I  need to configure Haproxy for SSL such that if certain keyword match in URL then it should go to non SSL port (8080) and for rest of calls, it should  go to SSL port 8443.

I have assigned 127.0.0.1 for example.com, if URL example.com entered in browser then it pointing localhost in my machine.

In Frontend SSL, acl rules are not working as desired because URL with action 'reporting' or 'account_management' are not referring to backend proxybackend. All traffic going through default_backend SSLappAPI even if URL having action=reporting.

Is acl not  working because i am trying to use non-SSL port  for  SSL traffic or am i having any issue in below haproxy configuration.

Any help will be much appreciated

Example URL: https://example.com/api/?uid=NrpB1vfSR01KVsxw1YI5H4&action=reporting

frontend  main *:80

    acl is_api url_param(action) -i host_check
    use_backend appAPI      if is_api
    default_backend             appUI
    option             forwardfor

frontend ssl
    mode tcp
    bind *:443
    option tcplog
    acl server_ssl urlp_sub(action) -i reporting
    acl server_ssl urlp_sub(action) -i account_management
    acl server_ssl hdr(host) -i example.com
    acl server_ssl hdr_sub(host) -i example.com

    use_backend proxybackend if server_ssl
    default_backend             SSLappAPI
    option             forwardfor

backend appUI
    server      ui-server 127.0.0.1:8080 check maxconn 50#ui <- leave this format to allow for selective script replacement

backend appAPI
    server  api-server 127.0.0.1:8080 check maxconn 750#api <- leave this format to allow for selective script replacement
    timeout http-keep-alive 0s

backend SSLappAPI
    mode tcp
    server  api-server 127.0.0.1:8443 check maxconn 800#ssl <- leave this format to allow for selective script replacement

backend proxybackend
    server proxyserver 127.0.0.1:8080

Body:
Rule 'req_ssl_sni' did the trick. Seems  like normal ACL not working for SSL and here 'req_ssl_sni' will come for rescue.

Working code is below for 2 SSL servers using same haproxy. Also below code will work for SSL certificates also, no need to install combined .PEM certificates at haproxy server.

frontend ssl
    mode tcp ssl
    bind *:443
    option tcplog

tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }

use_backend SSLappAPI if { req_ssl_sni -i anoexample.com }
use_backend proxybackend if { req_ssl_sni -i example.com }

default_backend             SSLappAPI

backend SSLappAPI
mode tcp
server  api-server 127.0.0.1:8443 check maxconn 800#ssl <- leave this format to allow for selective script replacement

backend proxybackend
mode tcp
#option nolinger
option tcplog
balance roundrobin
hash-type consistent
option srvtcpka

# maximum SSL session ID length is 32 bytes.
stick-table type binary len 32 size 30k expire 30m

# make sure we cover type 1 (fallback)
acl clienthello req_ssl_hello_type 1
acl serverhello rep_ssl_hello_type 2

# use tcp content accepts to detects ssl client and server hello.
tcp-request inspect-delay 5s
tcp-request content accept if clienthello

# no timeout on response inspect delay by default.
tcp-response content accept if serverhello

# SSL session ID (SSLID) may be present on a client or server hello.
# Its length is coded on 1 byte at offset 43 and its value starts
# at offset 44.
# Match and learn on request if client hello.
stick on payload_lv(43,1) if clienthello

# Learn on response if server hello.
stick store-response payload_lv(43,1) if serverhello

#option ssl-hello-chk

server proxyserver 127.0.0.2:443


问:
How to get returned value without await opeartor
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

```<code>class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}
</code>```

Here is there any possibility to get "hello world" string in var y without await operator?

答:
Are you looking for something like that;

```<code>var str = GetString2().Result;
</code>```

Result blocks the calling thread until the asynchronous operation is complete; it is equivalent the Wait method. await has asynchronous wait for the task completion.

Also, as @Sir Rufo and @MistyK described, you will get AggregateException on a possible exception, so it would be better to use GetAwaiter like this;

```<code>var str = GetString2().GetAwaiter().GetResult();
</code>```

Body:
I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await.
Is there any possibility to get the returned value?

Please find below sample code snippet:

class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}

Here is there any possibility to get "hello world" string in var y without await operator?

Body:
Are you looking for something like that;

var str = GetString2().Result;

Result blocks the calling thread until the asynchronous operation is complete; it is equivalent the Wait method. await has asynchronous wait for the task completion.

Also, as @Sir Rufo and @MistyK described, you will get AggregateException on a possible exception, so it would be better to use GetAwaiter like this;

var str = GetString2().GetAwaiter().GetResult();


问:
Perl print matched regex string
The following perl code only gives back true or false (1 & 0)

#!/usr/bin/perl
use strict;
use warnings;

my $string;

$string ="interface Ethernet1/20
  shutdown";

my $test = $string =~ m/^.+$(?=\s+shutdown)/mg;
print "'$test'\n";
```

I get back a 1.
But how can I get back the matched string 'interface Ethernet1/20' ?
Thanks for every help!

答:
Simply give it list context:

```<code>my ($test) = $string =~ m/^.+$(?=\s+shutdown)/mg;
</code>```

The concept of evaluation context (list vs scalar) is fundamental to Perl programming, so it may be time to review some tutorials and/or a reference manual.

Title: Perl print matched regex string

Body:
The following perl code only gives back true or false (1 & 0)

#!/usr/bin/perl
use strict;
use warnings;

my $string;

$string ="interface Ethernet1/20
  shutdown";

my $test = $string =~ m/^.+$(?=\s+shutdown)/mg;
print "'$test'\n";

I get back a 1.
But how can I get back the matched string 'interface Ethernet1/20' ?
Thanks for every help!

Body:
Simply give it list context:

my ($test) = $string =~ m/^.+$(?=\s+shutdown)/mg;

The concept of evaluation context (list vs scalar) is fundamental to Perl programming, so it may be time to review some tutorials and/or a reference manual.


问:
Train bvlc_reference_caffenet with input data scaled to [0,1]
I followed the Caffe ImageNet Tutorial and could successfully train the bvlc_reference_caffenet. Now I would like to scale the input data from [0,255] to [0,1] (since I later have to run this CNN on hardware with limited fixed/floating point accuracy) like in the Caffe LeNet MNIST Tutorial where it is done by adding a scale parameter to the data layer:

```<code>layer {
  name: "mnist"
  type: "Data"
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "mnist_train_lmdb"
    backend: LMDB
    batch_size: 64
  }
  top: "data"
  top: "label"
}
</code>```

Due to this I added this scale parameter also to the bvlc_reference_caffenet and also divide the mean parameter which will be subtracted from each channel by 255:

```<code>layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
     crop_size: 227
     scale: 0.00390625
     mean_value: 0.40784313
     mean_value: 0.45882352
     mean_value: 0.48235294
     mirror: true
  }
  data_param {
    source: "examples/imagenet/ilsvrc12_train_lmdb"
    batch_size: 32
    backend: LMDB
  }
}
layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    crop_size: 227
    scale: 0.00390625
    mean_value: 0.40784313
    mean_value: 0.45882352
    mean_value: 0.48235294
    mirror: false
  }
  data_param {
    source: "examples/imagenet/ilsvrc12_val_lmdb"
    batch_size: 32
    backend: LMDB
  }
}
</code>```

When I train the net now the accuracy will always be lower than chance. What other parameters do I have to adopt to train the net with [0,1] images instead of [0,255] images?

答:
Caffe first subtracts the mean and then scales the result. You should retain your original 0...255 mean values.

Reference:

```<code>if (has_mean_file) {
          transformed_data[top_index] =
            (datum_element - mean[data_index]) * scale;
}
</code>```

(data_transformer.cpp)

Body:
I followed the Caffe ImageNet Tutorial and could successfully train the bvlc_reference_caffenet. Now I would like to scale the input data from [0,255] to [0,1] (since I later have to run this CNN on hardware with limited fixed/floating point accuracy) like in the Caffe LeNet MNIST Tutorial where it is done by adding a scale parameter to the data layer:

layer {
  name: "mnist"
  type: "Data"
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "mnist_train_lmdb"
    backend: LMDB
    batch_size: 64
  }
  top: "data"
  top: "label"
}

Due to this I added this scale parameter also to the bvlc_reference_caffenet and also divide the mean parameter which will be subtracted from each channel by 255:

layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
     crop_size: 227
     scale: 0.00390625
     mean_value: 0.40784313
     mean_value: 0.45882352
     mean_value: 0.48235294
     mirror: true
  }
  data_param {
    source: "examples/imagenet/ilsvrc12_train_lmdb"
    batch_size: 32
    backend: LMDB
  }
}
layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    crop_size: 227
    scale: 0.00390625
    mean_value: 0.40784313
    mean_value: 0.45882352
    mean_value: 0.48235294
    mirror: false
  }
  data_param {
    source: "examples/imagenet/ilsvrc12_val_lmdb"
    batch_size: 32
    backend: LMDB
  }
}

When I train the net now the accuracy will always be lower than chance. What other parameters do I have to adopt to train the net with [0,1] images instead of [0,255] images?

Body:
Caffe first subtracts the mean and then scales the result. You should retain your original 0...255 mean values.

Reference:

if (has_mean_file) {
          transformed_data[top_index] =
            (datum_element - mean[data_index]) * scale;
}

(data_transformer.cpp)