问:
How to speed up Ionic 2 apps booting time when running on device
I am currently doing an app with ionic 2 angular2 and Typescript. ANd i have a big problem when it comes to launching speed of my app. When i build the app for dev or prod  environment and install it on any device, it takes a lot of time to load.

when i launch the app it displays a white screen that stays for so long which is really annoying considering users won't wait that long.

I did delete the splashscreen cordova plugin and i changed the splashscreen delay to 0 in config.xml but it still take so much time to load.

when starting up my app only does couple of Get requests that is all.
Here is my current Config.xml

```<code><widget id="com.ionicframework.comvltapp596066" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>com.vlt.app</name>
    <description>An awesome Ionic/Cordova app.</description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="http://ionic.local/*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="2" />
    <preference name="SplashShowOnlyFirstTime" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="0" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
    </platform>
    <engine name="android" spec="^6.2.3" />
    <engine name="browser" spec="^4.1.0" />
    <plugin name="cordova-plugin-console" spec="1.0.5" />
    <plugin name="cordova-plugin-device" spec="1.1.4" />
    <plugin name="cordova-plugin-googlemaps" spec="^1.4.0">
        <variable name="API_KEY_FOR_ANDROID" value="AIzaSyALRGE9KkSD9Qpng8XR7vUaVNj1teJGhw4" />
    </plugin>
    <plugin name="cordova-plugin-inappbrowser" spec="^1.7.1" />
    <plugin name="cordova-plugin-statusbar" spec="2.2.2" />
    <plugin name="cordova-plugin-whitelist" spec="1.3.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="ionic-plugin-keyboard" spec="~2.2.1" />
</widget>
</code>```

Please help!

答:
From experience I would say boot time hasn't improved significantly in Ionic apps, but from online articles I gathered that you can optimize your Ionic app to boot and work faster.

Prefer Ionicons over images when necessary

Check and make sure your javascript files are moved to the bottom of the page

Don't use unnecessary libraries like JQuery.

Use less pages or otherwise learn to reuse pages.

Ionic 3 also introduced lazy loading to avoid you loading all your components at startup.

etc. Check out this link for a little more details

Body:
I am currently doing an app with ionic 2 angular2 and Typescript. ANd i have a big problem when it comes to launching speed of my app. When i build the app for dev or prod  environment and install it on any device, it takes a lot of time to load.

when i launch the app it displays a white screen that stays for so long which is really annoying considering users won't wait that long.

I did delete the splashscreen cordova plugin and i changed the splashscreen delay to 0 in config.xml but it still take so much time to load.

when starting up my app only does couple of Get requests that is all.
Here is my current Config.xml

<widget id="com.ionicframework.comvltapp596066" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>com.vlt.app</name>
    <description>An awesome Ionic/Cordova app.</description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="http://ionic.local/*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="2" />
    <preference name="SplashShowOnlyFirstTime" value="true" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="0" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
    </platform>
    <engine name="android" spec="^6.2.3" />
    <engine name="browser" spec="^4.1.0" />
    <plugin name="cordova-plugin-console" spec="1.0.5" />
    <plugin name="cordova-plugin-device" spec="1.1.4" />
    <plugin name="cordova-plugin-googlemaps" spec="^1.4.0">
        <variable name="API_KEY_FOR_ANDROID" value="AIzaSyALRGE9KkSD9Qpng8XR7vUaVNj1teJGhw4" />
    </plugin>
    <plugin name="cordova-plugin-inappbrowser" spec="^1.7.1" />
    <plugin name="cordova-plugin-statusbar" spec="2.2.2" />
    <plugin name="cordova-plugin-whitelist" spec="1.3.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="ionic-plugin-keyboard" spec="~2.2.1" />
</widget>

Please help!


来源: stackexchange

问:
Create a directory and get the handle by issuing one IRP
When we create a file by CreateFile, the file created and we get the handle.

But CreateDirectory doesn't return directory's handle.

I'd like to also get the handle when I create a directory.

I want to handle this by issuing only one I/O request packet.

So, 'Do CreateDirectory, then CreateFile with FILE_FLAG_BACKUP_SEMANTICS.' won't be an answer.

It will issue two Irps to file system.

Is there an Api I can use in Usermode(Win32 Api)?

答:
NT can do this, but Win32 doesn't expose it.  You need to use NT APIs for this.  NtCreateFile, specifically.  It should follow the same parameters of ZwCreateFile.

Here's an illustrative example (hacked up in a hurry inside a web form -- YMMV):

```<code>HANDLE
CreateDirectoryAndGetHandle(PWSTR pszFileName)
{
    NTSTATUS Status;
    UNICODE_STRING FileName;
    HANDLE DirectoryHandle;
    IO_STATUS_BLOCK IoStatus;
    OBJECT_ATTRIBUTES ObjectAttributes;

    RtlInitUnicodeString(&FileName, pszFileName);
    InitializeObjectAttributes(&ObjectAtributes, &FileName, 0, NULL, NULL);

    Status = NtCreateFile(&DirectoryHandle,
                          GENERIC_READ | GENERIC_WRITE,
                          &ObjectAttributes,
                          &IoStatus,
                          FILE_ATTRIBUTE_NORMAL,
                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                          FILE_CREATE,
                          FILE_DIRECTORY_FILE,
                          NULL,
                          0);

    if (NT_SUCCESS(Status))
    {
       return DirectoryHandle;
    }
    else
    {
       SetLastError(RtlNtStatusToDosError(Status));
       return INVALID_HANDLE_VALUE;
    }
}
</code>```

Some things to note...

NT paths have slightly different conventions than Win32 paths...  You might have to sanitize the path.

When talking about HANDLEs, NT APIs generally deal with NULL rather than INVALID_HANDLE_VALUE.

I didn't do it here, but by changing the InitializeObjectAttributes call you can do interesting things, like do a create relative to another directory handle.  Of course all the flags I've put in here you might also want to change.  Consult documentation and/or the web for best results.

ContentLicense: CC BY-SA 2.5

Body:
NT can do this, but Win32 doesn't expose it.  You need to use NT APIs for this.  NtCreateFile, specifically.  It should follow the same parameters of ZwCreateFile.

Here's an illustrative example (hacked up in a hurry inside a web form -- YMMV):

HANDLE
CreateDirectoryAndGetHandle(PWSTR pszFileName)
{
    NTSTATUS Status;
    UNICODE_STRING FileName;
    HANDLE DirectoryHandle;
    IO_STATUS_BLOCK IoStatus;
    OBJECT_ATTRIBUTES ObjectAttributes;

    RtlInitUnicodeString(&FileName, pszFileName);
    InitializeObjectAttributes(&ObjectAtributes, &FileName, 0, NULL, NULL);

    Status = NtCreateFile(&DirectoryHandle,
                          GENERIC_READ | GENERIC_WRITE,
                          &ObjectAttributes,
                          &IoStatus,
                          FILE_ATTRIBUTE_NORMAL,
                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                          FILE_CREATE,
                          FILE_DIRECTORY_FILE,
                          NULL,
                          0);

    if (NT_SUCCESS(Status))
    {
       return DirectoryHandle;
    }
    else
    {
       SetLastError(RtlNtStatusToDosError(Status));
       return INVALID_HANDLE_VALUE;
    }
}

Some things to note...

NT paths have slightly different conventions than Win32 paths...  You might have to sanitize the path.

When talking about HANDLEs, NT APIs generally deal with NULL rather than INVALID_HANDLE_VALUE.

I didn't do it here, but by changing the InitializeObjectAttributes call you can do interesting things, like do a create relative to another directory handle.  Of course all the flags I've put in here you might also want to change.  Consult documentation and/or the web for best results.


问:
Create and Store Cookies of Onclick Dynamically
I'm trying to create a cookie to store the text value of  tags. I know I can use document.getElementById('whatever') to extract the text value, but the function should be dynamic, i.e non-specific, by getting the text of the link that the user clicks. Can anyone lend a helping hand and show me how to alter the code for it to work accordingly? Thanks.

```<code><a href="" onClick="getOrder">#1234WDF</a>
<a href="" onClick="getOrder">#7643FER</a>

function getOrder(order){
  createCookie('order', $this.text, 90);
}
</code>```

答:
If you run the below code here at StackOverflow, you will see an error message proclaiming that the document is sandboxed and lacks the 'allow-same-origin' flag.  So, I respectfully suggest that you see the live demo here instead.

function setOrder(name,order){
   document.cookie = name + "=" + order;
   console.log(document.cookie);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>#1234WDF
#7643FER </code>```

As a reminder about downvoting here at StackOverflow, the official policy here is as follows:

Use your downvotes whenever you encounter ... an answer that is clearly and perhaps dangerously incorrect.

My answer matches neither of these conditions and so whoever cast the downvote egregiously maligned the answer, without even extending the courtesy of an explanation.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a cookie to store the text value of  tags. I know I can use document.getElementById('whatever') to extract the text value, but the function should be dynamic, i.e non-specific, by getting the text of the link that the user clicks. Can anyone lend a helping hand and show me how to alter the code for it to work accordingly? Thanks.

#1234WDF
#7643FER

function getOrder(order){
  createCookie('order', $this.text, 90);
}

Body:
If you run the below code here at StackOverflow, you will see an error message proclaiming that the document is sandboxed and lacks the 'allow-same-origin' flag.  So, I respectfully suggest that you see the live demo here instead.

function setOrder(name,order){
   document.cookie = name + "=" + order;
   console.log(document.cookie);

}

<a href="#" onClick="setOrder('item1',this.textContent)">#1234WDF</a>
<a href="#" onClick="setOrder('item2',this.textContent)">#7643FER</a>

As a reminder about downvoting here at StackOverflow, the official policy here is as follows:

Use your downvotes whenever you encounter ... an answer that is clearly and perhaps dangerously incorrect.

My answer matches neither of these conditions and so whoever cast the downvote egregiously maligned the answer, without even extending the courtesy of an explanation.


问:
Will assetBundle in Unity 5.4 be compatible with 5.6, vice versa?
If I build an assetBundle in Unity Editor 5.6, will it work in the game built with Unity 5.4?

What about vice versa?

答: Based on this post on the Unity forums, assetBundle from 5.0 on are forward compatible - no express guarantee on backward compatibility from what I can see.</p>


问:
accessibilty issue with codeigniter session library
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors

Here is the Controller code : Login.php

```<code>function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr);
            redirect('Login/redirec_To_home','refresh');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}

function redirec_To_home(){
    $this->load->view('login/home');
}
</code>```

Here is the view html file name : path views/login/home.php

```<code><?php
    print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>
</code>```

THANKS IN ADVANCE

答:
In the __construct area you need to reload the session library using get instance in libraries

https://www.codeigniter.com/user_guide/general/ancillary_classes.html

https://www.codeigniter.com/user_guide/general/creating_libraries.html#utilizing-codeigniter-resources-within-your-library

```<code>class Example {

    protected $CI;

    // We'll use a constructor, as you can't directly call a function
    // from a property definition.
    public function __construct()
    {
            // Assign the CodeIgniter super-object
            $this->CI =& get_instance();
            $this->CI->load->library('session');
            $this->CI->load->model('login_model');
    }

    public function somefunction()
    {
         $this->CI->input->post('username');
         $this->CI->input->post('password');

         $user_model = $this->CI->login_model->user_login();

         $sesstion_data = array('user_id' => '1');

         $this->CI->session->set_userdata($sesstion_data);
    }
}
</code>```

Body:
I'm working on user login system in codeigniter. When user clicks on login button the username and password are verified and the data is store in $this->session->set_userdata($arr); session library and the page redirects to home.php. Till here works fine but when is try to access the session in home.php as print_r($this->session->userdata);. it give me this errors

Here is the Controller code : Login.php

function login_user(){
    $login_btn = $this->input->post('login_btn');

    if($login_btn == TRUE){
        $arr['login'] = array(
            'username'=>$this->input->post('username'),
            'password'=>$this->input->post('password')
        );

        $query = $this->Login_model->users_login($arr);

        if($query->num_rows() > 0 && $query->num_rows() == 1){
            $this->load->library('session');
            $this->session->set_userdata($arr);
            redirect('Login/redirec_To_home','refresh');
        }
        else
        {
            $this->index();
        }
    }
    else
    {
        $this->index();
    }
}

function redirec_To_home(){
    $this->load->view('login/home');
}

Here is the view html file name : path views/login/home.php

<?php
    print_r($this->session->userdata); //ERRORS SHOWN IN THIS LINE NUMBER : 13
?>

THANKS IN ADVANCE

Body:
In the __construct area you need to reload the session library using get instance in libraries

https://www.codeigniter.com/user_guide/general/ancillary_classes.html

https://www.codeigniter.com/user_guide/general/creating_libraries.html#utilizing-codeigniter-resources-within-your-library

class Example {

    protected $CI;

    // We'll use a constructor, as you can't directly call a function
    // from a property definition.
    public function __construct()
    {
            // Assign the CodeIgniter super-object
            $this->CI =& get_instance();
            $this->CI->load->library('session');
            $this->CI->load->model('login_model');
    }

    public function somefunction()
    {
         $this->CI->input->post('username');
         $this->CI->input->post('password');

         $user_model = $this->CI->login_model->user_login();

         $sesstion_data = array('user_id' => '1');

         $this->CI->session->set_userdata($sesstion_data);
    }
}


问:
ImageResizer triggering login redirect on a virtual directory
I am using Image resizer just fine in other areas of my site to resize local images, but when trying to resize an image that is in a virtual directory, I am getting the login screen. (Logging in does not change anything) If I add the '.ashx' extension, I get the same result.

The site is hosted on IIS 10 (integrated mode), with the appPool identity granted modify permissions on the site directory.  The virtual directory is using a network user that has modify permissions on the network folder.  The debug output does not show any errors -- I've posted the gist [here]

I can access images in the virtual directory without a resizing querystring (image.jpg instead of image.jpg?width=100) and the images are served up normally. However, as soon as I add a resizing command to the querystring, I get the login screen.

Any suggestions on what I am doing wrong?

Thanks,

答: Nathanael had the solution above in the comments -- to solve the issue, I created a network user and granted modify privileges on the shared network folder to that user. I then set that same user as the application pool identity. Thanks for the help Nathanael! </p>


问:
What is the time complexity of the following code snippet?
I have written the following code snippet to find the range summaries, i.e., when given a sorted integer array without any duplicates, it returns the summaries as:

```<code>/* IP: [0,1,2,4,5,7]
 * OP: ["0->2","4->5","7"]
 */

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;

        if(nums.empty())
            return res;

        for(int i=0; i<nums.size(); i++) {
            int lowerRange=nums[i];

            while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
                i++;

            int higherRange=nums[i];

            if(lowerRange!=higherRange) {
                string str=to_string(lowerRange)+"->"+to_string(higherRange);
                res.push_back(str);
            } else
                res.push_back(to_string(lowerRange));
        }

        return res;
    }
};
</code>```

I am wondering about the time complexity of the above code snippet.  In my opinion, I am doing some "task" (execution of the inner while loop) for each element in the array (using the outer for loop).  Due to this, in the worst case, the complexity should be O(n^2) in my opinion.  On the other hand, I am doubtful because I do i++ in the inner while loop, due to which, I won't do the "task" on all the elements using the outer for loop.  Due to this increment, I am visiting all the elements only once in my entire code.  So, this should make the complexity O(n).  Could someone please confirm if the complexity is O(n^2) or O(n)?

答: You're advancing in your inner loop, hence it runs in O(n) time complexity.</p>

Body:
I have written the following code snippet to find the range summaries, i.e., when given a sorted integer array without any duplicates, it returns the summaries as:

/* IP: [0,1,2,4,5,7]
 * OP: ["0->2","4->5","7"]
 */

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;

        if(nums.empty())
            return res;

        for(int i=0; i<nums.size(); i++) {
            int lowerRange=nums[i];

            while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
                i++;

            int higherRange=nums[i];

            if(lowerRange!=higherRange) {
                string str=to_string(lowerRange)+"->"+to_string(higherRange);
                res.push_back(str);
            } else
                res.push_back(to_string(lowerRange));
        }

        return res;
    }
};

I am wondering about the time complexity of the above code snippet.  In my opinion, I am doing some "task" (execution of the inner while loop) for each element in the array (using the outer for loop).  Due to this, in the worst case, the complexity should be O(n^2) in my opinion.  On the other hand, I am doubtful because I do i++ in the inner while loop, due to which, I won't do the "task" on all the elements using the outer for loop.  Due to this increment, I am visiting all the elements only once in my entire code.  So, this should make the complexity O(n).  Could someone please confirm if the complexity is O(n^2) or O(n)?


问:
How Do I Click Web Button In VBA
I've spent hours reading through Stack Overflow, but can't find an answer which works for me.  I'm using VBA, and using Microsoft Internet Controls and Microsoft HTML Object Library.

Here's my code (which allows me to enter user name and password information even if there is no "value" or "id" information ... only "name" information):

```<code>' Incorporating Microsoft Internet Controls AND Microsoft HTML Object Library
' Webpage loaded constant
Const READYSTATE_COMPLETE = 4
' Declare Windows API function for setting active window
Declare Function SetForegroundWindow Lib "user32" _
Alias "SetForegroundWindow" (ByVal Hwnd As Long)As Long
' Declare Internet Explorer object
Dim IE As SHDocVw.InternetExplorer
Sub Main
SetMicrophone 0
   ' create instance of InternetExplorer
   Set IE = New InternetExplorer
   ' using your newly created instance of Internet Explorer
   With IE
      SetForegroundWindow IE.HWND
      .Visible = True
      .Navigate2 "http://www.NakedCapitalism.com/wp-admin"
     ' Wait until page we are navigating to is loaded
      Do While .Busy
      Loop
      Do
      Loop Until .readyState = READYSTATE_COMPLETE
      ' the username and password values will not exist if already logged in
      ' so no need to fill in the values and go straight to Next
      On Error Resume Next
         If Err Then
           'Do Nothing
         Else
          ' When the page is fully loaded enter your username and password
          ' you will need to set these appropriately
  End If
     Dim inputs As MSHTML.IHTMLElementCollection
    Dim iFrames As MSHTML.IHTMLElementCollection
    Dim iFrame As MSHTML.HTMLFrameElement
    ' Get top_window frame and navigate to it then
    Set doc = IE.document
    Set iFrames = doc.getElementsByName("top_window")
    If Not iFrames Is Nothing Then
        Set iFrame = iFrames(0)
        IE.navigate url & iFrame.src
              Set inputs = doc.getElementsByName("log")
        If Not inputs Is Nothing Then
            inputs(0).value = "MyUserName"
        End If
    End If
    Set IE = Nothing
   End With
    ' Get top_window frame and navigate to it then
    Set doc = IE.document
    Set iFrames = doc.getElementsByName("top_window")
    If Not iFrames Is Nothing Then
        Set iFrame = iFrames(0)
        IE.navigate url & iFrame.src
        Set inputs = doc.getElementsByName("pwd")
        If Not inputs Is Nothing Then
            inputs(0).value = "MyPassword"
        End If
    End If
    Set IE = Nothing
   ' Tidy Up
   SetMicrophone 1
End Sub
</code>```

I'm trying to click the button which has the following code:

```<code><p class="submit">
        <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" />
        <input type="hidden" name="redirect_to" value="http://www.nakedcapitalism.com/wp-admin/" />
        <input type="hidden" name="testcookie" value="1" />
    </p>
</code>```

Help!?

答:
How about this?</p>

```<code>Sub ClickMe()

Dim IE As InternetExplorer
Dim myZip As Long
Dim siteZip As Object
Dim URL As String
Dim gender As Object
Dim btnGo As Object

Sub Macro_1()
myZip = "12345"
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = "Individual and Family Health Insurance"
IE.navigate (URL)

Do
DoEvents
Loop Until IE.readyState = 4

Set siteZip = IE.document.getElementById("census_zipCode")
siteZip.Value = myZip

Set gender = IE.document.getElementById("census_primary_gender")
gender.Value = "MALE"

Set btnGo = IE.document.forms(0).all("method:submit") ' method:submit is the button's name
btnGo.Click

End Sub
</code>```

Title: How Do I Click Web Button In VBA

Body:
I've spent hours reading through Stack Overflow, but can't find an answer which works for me.  I'm using VBA, and using Microsoft Internet Controls and Microsoft HTML Object Library.

Here's my code (which allows me to enter user name and password information even if there is no "value" or "id" information ... only "name" information):

' Incorporating Microsoft Internet Controls AND Microsoft HTML Object Library
' Webpage loaded constant
Const READYSTATE_COMPLETE = 4
' Declare Windows API function for setting active window
Declare Function SetForegroundWindow Lib "user32" _
Alias "SetForegroundWindow" (ByVal Hwnd As Long)As Long
' Declare Internet Explorer object
Dim IE As SHDocVw.InternetExplorer
Sub Main
SetMicrophone 0
   ' create instance of InternetExplorer
   Set IE = New InternetExplorer
   ' using your newly created instance of Internet Explorer
   With IE
      SetForegroundWindow IE.HWND
      .Visible = True
      .Navigate2 "http://www.NakedCapitalism.com/wp-admin"
     ' Wait until page we are navigating to is loaded
      Do While .Busy
      Loop
      Do
      Loop Until .readyState = READYSTATE_COMPLETE
      ' the username and password values will not exist if already logged in
      ' so no need to fill in the values and go straight to Next
      On Error Resume Next
         If Err Then
           'Do Nothing
         Else
          ' When the page is fully loaded enter your username and password
          ' you will need to set these appropriately
  End If
     Dim inputs As MSHTML.IHTMLElementCollection
    Dim iFrames As MSHTML.IHTMLElementCollection
    Dim iFrame As MSHTML.HTMLFrameElement
    ' Get top_window frame and navigate to it then
    Set doc = IE.document
    Set iFrames = doc.getElementsByName("top_window")
    If Not iFrames Is Nothing Then
        Set iFrame = iFrames(0)
        IE.navigate url & iFrame.src
              Set inputs = doc.getElementsByName("log")
        If Not inputs Is Nothing Then
            inputs(0).value = "MyUserName"
        End If
    End If
    Set IE = Nothing
   End With
    ' Get top_window frame and navigate to it then
    Set doc = IE.document
    Set iFrames = doc.getElementsByName("top_window")
    If Not iFrames Is Nothing Then
        Set iFrame = iFrames(0)
        IE.navigate url & iFrame.src
        Set inputs = doc.getElementsByName("pwd")
        If Not inputs Is Nothing Then
            inputs(0).value = "MyPassword"
        End If
    End If
    Set IE = Nothing
   ' Tidy Up
   SetMicrophone 1
End Sub

I'm trying to click the button which has the following code:

        <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" />
        <input type="hidden" name="redirect_to" value="http://www.nakedcapitalism.com/wp-admin/" />
        <input type="hidden" name="testcookie" value="1" />

Help!?

Body:
How about this?

Sub ClickMe()

Dim IE As InternetExplorer
Dim myZip As Long
Dim siteZip As Object
Dim URL As String
Dim gender As Object
Dim btnGo As Object

Sub Macro_1()
myZip = "12345"
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = "Individual and Family Health Insurance"
IE.navigate (URL)

Do
DoEvents
Loop Until IE.readyState = 4

Set siteZip = IE.document.getElementById("census_zipCode")
siteZip.Value = myZip

Set gender = IE.document.getElementById("census_primary_gender")
gender.Value = "MALE"

Set btnGo = IE.document.forms(0).all("method:submit") ' method:submit is the button's name
btnGo.Click

End Sub


问:
How to get trace-cmd report based on a network interface name(Eg: eth2)?
Is there any way to filter out trace-cmd report based on network interface name (Eg: eth1 or eth2) ?

When i try to use "name" as EVENT_FIELD in trace-cmd report filter i get nothing.

Following is the command i used

```<code>  [prap4test]$trace-cmd report -F 'net/netif_receive_skb:name=="eth1"'
  version = 6
  cpus=2
  [prap4test]$
</code>```

But i was able to use "len" as EVENT_FIELD

```<code>[prap4test]$trace-cmd report -F 'net/netif_receive_skb'
version = 6
cpus=2
       trace-cmd-19979 [000] 499726.602505: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb0e00 len=84
            sshd-21184 [000] 499726.603209: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0f00 len=52
       trace-cmd-19978 [000] 499727.809932: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb5000 len=46
       trace-cmd-19979 [001] 499728.105372: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e753cc00 len=328
       trace-cmd-19978 [000] 499728.780571: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0700 len=100
[prap4test]$trace-cmd report -F 'net/netif_receive_skb:len >= 50'
version = 6
cpus=2
       trace-cmd-19979 [000] 499726.602505: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb0e00 len=84
            sshd-21184 [000] 499726.603209: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0f00 len=52
       trace-cmd-19979 [001] 499728.105372: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e753cc00 len=328
       trace-cmd-19978 [000] 499728.780571: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0700 len=100
</code>```

Following is the event format for netif_receive_skb

```<code>name: netif_receive_skb
ID: 991
format:
        field:unsigned short common_type;       offset:0;       size:2; signed:0;
        field:unsigned char common_flags;       offset:2;       size:1; signed:0;
        field:unsigned char common_preempt_count;       offset:3;       size:1; signed:0;
        field:int common_pid;   offset:4;       size:4; signed:1;

        field:void * skbaddr;   offset:8;       size:8; signed:0;
        field:unsigned int len; offset:16;      size:4; signed:0;
        field:__data_loc char[] name;   offset:20;      size:4; signed:1;

print fmt: "dev=%s skbaddr=%p len=%u", __get_str(name), REC->skbaddr, REC->len
</code>```

And in trace-cmd-report i found following details

```<code>Note, the EVENT_FIELD is the field name as shown by an events format
(as displayed with *--events*), and not what is found in the output.
If the output shows "ID:foo" but the field that "foo" belongs to was
called "name" in the event format, then "name" must be used in the filter.
The same is true about values. If the value that is displayed is converted
by to a string symbol, the filter checks the original value and not the
value displayed. For example, to filter on all tasks that were in the
running state at a context switch:

    -F 'sched/sched_switch : prev_state==0'

Although the output displays 'R', having 'prev_stat=="R"' will not work.
</code>```

So in short i want to know command to filter out based on "name" EVENT_FIELD

Thanks in advance,

prap4search

答:
This is indeed a bug in trace-cmd .

I got following patch from Steven Rostedt(creator of trace-cmd) as a  fix.

```<code>diff --git a/parse-filter.c b/parse-filter.c
index c2fd26f..8e302c4 100644
--- a/parse-filter.c
+++ b/parse-filter.c
@@ -1880,17 +1880,25 @@ static const char *get_field_str(struct filter_arg *arg, struct pevent_record *r
    struct pevent *pevent;
    unsigned long long addr;
    const char *val = NULL;
+    unsigned int size;
    char hex[64];

    /* If the field is not a string convert it */
    if (arg->str.field->flags & FIELD_IS_STRING) {
        val = record->data + arg->str.field->offset;
+        size = arg->str.field->size;
+
+        if (arg->str.field->flags & FIELD_IS_DYNAMIC) {
+            addr = *(unsigned int *)val;
+            val = record->data + (addr & 0xffff);
+            size = addr >> 16;
+        }

        /*
        * We need to copy the data since we can't be sure the field
        * is null terminated.
        */
-        if (*(val + arg->str.field->size - 1)) {
+        if (*(val + size - 1)) {
            /* copy it */
            memcpy(arg->str.buffer, val, arg->str.field->size);
            /* the buffer is already NULL terminated */
</code>```

After applying patch i can filter out using interface name

```<code>[prap4test]$../trace-cmd/trace-cmd report -F 'net/netif_receive_skb:name=="eth1"'
cpus=2
       trace-cmd-1108  [000] 1111798.397704: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9f5ee00 len=52
       trace-cmd-1108  [000] 1111798.428998: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e867b400 len=392
       trace-cmd-1108  [000] 1111798.989447: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e743ed00 len=46
       trace-cmd-1108  [000] 1111799.450838: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800eab94b00 len=576
       trace-cmd-1108  [000] 1111799.549737: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800eab94700 len=576
       trace-cmd-1108  [000] 1111800.263439: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e87c4e00 len=100
</code>```

Body:
Is there any way to filter out trace-cmd report based on network interface name (Eg: eth1 or eth2) ?

When i try to use "name" as EVENT_FIELD in trace-cmd report filter i get nothing.

Following is the command i used

  [prap4test]$trace-cmd report -F 'net/netif_receive_skb:name=="eth1"'
  version = 6
  cpus=2
  [prap4test]$

But i was able to use "len" as EVENT_FIELD

[prap4test]$trace-cmd report -F 'net/netif_receive_skb'
version = 6
cpus=2
       trace-cmd-19979 [000] 499726.602505: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb0e00 len=84
            sshd-21184 [000] 499726.603209: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0f00 len=52
       trace-cmd-19978 [000] 499727.809932: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb5000 len=46
       trace-cmd-19979 [001] 499728.105372: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e753cc00 len=328
       trace-cmd-19978 [000] 499728.780571: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0700 len=100
[prap4test]$trace-cmd report -F 'net/netif_receive_skb:len >= 50'
version = 6
cpus=2
       trace-cmd-19979 [000] 499726.602505: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e9bb0e00 len=84
            sshd-21184 [000] 499726.603209: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0f00 len=52
       trace-cmd-19979 [001] 499728.105372: netif_receive_skb:    dev=eth2 skbaddr=0xffff8800e753cc00 len=328
       trace-cmd-19978 [000] 499728.780571: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9bb0700 len=100

Following is the event format for netif_receive_skb

name: netif_receive_skb
ID: 991
format:
        field:unsigned short common_type;       offset:0;       size:2; signed:0;
        field:unsigned char common_flags;       offset:2;       size:1; signed:0;
        field:unsigned char common_preempt_count;       offset:3;       size:1; signed:0;
        field:int common_pid;   offset:4;       size:4; signed:1;

        field:void * skbaddr;   offset:8;       size:8; signed:0;
        field:unsigned int len; offset:16;      size:4; signed:0;
        field:__data_loc char[] name;   offset:20;      size:4; signed:1;

print fmt: "dev=%s skbaddr=%p len=%u", __get_str(name), REC->skbaddr, REC->len

And in trace-cmd-report i found following details

Note, the EVENT_FIELD is the field name as shown by an events format
(as displayed with *--events*), and not what is found in the output.
If the output shows "ID:foo" but the field that "foo" belongs to was
called "name" in the event format, then "name" must be used in the filter.
The same is true about values. If the value that is displayed is converted
by to a string symbol, the filter checks the original value and not the
value displayed. For example, to filter on all tasks that were in the
running state at a context switch:

    -F 'sched/sched_switch : prev_state==0'

Although the output displays 'R', having 'prev_stat=="R"' will not work.

So in short i want to know command to filter out based on "name" EVENT_FIELD

Thanks in advance,

prap4search

Body:
This is indeed a bug in trace-cmd .

I got following patch from Steven Rostedt(creator of trace-cmd) as a  fix.

diff --git a/parse-filter.c b/parse-filter.c
index c2fd26f..8e302c4 100644
--- a/parse-filter.c
+++ b/parse-filter.c
@@ -1880,17 +1880,25 @@ static const char *get_field_str(struct filter_arg *arg, struct pevent_record *r
    struct pevent *pevent;
    unsigned long long addr;
    const char *val = NULL;
+    unsigned int size;
    char hex[64];

    /* If the field is not a string convert it */
    if (arg->str.field->flags & FIELD_IS_STRING) {
        val = record->data + arg->str.field->offset;
+        size = arg->str.field->size;
+
+        if (arg->str.field->flags & FIELD_IS_DYNAMIC) {
+            addr = *(unsigned int *)val;
+            val = record->data + (addr & 0xffff);
+            size = addr >> 16;
+        }

        /*
        * We need to copy the data since we can't be sure the field
        * is null terminated.
        */
-        if (*(val + arg->str.field->size - 1)) {
+        if (*(val + size - 1)) {
            /* copy it */
            memcpy(arg->str.buffer, val, arg->str.field->size);
            /* the buffer is already NULL terminated */

After applying patch i can filter out using interface name

[prap4test]$../trace-cmd/trace-cmd report -F 'net/netif_receive_skb:name=="eth1"'
cpus=2
       trace-cmd-1108  [000] 1111798.397704: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e9f5ee00 len=52
       trace-cmd-1108  [000] 1111798.428998: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e867b400 len=392
       trace-cmd-1108  [000] 1111798.989447: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e743ed00 len=46
       trace-cmd-1108  [000] 1111799.450838: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800eab94b00 len=576
       trace-cmd-1108  [000] 1111799.549737: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800eab94700 len=576
       trace-cmd-1108  [000] 1111800.263439: netif_receive_skb:    dev=eth1 skbaddr=0xffff8800e87c4e00 len=100


问:
Optimising a sentence search across multiple documents
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

```<code>$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];
</code>```

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

```<code>$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}
</code>```

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.

答:
You can use exec

create a test.php file and try this code

```<code>  <?php
    exec('grep '.escapeshellarg('end').' '."./test.php",$result);
    print_r($result);
    /* serach for some sentences
     * keep seraching
     * end of comment */
  ?>
</code>```

Ofcourse you will have to test its performance first then customize it to your needs

Body:
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.

Body:
You can use exec

create a test.php file and try this code

  <?php
    exec('grep '.escapeshellarg('end').' '."./test.php",$result);
    print_r($result);
    /* serach for some sentences
     * keep seraching
     * end of comment */
  ?>

Ofcourse you will have to test its performance first then customize it to your needs


问:
Insertion in Binary Tree (Not BST) Python
I'm trying to insert a node in my binary tree. However, I don't know the proper way to do this. I understand that I should run a bfs and insert in the first null position. How do I translate that into a code?

I was trying with DFS:
The tree looks like this:

```<code>class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
def insert(node, val):
     if not node:
           return Node(val)
     if not node.left:
           node.left = Node(val)
           return
     if not node.right:
           node.right = Node(val)
           return
     return insert(node.left, val)
     return insert(node.right, val)

n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8
</code>```

But that gives me an unreachable code.
What is the proper way to do this? I'm pretty frustrated by the people calling Binary Tree where they really mean BST.

答:
Yeah you're 100% right if you want it to be balanced and don't care about the order of the values inserts should be breadth-first and so I modified the code a little more for you but what I said originally still stands:

To do a bfs traversal you have to use another data structure, a queue. Queues are FIFO this means you end up visiting each node at each level before going to the next. Interestingly to make this depth first pop from the end instead of the beginning to simulate a stack.

```<code>def insert(node, val):
    """
    Always returns the root of the tree
    """
    if not node:
        return Node(val)
    queue = [node]
    while len(queue) > 0:
        # n is the current node in the tree
        n = queue.pop(0)

        # if it has no children insert node
        # start from the left
        if not n.left:
            n.left = Node(val)
            return node
        if not n.right:
            n.right = Node(val)
            return node

        queue.append(n.left)
        queue.append(n.right)
</code>```

Body:
I'm trying to insert a node in my binary tree. However, I don't know the proper way to do this. I understand that I should run a bfs and insert in the first null position. How do I translate that into a code?

I was trying with DFS:
The tree looks like this:

class Node:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
def insert(node, val):
     if not node:
           return Node(val)
     if not node.left:
           node.left = Node(val)
           return
     if not node.right:
           node.right = Node(val)
           return
     return insert(node.left, val)
     return insert(node.right, val)

n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8

But that gives me an unreachable code.
What is the proper way to do this? I'm pretty frustrated by the people calling Binary Tree where they really mean BST.

Body:
Yeah you're 100% right if you want it to be balanced and don't care about the order of the values inserts should be breadth-first and so I modified the code a little more for you but what I said originally still stands:

To do a bfs traversal you have to use another data structure, a queue. Queues are FIFO this means you end up visiting each node at each level before going to the next. Interestingly to make this depth first pop from the end instead of the beginning to simulate a stack.

def insert(node, val):
    """
    Always returns the root of the tree
    """
    if not node:
        return Node(val)
    queue = [node]
    while len(queue) > 0:
        # n is the current node in the tree
        n = queue.pop(0)

        # if it has no children insert node
        # start from the left
        if not n.left:
            n.left = Node(val)
            return node
        if not n.right:
            n.right = Node(val)
            return node

        queue.append(n.left)
        queue.append(n.right)


问:
Concourse CI: leverage docker image cache
I totally understand that Concourse is meant to be stateless, but nevertheless is there any way to re-use already pulled docker images?
In my case, I build ~10 docker images which have the same base image, but each time build is triggered Concourse pulls base image 10 times.

Is it possible to pull that image once and re-use it later (at least in scope of the same build) using standard docker resource?

Yeah, it should be possible to do that using custom image and code it in sh script, but I'm not in fond of inviting bicycles.

If standard docker resource does not allow that, is it possible to extend it somehow to enable such behaviour?

--cache-from is not helpful, as CI spends most of time pulling image, not building new layers.

答:
Theory

First, some Concourse theory (at least as of v3.3.1):

People often talk about Concourse having a "cache", but misinterpret what that means. Every concourse worker has a set of volumes on disk which are left around, forming a volume cache. This volume cache contains volumes that have been populated by resource get and put and task outputs.

People also often misunderstand how the docker-image-resource uses Docker. There is no global docker server running with your Concourse installation, in fact Concourse containers are not Docker containers, they are runC containers. Every docker-image-resource process (check, get, put) is run inside of its own runC container, inside of which there is a local docker server running. This means that there's no global docker server that is pulling docker images and caching the layers for further use.

What this implies is that when we talk about caching with the docker-image-resource, it means loading or pre-pulling images into the local docker server.

Practice

Now to the options for optimizing build times:

load_base

Background

The load_base param in your docker-image-resource put tells the resource to first docker load an image (retrieved via a get) into its local docker server, before building the image specified via your put params.

This is useful when you need to pre-populate an image into your "docker cache." In your case, you would want to preload the image used in the FROM directive. This is more efficient because it uses Concourse's own volume caching to only pull the "base" once, making it available to the docker server during the execution of the FROM command.

Usage

You can use load_base as follows:

Suppose you want to build a custom python image, and you have a git repository with a file ci/Dockerfile as follows:

```<code>FROM ubuntu

RUN apt-get update
RUN apt-get install -y python python-pip
</code>```

If you wanted to automate building/pushing of this image while taking advantage of Concourse volume caching as well as Docker image layer caching:

```<code>resources:
- name: ubuntu
  type: docker-image
  source:
    repository: ubuntu

- name: python-image
  type: docker-image
  source:
    repository: mydocker/python

- name: repo
  type: git
  source:
    uri: ...

jobs:
- name: build-image-from-base
  plan:
  - get: repo
  - get: ubuntu
    params: {save: true}
  - put: python-image
    params:
      load_base: ubuntu
      dockerfile: repo/ci/Dockerfile
</code>```

cache & cache_tag

Background

The cache and cache_tag params in your docker-image-resource put tell the resource to first pull a particular image+tag from your remote source, before building the image specified via your put params.

This is useful when it's easier to pull down the image than it is to build it from scratch, e.g. you have a very long build process, such as expensive compilations

This DOES NOT utilize Concourse's volume caching, and utilizes Docker's --cache-from feature (which runs the risk of needing to first perform a docker pull) during every put.

Usage

You can use cache and cache_tag as follows:

Suppose you want to build a custom ruby image, where you compile ruby from source, and you have a git repository with a file ci/Dockerfile as follows:

```<code>FROM ubuntu

# Install Ruby
RUN mkdir /tmp/ruby;\
  cd /tmp/ruby;\
  curl ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz | tar xz;\
  cd ruby-2.0.0-p247;\
  chmod +x configure;\
  ./configure --disable-install-rdoc;\
  make;\
  make install;\
  gem install bundler --no-ri --no-rdoc

RUN gem install nokogiri
</code>```

If you wanted to automate building/pushing of this image while taking advantage of only Docker image layer caching:

```<code>resources:
- name: compiled-ruby-image
  type: docker-image
  source:
    repository: mydocker/ruby
    tag: 2.0.0-compiled

- name: repo
  type: git
  source:
    uri: ...

jobs:
- name: build-image-from-cache
  plan:
  - get: repo
  - put: compiled-ruby-image
    params:
      dockerfile: repo/ci/Dockerfile
      cache: mydocker/ruby
      cache_tag: 2.0.0-compiled
</code>```

Recommendation

If you want to increase efficiency of building docker images, my personal belief is that load_base should be used in most cases. Because it uses a resource get, it takes advantage of Concourse volume caching, and avoids needing to do extra docker pulls.

Body:
Theory

First, some Concourse theory (at least as of v3.3.1):

People often talk about Concourse having a "cache", but misinterpret what that means. Every concourse worker has a set of volumes on disk which are left around, forming a volume cache. This volume cache contains volumes that have been populated by resource get and put and task outputs.

People also often misunderstand how the docker-image-resource uses Docker. There is no global docker server running with your Concourse installation, in fact Concourse containers are not Docker containers, they are runC containers. Every docker-image-resource process (check, get, put) is run inside of its own runC container, inside of which there is a local docker server running. This means that there's no global docker server that is pulling docker images and caching the layers for further use.

What this implies is that when we talk about caching with the docker-image-resource, it means loading or pre-pulling images into the local docker server.

Practice

Now to the options for optimizing build times:

load_base

Background

The load_base param in your docker-image-resource put tells the resource to first docker load an image (retrieved via a get) into its local docker server, before building the image specified via your put params.

This is useful when you need to pre-populate an image into your "docker cache." In your case, you would want to preload the image used in the FROM directive. This is more efficient because it uses Concourse's own volume caching to only pull the "base" once, making it available to the docker server during the execution of the FROM command.

Usage

You can use load_base as follows:

Suppose you want to build a custom python image, and you have a git repository with a file ci/Dockerfile as follows:

FROM ubuntu

RUN apt-get update
RUN apt-get install -y python python-pip

If you wanted to automate building/pushing of this image while taking advantage of Concourse volume caching as well as Docker image layer caching:

resources:
- name: ubuntu
  type: docker-image
  source:
    repository: ubuntu

- name: python-image
  type: docker-image
  source:
    repository: mydocker/python

- name: repo
  type: git
  source:
    uri: ...

jobs:
- name: build-image-from-base
  plan:
  - get: repo
  - get: ubuntu
    params: {save: true}
  - put: python-image
    params:
      load_base: ubuntu
      dockerfile: repo/ci/Dockerfile

cache & cache_tag

Background

The cache and cache_tag params in your docker-image-resource put tell the resource to first pull a particular image+tag from your remote source, before building the image specified via your put params.

This is useful when it's easier to pull down the image than it is to build it from scratch, e.g. you have a very long build process, such as expensive compilations

This DOES NOT utilize Concourse's volume caching, and utilizes Docker's --cache-from feature (which runs the risk of needing to first perform a docker pull) during every put.

Usage

You can use cache and cache_tag as follows:

Suppose you want to build a custom ruby image, where you compile ruby from source, and you have a git repository with a file ci/Dockerfile as follows:

FROM ubuntu

# Install Ruby
RUN mkdir /tmp/ruby;\
  cd /tmp/ruby;\
  curl ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz | tar xz;\
  cd ruby-2.0.0-p247;\
  chmod +x configure;\
  ./configure --disable-install-rdoc;\
  make;\
  make install;\
  gem install bundler --no-ri --no-rdoc

RUN gem install nokogiri

If you wanted to automate building/pushing of this image while taking advantage of only Docker image layer caching:

resources:
- name: compiled-ruby-image
  type: docker-image
  source:
    repository: mydocker/ruby
    tag: 2.0.0-compiled

- name: repo
  type: git
  source:
    uri: ...

jobs:
- name: build-image-from-cache
  plan:
  - get: repo
  - put: compiled-ruby-image
    params:
      dockerfile: repo/ci/Dockerfile
      cache: mydocker/ruby
      cache_tag: 2.0.0-compiled

Recommendation

If you want to increase efficiency of building docker images, my personal belief is that load_base should be used in most cases. Because it uses a resource get, it takes advantage of Concourse volume caching, and avoids needing to do extra docker pulls.

ContentLicense: CC BY-SA 4.0


问:
LAMP vhost still points to www/html
I've created the following virtual host file in /etc/apache2/sites-available/lion.dev:

```<code><VirtualHost *:80>
    ServerAdmin webmaster@lion.dev
    ServerName lion.dev

    DocumentRoot /var/www/lion.dev
    <Directory />
    Options FollowSymLinks
    AllowOverride None
    </Directory>
    <Directory /var/www/lion.dev/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>

    CustomLog /var/log/apache2/lion.dev/access.log combined
    ErrorLog /var/log/apache2/lion.dev/error.log
</VirtualHost>
</code>```

The problem is that it is actually pointing to the /www/html folder when I visit lion.dev in my browser.

What am I missing and why isn't this working?

答: I resolved the issue by uninstalling Ubuntu and re-installing Windows 10</p>

Title: LAMP vhost still points to www/html

Body:
I've created the following virtual host file in /etc/apache2/sites-available/lion.dev:

<VirtualHost *:80>
    ServerAdmin webmaster@lion.dev
    ServerName lion.dev

    DocumentRoot /var/www/lion.dev
    <Directory />
    Options FollowSymLinks
    AllowOverride None
    </Directory>
    <Directory /var/www/lion.dev/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>

    CustomLog /var/log/apache2/lion.dev/access.log combined
    ErrorLog /var/log/apache2/lion.dev/error.log
</VirtualHost>

The problem is that it is actually pointing to the /www/html folder when I visit lion.dev in my browser.

What am I missing and why isn't this working?


问:
Grabbing specific sections of a txt file via Powershell
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

```<code>-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:
</code>```

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

```<code>$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array
</code>```

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.

答:
You could use Select-String or Where-Object to look for words with a \. Taking that even further you could look for just the server\printer values with a RegEx like this:

```<code>Get-Content C:\Users\User1\Documents\Config.txt -Raw |
    Select-String '[A-Z0-9]+\\[A-Z0-9]+' -AllMatches |
    ForEach-Object {$_.Matches.Value}
</code>```

Note that this makes the assumption the Server Names and Printers use only A-Z and 0-9, you may need to look for more characters if that is not a valid assumption.

Here would be an example of using Where-Object to filter for lines with \

```<code>Get-Content 'C:\Users\User1\Documents\Config.txt' | Where-Object {$_ -like '*\*'}
</code>```

Body:
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.

Body:
You could use Select-String or Where-Object to look for words with a \. Taking that even further you could look for just the server\printer values with a RegEx like this:

Get-Content C:\Users\User1\Documents\Config.txt -Raw |
    Select-String '[A-Z0-9]+\\[A-Z0-9]+' -AllMatches |
    ForEach-Object {$_.Matches.Value}

Note that this makes the assumption the Server Names and Printers use only A-Z and 0-9, you may need to look for more characters if that is not a valid assumption.

Here would be an example of using Where-Object to filter for lines with \

Get-Content 'C:\Users\User1\Documents\Config.txt' | Where-Object {$_ -like '*\*'}


问:
Multiply two column on a inner Join
help needed.

i want to multiply two column and display result to a  new column(totalQty).
TotalQty= (ITY00.CMPITQTY *  MPOS_GP_InvTransaction.Quantity)

HOW CAN I ACHIEVE THIS ?

```<code>Select
    MPOS_GP_InvTransaction.id,
    MPOS_GP_InvTransaction.[Type],
    MPOS_GP_InvTransaction.Vendor,
    MPOS_GP_InvTransaction.Currency,ITY00.CMPTITNM,
    MPOS_GP_InvTransaction.BatchId,
    MPOS_GP_InvTransaction.UserId,
    MPOS_GP_InvTransaction.ItemNo,
    MPOS_GP_InvTransaction.SiteId,
    ITY00.CMPITQTY,
    MPOS_GP_InvTransaction.Quantity,
    MPOS_GP_InvTransaction.IntegrationFlag
From DB_37788.dbo.MPOS_GP_InvTransaction
INNER JOIN TWCL.dbo.ITY00 ON ITY00.ITEMNMBR=MPOS_GP_InvTransaction.ItemNo
Where (MPOS_GP_InvTransaction.ItemNo  like '%-GTYR%' )
OR (MPOS_GP_InvTransaction.ItemNo  like '%-JKOP%' )
And (MPOS_GP_InvTransaction.SiteId  IN('MM-DC-ZZQW','MM-DC-TTYR') )
And (MPOS_GP_InvTransaction.IntegrationFlag = 0 )
</code>```

答:
```<code>SELECT MPOS_GP_InvTransaction.id,
       MPOS_GP_InvTransaction.Type,
       MPOS_GP_InvTransaction.Vendor,
       MPOS_GP_InvTransaction.Currency,
       ITY00.CMPTITNM,
       MPOS_GP_InvTransaction.BatchId,
       MPOS_GP_InvTransaction.UserId,
       MPOS_GP_InvTransaction.ItemNo,
       MPOS_GP_InvTransaction.SiteId,
       ITY00.CMPITQTY,
       MPOS_GP_InvTransaction.Quantity,
       MPOS_GP_InvTransaction.IntegrationFlag,
      ITY00.CMPITQTY * MPOS_GP_InvTransaction.Quantity AS TotalQty
FROM DB_37788.dbo.MPOS_GP_InvTransaction
     INNER JOIN TWCL.dbo.ITY00 ON ITY00.ITEMNMBR = MPOS_GP_InvTransaction.ItemNo
WHERE(MPOS_GP_InvTransaction.ItemNo LIKE '%-GTYR%')
     OR (MPOS_GP_InvTransaction.ItemNo LIKE '%-JKOP%')
     AND (MPOS_GP_InvTransaction.SiteId IN('MM-DC-ZZQW', 'MM-DC-TTYR'))
     AND (MPOS_GP_InvTransaction.IntegrationFlag = 0);
</code>```

Title: Multiply two column on a inner Join

Body:
help needed.

i want to multiply two column and display result to a  new column(totalQty).
TotalQty= (ITY00.CMPITQTY *  MPOS_GP_InvTransaction.Quantity)

HOW CAN I ACHIEVE THIS ?

Select
    MPOS_GP_InvTransaction.id,
    MPOS_GP_InvTransaction.[Type],
    MPOS_GP_InvTransaction.Vendor,
    MPOS_GP_InvTransaction.Currency,ITY00.CMPTITNM,
    MPOS_GP_InvTransaction.BatchId,
    MPOS_GP_InvTransaction.UserId,
    MPOS_GP_InvTransaction.ItemNo,
    MPOS_GP_InvTransaction.SiteId,
    ITY00.CMPITQTY,
    MPOS_GP_InvTransaction.Quantity,
    MPOS_GP_InvTransaction.IntegrationFlag
From DB_37788.dbo.MPOS_GP_InvTransaction
INNER JOIN TWCL.dbo.ITY00 ON ITY00.ITEMNMBR=MPOS_GP_InvTransaction.ItemNo
Where (MPOS_GP_InvTransaction.ItemNo  like '%-GTYR%' )
OR (MPOS_GP_InvTransaction.ItemNo  like '%-JKOP%' )
And (MPOS_GP_InvTransaction.SiteId  IN('MM-DC-ZZQW','MM-DC-TTYR') )
And (MPOS_GP_InvTransaction.IntegrationFlag = 0 )


问:
What's the best way to save set of objects locally in react-native?
AsyncStorage is unable to retain data and I have run out of options to save
a set of objects and update them with new entries to the list. Please help</p>

答:
For Handling App's Data:

State - It handles component's internal data with not much complexity.

Props - It tosses data back and forth from parent component to children and vice verse.

Redux - It handles data efficiently using action-reducer-store architecture. Great for a complex app with a lot of user's data to handle.

For Data Persistance:

AsyncStorage - Simple API to save and manage data on device manually.

Redux Persist - Built over Redux to store all the Redux State data to device synchronously.

Hope this helps :)


问:
Only prints the last server in the list, I want all servers
This only prints the last server in the list, I'm looking to get all servers and print to screen </p>

```<code>$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status
</code>```

答:
$Status is constantly being overwritten by the current machine in your list.

You're looking for:

```<code>$Status+=
</code>```

As opposed to:

```<code>$Status=
</code>```

You'll also want to explicitly state that $Status will be an array at the beginning like so:

```<code>$Status=@()
</code>```

Or when you create the variable and omit the line at the beginning.

```<code>[array]$Status +=
</code>```

Otherwise, you'll get results that run together as it will be treated as a [String]

Body:
This only prints the last server in the list, I'm looking to get all servers and print to screen

$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status

Body:
$Status is constantly being overwritten by the current machine in your list.

You're looking for:

$Status+=

As opposed to:

$Status=

You'll also want to explicitly state that $Status will be an array at the beginning like so:

$Status=@()

Or when you create the variable and omit the line at the beginning.

[array]$Status +=

Otherwise, you'll get results that run together as it will be treated as a [String]


问:
MMORPG protocol encryption
Anyone know what the trend is with MMORPG developers encryption their client/server protocols these days?

The pro's and con's are as follows.

Encrypting protocol:

protects trade secrets regarding client/server protocol to a degree?

Botting isn't stopped, it is only changed because people will create bots which read screen states and trigger mouse+keyboard events will then be developed, merely mitigating the development of bots as opposed to stopping them in anyway. Still though bot development is less in supply somewhat, but the demand is still there, they merely get higher bids on rentacoder.com

Regular plain text:

more advanced bots since the developers are able to inject their own datagrams into the client/server protocol. (ie: running through walls, teleporting... which the server side has to now check, which in turn leads to a development contest between out patching exploits via injection (time consuming)

答:
At the very least, the MMO's login protocol should be encrypted so that people on the player's network can't packet sniff their account information.

This reason can easily be extended to other data the player sends.  For example, chat with other players can contain sensitive information.  If the game is already going through the trouble of setting up an encryption protocol for the login process, there's probably not a lot of reason to turn it off after you're done.

OwnerDisplayName: Zombies

Title: MMORPG protocol encryption

OwnerDisplayName: fastcall


问:
Uncaught TypeError: Object function ()
I wrote the following functions. At run time the browser complains about uncaught TypeError ...has no method 'init'. What's wrong of my code? </p>

```<code>function build_results_grid (response) {

        // build grid
        grid_ui.init();

    } // build the results grid

    var grid_ui = function () {

        return {
            init: function () {
               //build_grid();
            }
      }; // return
    }
</code>```

答:
You assigned grid_ui to a function, without calling it.

Change that to

```<code>var grid_ui = (function() { ... })();
</code>```

Title: Uncaught TypeError: Object function ()

Body:
I wrote the following functions. At run time the browser complains about uncaught TypeError ...has no method 'init'. What's wrong of my code?

function build_results_grid (response) {

        // build grid
        grid_ui.init();

    } // build the results grid

    var grid_ui = function () {

        return {
            init: function () {
               //build_grid();
            }
      }; // return
    }

Body:
You assigned grid_ui to a function, without calling it.

Change that to

var grid_ui = (function() { ... })();


问:
Python - Zeep SOAP Complex Header
I'd like to pass "Complex" Header to a SOAP service with zeep library

Here's what it should look like

```<code> <soapenv:Header>
      <something:myVar1>FOO</something:myVar1>
      <something:myVar2>JAM</something:myVar2>
 </soapenv:Header>
</code>```

I guess that I succeed in sending a header this way

```<code>header = xsd.Element(
    '{http://urlofthews}Header',
        xsd.ComplexType([
        xsd.Element(
        '{http://urlofthews}myVar1',
        xsd.String()),
        xsd.Element(
        '{http://urlofthews}myVar2',
        xsd.String())
        ])
    )

header_value = header(myVar1='FOO',myVar2='JAM')
print (header_value)
datasoap=client.service.UserRessourcesCatalog(requete,_soapheaders=[header_value])
</code>```

But I don't get how to declare and pass the namespace "something" in my Header with the XSD.

Any Help ?

Thx by advance.

Best Regards

As mentionned in the documentation

http://docs.python-zeep.org/en/master/headers.html

"Another option is to pass an lxml Element object. This is generally useful if the wsdl doesn’t define a soap header but the server does expect it."

which is my case so I tried

```<code>try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElementTree as ET
    ET.register_namespace('something', 'http://urlofthews')

    headerXML = ET.Element("soapenv:Header")
    var1 = ET.SubElement(headerXML, "something:myVar1")
    var1.text = "FOO"
    var2 = ET.SubElement(headerXML, "something:myVar2")
    var2.text = "JAM"

headerDict=xmltodict.parse(ET.tostring(headerXML))
print (json.dumps(headerDict))

    datasoap=client.service.UserRessourcesCatalog(requete,_soapheaders=headerDict)
</code>```

But I get : ComplexType() got an unexpected keyword argument u'soapenv:Header'. Signature: ``

答:
Thx Oblivion02.

I finally use a raw method

```<code>headers = {'content-type': 'text/xml'}
body = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://blablabla">
<soapenv:Header>
<something:myVar1>FOO</something:myVar1>
<something:myVar2>JAM</something:myVar2>
</soapenv:Header>
<soapenv:Body>
          ...
</soapenv:Body>
</soapenv:Envelope>"""

response = requests.post(wsdl,data=body,headers=headers)
</code>```

Title: Python - Zeep SOAP Complex Header

Body:
I'd like to pass "Complex" Header to a SOAP service with zeep library

Here's what it should look like

 <soapenv:Header>
      <something:myVar1>FOO</something:myVar1>
      <something:myVar2>JAM</something:myVar2>
 </soapenv:Header>

I guess that I succeed in sending a header this way

header = xsd.Element(
    '{http://urlofthews}Header',
        xsd.ComplexType([
        xsd.Element(
        '{http://urlofthews}myVar1',
        xsd.String()),
        xsd.Element(
        '{http://urlofthews}myVar2',
        xsd.String())
        ])
    )

header_value = header(myVar1='FOO',myVar2='JAM')
print (header_value)
datasoap=client.service.UserRessourcesCatalog(requete,_soapheaders=[header_value])

But I don't get how to declare and pass the namespace "something" in my Header with the XSD.

Any Help ?

Thx by advance.

Best Regards

As mentionned in the documentation

http://docs.python-zeep.org/en/master/headers.html

"Another option is to pass an lxml Element object. This is generally useful if the wsdl doesn’t define a soap header but the server does expect it."

which is my case so I tried

try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElementTree as ET
    ET.register_namespace('something', 'http://urlofthews')

    headerXML = ET.Element("soapenv:Header")
    var1 = ET.SubElement(headerXML, "something:myVar1")
    var1.text = "FOO"
    var2 = ET.SubElement(headerXML, "something:myVar2")
    var2.text = "JAM"

headerDict=xmltodict.parse(ET.tostring(headerXML))
print (json.dumps(headerDict))

    datasoap=client.service.UserRessourcesCatalog(requete,_soapheaders=headerDict)

But I get : ComplexType() got an unexpected keyword argument u'soapenv:Header'. Signature: ``

Body:
Thx Oblivion02.

I finally use a raw method

headers = {'content-type': 'text/xml'}
body = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://blablabla">
<soapenv:Header>
<something:myVar1>FOO</something:myVar1>
<something:myVar2>JAM</something:myVar2>
</soapenv:Header>
<soapenv:Body>
          ...
</soapenv:Body>
</soapenv:Envelope>"""

response = requests.post(wsdl,data=body,headers=headers)


问:
Resolving "Unresolved function or method observable()" warning using KnockoutJS in PyCharm
PyCharm (professional edition, v2017.1.4) is failing to pick up any intellisense for KnockoutJS references such as these:

I've managed to resolve this in the past when using WebStorm; from what I recall, it boiled down to ensuring there was a KnockoutJS reference under Javascript > Libraries:

However, although I've done this (including the "Definitely Typed" version of the lib, see above), the "unresolved" warnings persist in PyCharm.

Anyone have any bright ideas as to what may help clear these warnings?

EDIT:

Additional screenshots:

Project interpreter settings

Javascript Libraries settings

RequireJS settings - points to debug v3.4.1 of KnockoutJS

ViewModel KO reference

Unfortunately, even with the js.knockout reference, the issue persists.

答:
You need to install the library there, as well as in the python project interpreter which you are using.

Settings | Project:myprj | Project Interpreter | '+'

Type in 'knockout'

Choose 'js.knockout'

Click Install Package

Should be good now.

For reference, here are the javascript libraries I have.


问:
list query using if and .split() taking too long Python
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

```<code>get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)
</code>```

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

答:
```<code>import numpy as np

# convert your data to 2D numpy array of integer numbers (year, quarter):
two_q_growth_arr = np.array([map(int, x.split('q')) for x in two_q_growth])

# Pull start_year and start_q computation out of the loop:
start_year, start_q = list(map(int, get_recession_start().split('q')))

# find indices of all data that satisfy your criteria:
ind = np.where((two_q_growth_arr[:, 0] > start_year) | ((two_q_growth_arr[:, 0] == start_year) & (two_q_growth_arr[:, 1] > start_q)))

# Extract the years as a list of integer numbers:
recession_end = two_q_growth_arr[ind][:,0].tolist()

# or, alternatively, convert to a list of strings:
recession_end = list(map(str, two_q_growth_arr[ind][:,0].tolist()))
</code>```

Another option is to convert years and quarters to a single fractional year which then simplifies the condition:

```<code>import numpy as np
two_q_growth_arr = np.array([map(int, x.split('q')) for x in two_q_growth])
two_q_growth_arr = two_q_growth_arr[:, 0] + 0.25 * (two_q_growth_arr[:, 1] - 1.0)
ind = np.where(two_q_growth_arr[:, 0] > start_year)
recession_end = list(map(str, two_q_growth_arr[ind][:,0].tolist()))
</code>```

Body:
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

Body:
import numpy as np

# convert your data to 2D numpy array of integer numbers (year, quarter):
two_q_growth_arr = np.array([map(int, x.split('q')) for x in two_q_growth])

# Pull start_year and start_q computation out of the loop:
start_year, start_q = list(map(int, get_recession_start().split('q')))

# find indices of all data that satisfy your criteria:
ind = np.where((two_q_growth_arr[:, 0] > start_year) | ((two_q_growth_arr[:, 0] == start_year) & (two_q_growth_arr[:, 1] > start_q)))

# Extract the years as a list of integer numbers:
recession_end = two_q_growth_arr[ind][:,0].tolist()

# or, alternatively, convert to a list of strings:
recession_end = list(map(str, two_q_growth_arr[ind][:,0].tolist()))

Another option is to convert years and quarters to a single fractional year which then simplifies the condition:

import numpy as np
two_q_growth_arr = np.array([map(int, x.split('q')) for x in two_q_growth])
two_q_growth_arr = two_q_growth_arr[:, 0] + 0.25 * (two_q_growth_arr[:, 1] - 1.0)
ind = np.where(two_q_growth_arr[:, 0] > start_year)
recession_end = list(map(str, two_q_growth_arr[ind][:,0].tolist()))


问:
Wordpress 301 Redirect not working
I am moving from a Wordpress site to a shopify site with a change of URL.

I have used the 301 Redirects plugin to send all site traffic from:

https://power-focus.co.uk    >     https://www.brainpowernootropics.com.

Except what I ended up with when I visit the first site expecting to get redirected is the first URL and the second URL together and no redirection.

No redirect happened? It just added the second URL on to the end of the first. (I dont know how to access the htaccess file as I dont have the server login details and don't know how to get them)

Thanks for your time!

答:
The above links are working fine. The power-focus url is redirecting to the new one.

However, you should redirect using wild card, meaning

```<code>https://power-focus.co.uk/any-page
</code>```

must redirect to

```<code>https://www.brainpowernootropics.com/any-page
</code>```

Hope that helps.

Title: Wordpress 301 Redirect not working

Body:
The above links are working fine. The power-focus url is redirecting to the new one.

However, you should redirect using wild card, meaning

https://power-focus.co.uk/any-page

must redirect to

https://www.brainpowernootropics.com/any-page

Hope that helps.


问:
Scanning documents asynchronously using TWAIN
I have a C# program that uses TwainDotNet to scan and receive images from a fujitsu scanner. I have working code, but I want to perform scanning and image transfer asynchronously because the GUI hangs until the scan process is complete.

I attempted to follow the guidelines from this post's accepted solution using this code:

```<code>public void StartScanning()
{
    // Run the scanner from a separate thread
    Task.Run(() => ScanThread());
}

private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Twain twain = new Twain(new WinFormsWindowMessageHook(new Form()));
    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}
</code>```

The code inside ScanThread() is technically correct, because it works outside of the call to Task.Run() (meaning it runs fine on the GUI thread). However, ScanThread() does not work if called from a new thread. The scanner hardware never begins to scan images, let alone transfer them.

Does anyone know of a concrete way to scan and transfer images asynchronously using TWAIN?

答:
I suspect the "simple" answer is "you can't".

The more involved answer is that "twain" (or possibly "GetScanSettings" - what does this do?) is likely to require operations to be performed on the UI thread.

See: TwainDotNet Scanning using TWAIN with BackgroundWorker

However, it might be possible, using the code you've got, except that the form you create likely goes out of scope almost immediately if the references are weak (such as event delegate).

Try adding a Thread Safe list or dictionary, adding your form to it when you create it, and removing it in Twain_ScanningComplete.

Hmm.
Actually, try

```<code>private ConcurrentDictionary<Twain,Form> m_References = new ConcurrentDictionary<Twain,Form>();

private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Form frm = new Form();
    Twain twain = new Twain(new WinFormsWindowMessageHook(frm));
    m_References.Add(twain, frm);

    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}

private void Twain_ScanningComplete(object sender, ScanningCompleteEventArgs args)
{
    Form frm;
    m_References.TryRemove((Twain) sender, out frm);
    if(null != frm)
    {
       frm.Close();
    }
}
</code>```

Body:
I have a C# program that uses TwainDotNet to scan and receive images from a fujitsu scanner. I have working code, but I want to perform scanning and image transfer asynchronously because the GUI hangs until the scan process is complete.

I attempted to follow the guidelines from this post's accepted solution using this code:

public void StartScanning()
{
    // Run the scanner from a separate thread
    Task.Run(() => ScanThread());
}

private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Twain twain = new Twain(new WinFormsWindowMessageHook(new Form()));
    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}

The code inside ScanThread() is technically correct, because it works outside of the call to Task.Run() (meaning it runs fine on the GUI thread). However, ScanThread() does not work if called from a new thread. The scanner hardware never begins to scan images, let alone transfer them.

Does anyone know of a concrete way to scan and transfer images asynchronously using TWAIN?

Body:
I suspect the "simple" answer is "you can't".

The more involved answer is that "twain" (or possibly "GetScanSettings" - what does this do?) is likely to require operations to be performed on the UI thread.

See: TwainDotNet Scanning using TWAIN with BackgroundWorker

However, it might be possible, using the code you've got, except that the form you create likely goes out of scope almost immediately if the references are weak (such as event delegate).

Try adding a Thread Safe list or dictionary, adding your form to it when you create it, and removing it in Twain_ScanningComplete.

Hmm.
Actually, try

private ConcurrentDictionary<Twain,Form> m_References = new ConcurrentDictionary<Twain,Form>();

private void ScanThread()
{
    // Instantiate the Twain object and hookup event handlers
    Form frm = new Form();
    Twain twain = new Twain(new WinFormsWindowMessageHook(frm));
    m_References.Add(twain, frm);

    twain.TransferImage += Twain_TransferImage;
    twain.ScanningComplete += Twain_ScanningComplete;

    // Start the scanning process by passing along pre-defined scan settings
    twain.StartScanning(GetScanSettings());
}

private void Twain_ScanningComplete(object sender, ScanningCompleteEventArgs args)
{
    Form frm;
    m_References.TryRemove((Twain) sender, out frm);
    if(null != frm)
    {
       frm.Close();
    }
}


问:
Let person login to google docs automatically
I write a web application that allow person1 create a document on google docs and share it to person2.

A problem: When person2 click on the link of shared document, google alway redirect to login page.

I can store Person2 UserName and Password in database, but there are any way to let person2 login to google docs automatically?

答:
This is a simple permissions problem, you have set the document to be private or only granted explicit permission to select people.  Try changing the visibility to "public on the web" or "anyone with the link" so no sign in is required.

http://docs.google.com/support/bin/answer.py?answer=183965&hl=en_GB