问:
How to call methods from class located in one python file from another python file
I am creating framework using Selenium and Python.
    My data driven Framework should consist of (so far) 3 files:

```<code>1) Config.py have class Config() that have all the nessesary methods such as:
   def setUp() -
   def tearDown()
   def click()
   def send_keys()

2) data.py - with all data

3) test.py - with all of the steps
</code>```

I am currently working on click() method.

I want to pass 2 parameters to this method, it will use slice()
    to identify what kind of locators i am using and click
    accordingly. Unfortunatly no matter what i do - it keeps
    throwing me some errors.

config.py:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass
        elif elp[flp] == 'li':
            try:
                self.driver.find_element_by_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'na':
            try:
                self.driver.find_element_by_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cs':
            try:
                self.driver.find_element_by_css_selector(elemValue).click()
            except:
                pass
        elif elp[flp] == 'pa':
            try:
                self.driver.find_element_by_partial_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'ta':
            try:
                self.driver.find_element_by_tag_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cl':
            try:
                self.driver.find_element_by_class_name(elemValue).click()
            except:
                pass

    def send_keys(self):
        pass
</code>```

test.py:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
from Setup import Actions

action = Actions()
action.setUp()
</code>```

Error Message:

```<code>Traceback (most recent call last):
  File "/Users/a./Desktop/Automation_Work/correct_PPLS/oop/Test.py", line 9, in <module>
    action = Actions()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.153s]
</code>```

答:
You have to make an instance of the class if you're calling a method that is not static. </p>

<p>I'm not sure if you're using Python 2 or 3, but here's how you make your methods static in 2: https://docs.python.org/2/library/functions.html#staticmethod </p>

Body:
I am creating framework using Selenium and Python.
    My data driven Framework should consist of (so far) 3 files:

1) Config.py have class Config() that have all the nessesary methods such as:
   def setUp() -
   def tearDown()
   def click()
   def send_keys()

2) data.py - with all data

3) test.py - with all of the steps

I am currently working on click() method.

I want to pass 2 parameters to this method, it will use slice()
    to identify what kind of locators i am using and click
    accordingly. Unfortunatly no matter what i do - it keeps
    throwing me some errors.

config.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass
        elif elp[flp] == 'li':
            try:
                self.driver.find_element_by_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'na':
            try:
                self.driver.find_element_by_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cs':
            try:
                self.driver.find_element_by_css_selector(elemValue).click()
            except:
                pass
        elif elp[flp] == 'pa':
            try:
                self.driver.find_element_by_partial_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'ta':
            try:
                self.driver.find_element_by_tag_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cl':
            try:
                self.driver.find_element_by_class_name(elemValue).click()
            except:
                pass

    def send_keys(self):
        pass

test.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
from Setup import Actions

action = Actions()
action.setUp()

Error Message:

Traceback (most recent call last):
  File "/Users/a./Desktop/Automation_Work/correct_PPLS/oop/Test.py", line 9, in <module>
    action = Actions()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.153s]

Body:
You have to make an instance of the class if you're calling a method that is not static.

I'm not sure if you're using Python 2 or 3, but here's how you make your methods static in 2: https://docs.python.org/2/library/functions.html#staticmethod


来源: stackexchange

问:
jquery - post() method gets `not found` error
I want to send an email address to my submit.php as post and receive a response with jquery.

submit.php and index.html are in website root and script.js is in 'js' folder.

my index.html:

<!DOCTYPE html>

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

<input id="email" type="email" placeholder="  Email">

<button id="submit-btn">send</button>

```

<p><br/>
my <code>script.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(()=>{
    $("#submit-btn").click(()=>{
        $.post("../submit.php", { user_email: $("#email").val()})
            .done((data)=>{
                alert(data);
            })
            .fail((xhr, status, error)=>{
                alert(error);
            });
    });
});
</code>```

my submit.php:

<?php
$email = (isset($_POST['user_email']) ? $_POST['user_email'] : "nothing");
echo $email;
```

I expect the output to be my email address, but the actual output is not found.
I think my request has failed

答:
Since you say that both files are in the same folder, there is no need for the ../ in front of your request.

```<code>$.post("../submit.php", { user_email: $("#email").val()})
</code>```

```<code>$.post("submit.php", { user_email: $("#email").val()})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to send an email address to my submit.php as post and receive a response with jquery.

submit.php and index.html are in website root and script.js is in 'js' folder.

my index.html:

<!DOCTYPE html>

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

<input id="email" type="email" placeholder="  Email">

<button id="submit-btn">send</button>

my script.js:

$(document).ready(()=>{
    $("#submit-btn").click(()=>{
        $.post("../submit.php", { user_email: $("#email").val()})
            .done((data)=>{
                alert(data);
            })
            .fail((xhr, status, error)=>{
                alert(error);
            });
    });
});

my submit.php:

<?php
$email = (isset($_POST['user_email']) ? $_POST['user_email'] : "nothing");
echo $email;

I expect the output to be my email address, but the actual output is not found.
I think my request has failed

Body:
Since you say that both files are in the same folder, there is no need for the ../ in front of your request.

$.post("../submit.php", { user_email: $("#email").val()})

$.post("submit.php", { user_email: $("#email").val()})


问:
Interate through multiple dictionaries in a Pickle file
I must to use pickle to store some data. I've created a class to handle the i/o of the data, one the functions is resposible for loading the data and print all the informations, but when I call the function to print out the data, it only interates through the first dictionary. All the inputs are being saved (as I openned the pickle file and could see some data related to other inputs).

I've checked some of the stackoverflow questions like: Iterating over dictionaries using 'for' loops and Best way to loop through multiple dictionaries in Python but none of the examples  gave me the expected output.

This is the DataBase class which is resposible to handle pickle:

```<code>
import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            return loaded_file

    def PrintFile(self):
        for k, v in self.Load().items():
            print(f"{k} {v}")

</code>```

This is the code I've written for testing the class:

```<code>from DataBase import DataBase as DB

dict0 = {1:'A', 2:'E', 3:'I', 4:'O', 5:'U'}
dict1 = {0:"Water", 1:"Fire", 2:"Air", 3:"Sand"}
db = DB("test")
db.Create(dict0)
db.Create(dict1)
db.PrintFile()
</code>```

I expected the output to be:

```<code>1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand
</code>```

However the output I get is:

```<code>1 A
2 E
3 I
4 O
5 U
</code>```

The whole information is being saved, when I open the pickle file with a text ediot, I can see some o the information stored there:

��#}�(K�A�K�E�K�I�K�O�K�U�u.��)}�(K�Water�K�Fire�K�Air�K�Sand�u

We can see for example Air in the file.

What can I do to have the expected output?

答:
You can run pickle.load() on the same file multiple times.

Like this:

```<code>import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            loaded_file2 = pickle.load(this_file)
            return [loaded_file, loaded_file2]

    def PrintFile(self):
        for i in self.Load():
            for k, v in i.items():
                print(f"{k} {v}")

if __name__ == '__main__':
    # from DataBase import DataBase as DB
    dict0 = {1: 'A', 2: 'E', 3: 'I', 4:'O', 5: 'U'}
    dict1 = {0: "Water", 1: "Fire", 2: "Air", 3: "Sand"}
    db = DataBase("test")
    db.Create(dict0)
    db.Create(dict1)
    db.PrintFile()
</code>```

Gives the following output:

```<code>1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand
</code>```

Body:
I must to use pickle to store some data. I've created a class to handle the i/o of the data, one the functions is resposible for loading the data and print all the informations, but when I call the function to print out the data, it only interates through the first dictionary. All the inputs are being saved (as I openned the pickle file and could see some data related to other inputs).

I've checked some of the stackoverflow questions like: Iterating over dictionaries using 'for' loops and Best way to loop through multiple dictionaries in Python but none of the examples  gave me the expected output.

This is the DataBase class which is resposible to handle pickle:

import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            return loaded_file

    def PrintFile(self):
        for k, v in self.Load().items():
            print(f"{k} {v}")

This is the code I've written for testing the class:

from DataBase import DataBase as DB

dict0 = {1:'A', 2:'E', 3:'I', 4:'O', 5:'U'}
dict1 = {0:"Water", 1:"Fire", 2:"Air", 3:"Sand"}
db = DB("test")
db.Create(dict0)
db.Create(dict1)
db.PrintFile()

I expected the output to be:

1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand

However the output I get is:

1 A
2 E
3 I
4 O
5 U

The whole information is being saved, when I open the pickle file with a text ediot, I can see some o the information stored there:

��#}�(K�A�K�E�K�I�K�O�K�U�u.��)}�(K�Water�K�Fire�K�Air�K�Sand�u

We can see for example Air in the file.

What can I do to have the expected output?

Body:
You can run pickle.load() on the same file multiple times.

Like this:

import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            loaded_file2 = pickle.load(this_file)
            return [loaded_file, loaded_file2]

    def PrintFile(self):
        for i in self.Load():
            for k, v in i.items():
                print(f"{k} {v}")

if __name__ == '__main__':
    # from DataBase import DataBase as DB
    dict0 = {1: 'A', 2: 'E', 3: 'I', 4:'O', 5: 'U'}
    dict1 = {0: "Water", 1: "Fire", 2: "Air", 3: "Sand"}
    db = DataBase("test")
    db.Create(dict0)
    db.Create(dict1)
    db.PrintFile()

Gives the following output:

1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand


问:
How to detect scroll direction in ionic 4
I want to hide and show my tab bar on scroll. Wanna hide it when user scrolls down and show it when they scroll up. How to determine the direction in the onScroll method?

Here below my onScroll function:

```<code>onScroll($event: CustomEvent<ScrollDetail>) {
    if ($event && $event.detail && $event.detail.scrollTop) {
        let scrollTop = $event.detail.scrollTop;
        console.log($event, scrollTop);
        document.querySelector('ion-tab-bar').style.display = 'none';
    }
}
</code>```

答:
I think you just need to enable scroll events (Ionic 4 requires it) on ion-content element and bind ionScroll event to your method + bind your tab visibility to a variable (I used footer for this example):

```<code><ion-content padding [scrollEvents]="true" (ionScroll)="onScroll($event)">
  <ion-list>
    <ion-item *ngFor="let item of [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]">
      I am item # {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

<ion-footer [hidden]="footerHidden">
  <ion-toolbar>Hi, I am footer, I hide on scroll down, I am revealed on scroll up</ion-toolbar>
</ion-footer>
</code>```

Now your ts file can be something like this:

```<code>  ///
  footerHidden: boolean;

  constructor(
  ) {}

  onScroll(event) {
    // used a couple of "guards" to prevent unnecessary assignments if scrolling in a direction and the var is set already:
    if (event.detail.deltaY > 0 && this.footerHidden) return;
    if (event.detail.deltaY < 0 && !this.footerHidden) return;
    if (event.detail.deltaY > 0) {
      console.log("scrolling down, hiding footer...");
      this.footerHidden = true;
    } else {
      console.log("scrolling up, revealing footer...");
      this.footerHidden = false;
    };
  };
  ///
</code>```

See demo here:

https://stackblitz.com/edit/ionic-v4-euwnrg

UPDATE FOR TABS:

create new tabs app with ionic (ionic start myTabsApp, then chose tabs starter)

Then create shared service (ionic g, then generate a service) so that your tabs hidden flag boolean was available across many pages as needed:

```<code>import { Injectable } from '@angular/core';

@Injectable({   providedIn: 'root' }) export class FoundationService {

  public hiddenTabs: boolean;

  constructor() { }
}
</code>```

Then import foundation service into your tab1 and do changes to your template:

```<code><ion-header>
  <ion-toolbar>
    <ion-title>
      Tab One
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding [scrollEvents]="true" (ionScroll)="onScroll($event)">
    <ion-list>
      <ion-item *ngFor="let item of [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]">
        I am item # {{ item }}
      </ion-item>
    </ion-list>
</ion-content>
</code>```

Then update your tab1 ts:

```<code>import { Component } from '@angular/core'; import { FoundationService } from '../services/foundation.service';

@Component({   selector: 'app-tab1',   templateUrl: 'tab1.page.html',   styleUrls: ['tab1.page.scss'] }) export class Tab1Page {

  constructor(private foundation: FoundationService) {}

  onScroll(event) {
    // used a couple of "guards" to prevent unnecessary assignments if scrolling in a direction and the var is set already:
    if (event.detail.deltaY > 0 && this.foundation.hiddenTabs) return;
    if (event.detail.deltaY < 0 && !this.foundation.hiddenTabs) return;
    if (event.detail.deltaY > 0) {
      console.log("scrolling down, hiding footer...");
      this.foundation.hiddenTabs = true;
    } else {
      console.log("scrolling up, revealing footer...");
      this.foundation.hiddenTabs = false;
    };   };

}
</code>```

Now update tabs.ts to import foundation service:

```<code>import { Component } from '@angular/core';
import { FoundationService } from '../services/foundation.service';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {

  constructor(private foundation: FoundationService) {

  }

}
</code>```

And also update template of tabs page to bind the boolean:

```<code><ion-tabs>

  <ion-tab-bar slot="bottom" [hidden]="foundation.hiddenTabs">
    <ion-tab-button tab="tab1">
      <ion-icon name="flash"></ion-icon>
      <ion-label>Tab One</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="apps"></ion-icon>
      <ion-label>Tab Two</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="send"></ion-icon>
      <ion-label>Tab Three</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>
</code>```

Then run ionic serve and try it out.
The method I wrote is rather raw and naive so you way want to update / tune logic of what changes in the scrolling event should call for boolean to be false /true;

Body:
I want to hide and show my tab bar on scroll. Wanna hide it when user scrolls down and show it when they scroll up. How to determine the direction in the onScroll method?

Here below my onScroll function:

onScroll($event: CustomEvent<ScrollDetail>) {
    if ($event && $event.detail && $event.detail.scrollTop) {
        let scrollTop = $event.detail.scrollTop;
        console.log($event, scrollTop);
        document.querySelector('ion-tab-bar').style.display = 'none';
    }
}

Body:
I think you just need to enable scroll events (Ionic 4 requires it) on ion-content element and bind ionScroll event to your method + bind your tab visibility to a variable (I used footer for this example):

<ion-content padding [scrollEvents]="true" (ionScroll)="onScroll($event)">
  <ion-list>
    <ion-item *ngFor="let item of [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]">
      I am item # {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

<ion-footer [hidden]="footerHidden">
  <ion-toolbar>Hi, I am footer, I hide on scroll down, I am revealed on scroll up</ion-toolbar>
</ion-footer>

Now your ts file can be something like this:

  ///
  footerHidden: boolean;

  constructor(
  ) {}

  onScroll(event) {
    // used a couple of "guards" to prevent unnecessary assignments if scrolling in a direction and the var is set already:
    if (event.detail.deltaY > 0 && this.footerHidden) return;
    if (event.detail.deltaY < 0 && !this.footerHidden) return;
    if (event.detail.deltaY > 0) {
      console.log("scrolling down, hiding footer...");
      this.footerHidden = true;
    } else {
      console.log("scrolling up, revealing footer...");
      this.footerHidden = false;
    };
  };
  ///

See demo here:

https://stackblitz.com/edit/ionic-v4-euwnrg

UPDATE FOR TABS:

create new tabs app with ionic (ionic start myTabsApp, then chose tabs starter)

Then create shared service (ionic g, then generate a service) so that your tabs hidden flag boolean was available across many pages as needed:

import { Injectable } from '@angular/core';

@Injectable({   providedIn: 'root' }) export class FoundationService {

  public hiddenTabs: boolean;

  constructor() { }
}

Then import foundation service into your tab1 and do changes to your template:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Tab One
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding [scrollEvents]="true" (ionScroll)="onScroll($event)">
    <ion-list>
      <ion-item *ngFor="let item of [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]">
        I am item # {{ item }}
      </ion-item>
    </ion-list>
</ion-content>

Then update your tab1 ts:

import { Component } from '@angular/core'; import { FoundationService } from '../services/foundation.service';

@Component({   selector: 'app-tab1',   templateUrl: 'tab1.page.html',   styleUrls: ['tab1.page.scss'] }) export class Tab1Page {

  constructor(private foundation: FoundationService) {}

  onScroll(event) {
    // used a couple of "guards" to prevent unnecessary assignments if scrolling in a direction and the var is set already:
    if (event.detail.deltaY > 0 && this.foundation.hiddenTabs) return;
    if (event.detail.deltaY < 0 && !this.foundation.hiddenTabs) return;
    if (event.detail.deltaY > 0) {
      console.log("scrolling down, hiding footer...");
      this.foundation.hiddenTabs = true;
    } else {
      console.log("scrolling up, revealing footer...");
      this.foundation.hiddenTabs = false;
    };   };

}

Now update tabs.ts to import foundation service:

import { Component } from '@angular/core';
import { FoundationService } from '../services/foundation.service';

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss']
})
export class TabsPage {

  constructor(private foundation: FoundationService) {

  }

}

And also update template of tabs page to bind the boolean:

<ion-tabs>

  <ion-tab-bar slot="bottom" [hidden]="foundation.hiddenTabs">
    <ion-tab-button tab="tab1">
      <ion-icon name="flash"></ion-icon>
      <ion-label>Tab One</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab2">
      <ion-icon name="apps"></ion-icon>
      <ion-label>Tab Two</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="tab3">
      <ion-icon name="send"></ion-icon>
      <ion-label>Tab Three</ion-label>
    </ion-tab-button>
  </ion-tab-bar>

</ion-tabs>

Then run ionic serve and try it out.
The method I wrote is rather raw and naive so you way want to update / tune logic of what changes in the scrolling event should call for boolean to be false /true;


问:
Is there a way of compiling (i.e. caching) a cupy RawKernel before calling it?
I'm writing a python application that processes a lot of images.
The computation speed of the application is important, thus I'm trying to minimize the execution time by writing cupy kernels.

For the sake of simplicity, assume that I have a cupy raw kernel below.

import cupy as cp

add_kernel = cp.RawKernel(r'''
extern "C" __global__
void add_one(float* dimg, float* y) {
    int j = threadIdx.x;
    int i = blockIdx.x;
    int k = blockDim.x;
    int tid = k*i+j;

    y[tid] = dimg[tid] + 1;
}
''', 'add_one')

if __name__ == '__main__':
    h, w = 192, 256
    dimg_cp = cp.zeros(shape=(h, w), dtype=cp.float32)
    y = cp.zeros(shape=(h, w), dtype=cp.float32)
    add_kernel((h,), (w,), (dimg_cp, y))
    print(y)
```

Here, 'add_kernel' simply copies an input matrix and add one to every element of the copied matrix then return it. It works great but I believe the code can be further optimized in terms of execution speed.

According to the link, when the kernel is called for the first time (i.e. not cached), there will be an overhead for compilation.

I want to avoid this compilation time.
So I want to ask if there is a way of compiling cp.RawKernel prior to calling the kernel for the first time?

Thanks in advance.

答: There is currently no explicit way to precompile the kernel without calling it. One easy solution is just calling it once with a small input. Note that the compiled kernel is also cached to a file, so the overhead only exists at the first execution of the script in the environment.</p>

Body:
I'm writing a python application that processes a lot of images.
The computation speed of the application is important, thus I'm trying to minimize the execution time by writing cupy kernels.

For the sake of simplicity, assume that I have a cupy raw kernel below.

import cupy as cp

add_kernel = cp.RawKernel(r'''
extern "C" __global__
void add_one(float* dimg, float* y) {
    int j = threadIdx.x;
    int i = blockIdx.x;
    int k = blockDim.x;
    int tid = k*i+j;

    y[tid] = dimg[tid] + 1;
}
''', 'add_one')

if __name__ == '__main__':
    h, w = 192, 256
    dimg_cp = cp.zeros(shape=(h, w), dtype=cp.float32)
    y = cp.zeros(shape=(h, w), dtype=cp.float32)
    add_kernel((h,), (w,), (dimg_cp, y))
    print(y)

Here, 'add_kernel' simply copies an input matrix and add one to every element of the copied matrix then return it. It works great but I believe the code can be further optimized in terms of execution speed.

According to the link, when the kernel is called for the first time (i.e. not cached), there will be an overhead for compilation.

I want to avoid this compilation time.
So I want to ask if there is a way of compiling cp.RawKernel prior to calling the kernel for the first time?

Thanks in advance.


问:
Firestore/Nuxt - How do I keep my mutation push from nesting the next set of results?
I am trying to build my app so it does not read all 200+ documents on load but a handful at load and grab the rest as they scroll down.

I have working code that allows me to grab a page of results, say 2, then hit next and grab the next 2 but I want the next 2 to be added to the last so the user can scroll back up.

I am trying to push in my mutation but it's creating a nested mess. It returns 3 with the last having 2.

Mutations

```<code>setAddons(state, payload) {
        state.addons = payload;
      },
      nextAddons(state, payload) {
        state.addons.push(payload);
      },
</code>```

My 2 actions. One loads up with the page to grab first set. The second right now when I hit a button, but hopefully linked to scroll event once I get this sorted.

```<code>async firstAddons({ commit }) {
        let addonsData = [];

        return await db
          .collection('addons')
          .where('publish', '==', true)
          .orderBy('timeUpdated', 'desc')
          .limit(10)
          .get()
          .then(querySnapshot => {
            querySnapshot.forEach(doc => {
              addonsData.push({
                ...doc.data(),
                id: doc.id,
                timeUpdated: doc.data().timeUpdated.toDate(),
                timeCreated: doc.data().timeCreated.toDate()
              });
              let last = querySnapshot.docs[querySnapshot.docs.length - 1];
              commit('setLast', last);
            });
            commit('setAddons', addonsData);
          });
      },

      async nextAddons({ commit, state }) {
        let addonsData = [];

        await db
          .collection('addons')
          .where('publish', '==', true)
          .orderBy('timeUpdated', 'desc')
          .startAfter(state.last.data().timeUpdated)
          .limit(10)
          .get()
          .then(querySnapshot => {
            querySnapshot.forEach(doc => {
              addonsData.push({
                ...doc.data(),
                id: doc.id,
                timeUpdated: doc.data().timeUpdated.toDate(),
                timeCreated: doc.data().timeCreated.toDate()
              });
              let next = querySnapshot.docs[querySnapshot.docs.length - 1];
              commit('setLast', next);
            });
            commit('nextAddons', addonsData);
            console.log(state.addons);
          });
      },
</code>```

What is coming back

```<code>(3) [{…}, {…}, Array(2), __ob__: Observer]
0: {…}
1: {…}
2: Array(2)
  0: {…}
  1: {…}
  length: 2
length: 3
</code>```

Expected results are that the next page of results should be pushed onto the end of the last results and carry on.

Actual results: The array is putting each set into a nested array.

How can I put these together in one continuous array to use in my template?

Thank you

答:
Solved and feel like a dope.

Turns out it was as simple as using spread.

```<code>setAddons(state, payload) {
        state.addons = payload;
      },
      nextAddons(state, payload) {
        state.addons.push(...payload);
      },
</code>```

That is working!

Body:
I am trying to build my app so it does not read all 200+ documents on load but a handful at load and grab the rest as they scroll down.

I have working code that allows me to grab a page of results, say 2, then hit next and grab the next 2 but I want the next 2 to be added to the last so the user can scroll back up.

I am trying to push in my mutation but it's creating a nested mess. It returns 3 with the last having 2.

Mutations

setAddons(state, payload) {
        state.addons = payload;
      },
      nextAddons(state, payload) {
        state.addons.push(payload);
      },

My 2 actions. One loads up with the page to grab first set. The second right now when I hit a button, but hopefully linked to scroll event once I get this sorted.

async firstAddons({ commit }) {
        let addonsData = [];

        return await db
          .collection('addons')
          .where('publish', '==', true)
          .orderBy('timeUpdated', 'desc')
          .limit(10)
          .get()
          .then(querySnapshot => {
            querySnapshot.forEach(doc => {
              addonsData.push({
                ...doc.data(),
                id: doc.id,
                timeUpdated: doc.data().timeUpdated.toDate(),
                timeCreated: doc.data().timeCreated.toDate()
              });
              let last = querySnapshot.docs[querySnapshot.docs.length - 1];
              commit('setLast', last);
            });
            commit('setAddons', addonsData);
          });
      },

      async nextAddons({ commit, state }) {
        let addonsData = [];

        await db
          .collection('addons')
          .where('publish', '==', true)
          .orderBy('timeUpdated', 'desc')
          .startAfter(state.last.data().timeUpdated)
          .limit(10)
          .get()
          .then(querySnapshot => {
            querySnapshot.forEach(doc => {
              addonsData.push({
                ...doc.data(),
                id: doc.id,
                timeUpdated: doc.data().timeUpdated.toDate(),
                timeCreated: doc.data().timeCreated.toDate()
              });
              let next = querySnapshot.docs[querySnapshot.docs.length - 1];
              commit('setLast', next);
            });
            commit('nextAddons', addonsData);
            console.log(state.addons);
          });
      },

What is coming back

(3) [{…}, {…}, Array(2), __ob__: Observer]
0: {…}
1: {…}
2: Array(2)
  0: {…}
  1: {…}
  length: 2
length: 3

Expected results are that the next page of results should be pushed onto the end of the last results and carry on.

Actual results: The array is putting each set into a nested array.

How can I put these together in one continuous array to use in my template?

Thank you

Body:
Solved and feel like a dope.

Turns out it was as simple as using spread.

setAddons(state, payload) {
        state.addons = payload;
      },
      nextAddons(state, payload) {
        state.addons.push(...payload);
      },

That is working!


问:
When Using Redux Saga with React Get This Error .. Uncaught TypeError: getPosts is not a function
Trying to learn how to use Redux Sagas with React. Put together a simple example but it is not working for me.

My code in my App.js file:

```<code>const sagaMiddleware = createSagaMiddleWare();

const store = createStore(
  reducers,
  applyMiddleware(sagaMiddleware)
)

sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
</code>```

Action Creator:

```<code> export const getPosts = () => {
        return  {
           type: 'GET_POSTS'
        }
     };
</code>```

Reducer:

```<code>const combineReducers = (state= {}, action) => {
     switch (action.type) {
       case 'GET_POSTS':
         return { ...state, loading: true};
       default:
         return state;
        }
      }

   export default combineReducers;
</code>```

My Button component where the action should be called onClick

```<code>const ButtonContainer = (getPosts) => (
     <button onClick={() => getPosts()}>Get Posts</button>
)

const mapDispatchToProps = {
  getPosts: getPosts
}

export default connect(null, mapDispatchToProps)(ButtonContainer);
</code>```

Problem is I get this error on page load.

```<code>Uncaught TypeError: getPosts is not a function....
</code>```

Makes sense what the error is saying, it is getting the object instead of the function but not really sure what I need to do for this to work.

Thank you!

答:
The code you have currently is not actually dispatching the getPosts action to your reducer.

Change you mapDispatchToProps to:

```<code>const mapDispatchToProps = dispatch => {
  getPosts: bindActionCreators(getPosts, dispatch)
}
</code>```

You'll also need:

```<code>import { bindActionCreators, Dispatch } from "redux"
</code>```

Also change your ButtonContainer to:

```<code>const ButtonContainer = props => (
     <button onClick={() => props.getPosts()}>Get Posts</button>
)
</code>```

More info on dispatching can be found in this good documentation.

Body:
Trying to learn how to use Redux Sagas with React. Put together a simple example but it is not working for me.

My code in my App.js file:

const sagaMiddleware = createSagaMiddleWare();

const store = createStore(
  reducers,
  applyMiddleware(sagaMiddleware)
)

sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

Action Creator:

 export const getPosts = () => {
        return  {
           type: 'GET_POSTS'
        }
     };

Reducer:

const combineReducers = (state= {}, action) => {
     switch (action.type) {
       case 'GET_POSTS':
         return { ...state, loading: true};
       default:
         return state;
        }
      }

   export default combineReducers;

My Button component where the action should be called onClick

const ButtonContainer = (getPosts) => (
     <button onClick={() => getPosts()}>Get Posts</button>
)

const mapDispatchToProps = {
  getPosts: getPosts
}

export default connect(null, mapDispatchToProps)(ButtonContainer);

Problem is I get this error on page load.

Uncaught TypeError: getPosts is not a function....

Makes sense what the error is saying, it is getting the object instead of the function but not really sure what I need to do for this to work.

Thank you!

Body:
The code you have currently is not actually dispatching the getPosts action to your reducer.

Change you mapDispatchToProps to:

const mapDispatchToProps = dispatch => {
  getPosts: bindActionCreators(getPosts, dispatch)
}

You'll also need:

import { bindActionCreators, Dispatch } from "redux"

Also change your ButtonContainer to:

const ButtonContainer = props => (
     <button onClick={() => props.getPosts()}>Get Posts</button>
)

More info on dispatching can be found in this good documentation.


问:
Why am I getting this error with socket_read()?
I have the following code: http://pastebin.com/U9qYSmET

When I try to telnet into my server and port with

```<code>telnet localhost 6667
</code>```

I get the following error:

PHP Warning:  socket_read(): unable to read from socket [107]: Transport endpoint is not connected in /var/www/php-irc/proxy.php on line 91

Anyone have any ideas why I'm getting this error?

Code:

```<code><?php

if(!defined('SOCKET_ADDRESS')) {
    define('SOCKET_ADDRESS', '127.0.0.1');
}

if(!defined('SOCKET_PORT')) {
    define('SOCKET_PORT', '6667');
}

if(!defined('MAX_CLIENTS')) {
    define('MAX_CLIENTS', '10');
}
set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, SOCKET_ADDRESS, SOCKET_PORT) or die('Could not bind to address ' . SOCKET_ADDRESS . ' on port ' . SOCKET_PORT . "!\n");
socket_listen($socket, MAX_CLIENTS) or die ("Could not setup socket listener!\n");

// setup read socket array
$read = array();

// client array w/ default initial socket
$clients = array('0' => array('socket' => $socket));

// force debug at first run..
$debug = true;
$time = time();
printf('Time: %d%s', $time, "\n");
while(true) {

    if(time() - $time >= 10) {
        $time = time();
        printf('Time: %d%s', $time, "\n");
        $debug = true;
    }
    if($debug === true) {
        printf('Debug: %s%s', $debug, "\n");
    }
    // $read[0] = $socket;
    if($debug) {
        var_dump($read);
    }

    // Handle clients
    for($i = 0; $i < count($clients); $i++) {
        if(isset($clients[$i]['socket'])) {
            if($debug === true) {
                printf('Setting socket %d to client %d%s', $i, $i, "\n");
            }
            $read[$i] = $clients[$i]['socket'];
        }
    }
    if($debug) {
        var_dump($read);
    }
    // Any changed sockets?
    // $write and $except are only placeholders
    $changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0);
    if($debug === true){
        printf('Changed sockets: %d%s', $changed_sockets, "\n");
    }
    // Handle new connections
    if(in_array($socket, $read)) {
        for($i = 0; $i < MAX_CLIENTS; $i++) {
            if(!isset($clients[$i])) {
                $clients[$i]['socket'] = socket_accept($socket);
                socket_getpeername($clients[$i]['socket'],$ip);
                $clients[$i]['ip'] = $ip;
                printf('Accepting connection into client %d from %s%s', $i, $ip, "\n");
                break;
            }
            // } elseif($i == MAX_CLIENTS - 1) {
                // echo 'Too many clients connected!', "\n";
            // }
            if($changed_sockets < 1) {
                continue;
            }
        }
    }
    if($debug) {
        var_dump($clients);
    }

    for($i = 0; $i < count($clients); $i++) {
        $client = $clients[$i];
        // Has our client socket seen any changes?
        if(in_array($client['socket'], $read)) {
            printf('Client %d has changed! Reading...%s', $i, "\n");
            $data = socket_read($client['socket'], 1024);
            if($data === false) {
                $error = socket_strerror(socket_last_error());
                printf('An error occured...%s%s', $error, "\n");

            }
            printf("Read raw data %s from client %i%s", $data, $i, "\n");
            if($data === null) {
                // disconnected
                unset($clients[$i]);
            }

            $data = trim($data);
            if($data == 'exit') {
                printf('Received exit command from client%s', "\n");
                socket_close($clients[$i]['socket']);
            } elseif($data) {
                // Strip whitespace
                printf('Received data: %s from client %d%s', $data, $i, "\n");
                $output = sprintf('%s%s%s', $data, "\n", chr(0));
                socket_write($client['socket'], $output);
            }
        }
    }

    // reset debug
    $debug = false;
}

socket_close($socket);
</code>```

答:
The problem was it was trying to read from $clients[0]. Which isn't a valid client to be reading from. I simply changed the last two for loops to start $i at 1.

So far in my testing, this doesn't seem to be having any adverse affects. The error is gone, and I all of the client instances appear to be working fine.

ContentLicense: CC BY-SA 3.0

Body:
I have the following code: http://pastebin.com/U9qYSmET

When I try to telnet into my server and port with

telnet localhost 6667

I get the following error:

PHP Warning:  socket_read(): unable to read from socket [107]: Transport endpoint is not connected in /var/www/php-irc/proxy.php on line 91

Anyone have any ideas why I'm getting this error?

Code:

<?php

if(!defined('SOCKET_ADDRESS')) {
    define('SOCKET_ADDRESS', '127.0.0.1');
}

if(!defined('SOCKET_PORT')) {
    define('SOCKET_PORT', '6667');
}

if(!defined('MAX_CLIENTS')) {
    define('MAX_CLIENTS', '10');
}
set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, SOCKET_ADDRESS, SOCKET_PORT) or die('Could not bind to address ' . SOCKET_ADDRESS . ' on port ' . SOCKET_PORT . "!\n");
socket_listen($socket, MAX_CLIENTS) or die ("Could not setup socket listener!\n");

// setup read socket array
$read = array();

// client array w/ default initial socket
$clients = array('0' => array('socket' => $socket));

// force debug at first run..
$debug = true;
$time = time();
printf('Time: %d%s', $time, "\n");
while(true) {

    if(time() - $time >= 10) {
        $time = time();
        printf('Time: %d%s', $time, "\n");
        $debug = true;
    }
    if($debug === true) {
        printf('Debug: %s%s', $debug, "\n");
    }
    // $read[0] = $socket;
    if($debug) {
        var_dump($read);
    }

    // Handle clients
    for($i = 0; $i < count($clients); $i++) {
        if(isset($clients[$i]['socket'])) {
            if($debug === true) {
                printf('Setting socket %d to client %d%s', $i, $i, "\n");
            }
            $read[$i] = $clients[$i]['socket'];
        }
    }
    if($debug) {
        var_dump($read);
    }
    // Any changed sockets?
    // $write and $except are only placeholders
    $changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0);
    if($debug === true){
        printf('Changed sockets: %d%s', $changed_sockets, "\n");
    }
    // Handle new connections
    if(in_array($socket, $read)) {
        for($i = 0; $i < MAX_CLIENTS; $i++) {
            if(!isset($clients[$i])) {
                $clients[$i]['socket'] = socket_accept($socket);
                socket_getpeername($clients[$i]['socket'],$ip);
                $clients[$i]['ip'] = $ip;
                printf('Accepting connection into client %d from %s%s', $i, $ip, "\n");
                break;
            }
            // } elseif($i == MAX_CLIENTS - 1) {
                // echo 'Too many clients connected!', "\n";
            // }
            if($changed_sockets < 1) {
                continue;
            }
        }
    }
    if($debug) {
        var_dump($clients);
    }

    for($i = 0; $i < count($clients); $i++) {
        $client = $clients[$i];
        // Has our client socket seen any changes?
        if(in_array($client['socket'], $read)) {
            printf('Client %d has changed! Reading...%s', $i, "\n");
            $data = socket_read($client['socket'], 1024);
            if($data === false) {
                $error = socket_strerror(socket_last_error());
                printf('An error occured...%s%s', $error, "\n");

            }
            printf("Read raw data %s from client %i%s", $data, $i, "\n");
            if($data === null) {
                // disconnected
                unset($clients[$i]);
            }

            $data = trim($data);
            if($data == 'exit') {
                printf('Received exit command from client%s', "\n");
                socket_close($clients[$i]['socket']);
            } elseif($data) {
                // Strip whitespace
                printf('Received data: %s from client %d%s', $data, $i, "\n");
                $output = sprintf('%s%s%s', $data, "\n", chr(0));
                socket_write($client['socket'], $output);
            }
        }
    }

    // reset debug
    $debug = false;
}

socket_close($socket);


问:
Use ItemChange event handler to update an item property
I have a list of contacts in Outlook updated through other program. I don't touch the list myself. Every time a contact is changed, I want to update company name through VBA.

```<code>Public WithEvents objNewContact As Items
Public Sub Initialize_handler()
    Set objNewContact = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
End Sub
</code>```

If I edit the contact myself through Outlook, it works. If edited through other source, it shows the MsgBox telling me that the company name has been changed, but the change is not saved.

If I add "Item.Save" it creates an infinite loop.

```<code>Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
    Item.Save
End Sub
</code>```

答:
You could toggle the ItemChange event handler off before changing Item.CompanyName.

```<code>Public Sub objNewContact_ItemChange(ByVal Item As Object)

    ' event handler off
    Set objNewContact = Nothing

    Item.CompanyName = "NewCompanyName"
    Item.Save

    MsgBox "Company name changed to " & Item.CompanyName

    ' event handler on
    Initialize_handler

End Sub
</code>```

Body:
I have a list of contacts in Outlook updated through other program. I don't touch the list myself. Every time a contact is changed, I want to update company name through VBA.

Public WithEvents objNewContact As Items
Public Sub Initialize_handler()
    Set objNewContact = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
End Sub

If I edit the contact myself through Outlook, it works. If edited through other source, it shows the MsgBox telling me that the company name has been changed, but the change is not saved.

If I add "Item.Save" it creates an infinite loop.

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
    Item.Save
End Sub

Body:
You could toggle the ItemChange event handler off before changing Item.CompanyName.

Public Sub objNewContact_ItemChange(ByVal Item As Object)

    ' event handler off
    Set objNewContact = Nothing

    Item.CompanyName = "NewCompanyName"
    Item.Save

    MsgBox "Company name changed to " & Item.CompanyName

    ' event handler on
    Initialize_handler

End Sub


问:
Print received messages while prompting user for input in a chat program
I am creating a chat application on Python without the use of non standard libraries and I've encountered a problem while prompting a user for a message and a message comes through.

```<code>def printit():
    threading.Timer(5.0, printit).start()
    print("This is a test message!")

def prompt():
    while True:
        msg = input("Your Message: ")

def main():
    thread_prompt = threading.Thread(target = prompt)
    thread_prompt.start()
    printit()
</code>```

While I would like any received messages to display on a different line from the prompt, what happens at the moment is this (e.g. User is trying to type and send "hello world"):

```<code>Your Message: hello worThis is a test message!
</code>```

While I want it to be like the following:

```<code>This is a test message!
Your Message: hello wor
</code>```

Is this possible to achieve without the use of external libraries? Also, I've yet to implement sockets/server that sends messages back so for now I am using threading.Timer to imitate a message that comes through every 5 seconds.

答:
I do not think you can easily do what you want in this particular order (the test message followed by the prompt), but the reverse order (the prompt followed by the test message) is easily achievable. Instead of printing the test message, queue it and later print all queued messages when the user presses Enter.

```<code>queue = []
lock = threading.Lock()

def printit():
    threading.Timer(5.0, printit).start()
    lock.acquire()
    queue.append("This is a test message!")
    lock.release()

def prompt():
    global queue
    while True:
        msg = input("Your Message: ")
        lock.acquire()
        while queue:
            print(queue.pop())
        lock.release()

def main():
    thread_prompt = threading.Thread(target = prompt)
    thread_prompt.start()
    printit()
</code>```

Body:
I am creating a chat application on Python without the use of non standard libraries and I've encountered a problem while prompting a user for a message and a message comes through.

def printit():
    threading.Timer(5.0, printit).start()
    print("This is a test message!")

def prompt():
    while True:
        msg = input("Your Message: ")

def main():
    thread_prompt = threading.Thread(target = prompt)
    thread_prompt.start()
    printit()

While I would like any received messages to display on a different line from the prompt, what happens at the moment is this (e.g. User is trying to type and send "hello world"):

Your Message: hello worThis is a test message!

While I want it to be like the following:

This is a test message!
Your Message: hello wor

Is this possible to achieve without the use of external libraries? Also, I've yet to implement sockets/server that sends messages back so for now I am using threading.Timer to imitate a message that comes through every 5 seconds.

Body:
I do not think you can easily do what you want in this particular order (the test message followed by the prompt), but the reverse order (the prompt followed by the test message) is easily achievable. Instead of printing the test message, queue it and later print all queued messages when the user presses Enter.

queue = []
lock = threading.Lock()

def printit():
    threading.Timer(5.0, printit).start()
    lock.acquire()
    queue.append("This is a test message!")
    lock.release()

def prompt():
    global queue
    while True:
        msg = input("Your Message: ")
        lock.acquire()
        while queue:
            print(queue.pop())
        lock.release()

def main():
    thread_prompt = threading.Thread(target = prompt)
    thread_prompt.start()
    printit()


问:
join previous line with next depending of pattern of previous line
I have this Input:

```<code>1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g
</code>```

I want this output using sed command

```<code>1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g
</code>```

I'm trying this without success

```<code>sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file
</code>```

答:
Made it simpler with awk:

```<code>awk 'NF==2 {printf("%s ", $0); next} 1' file
</code>```

Basically, "Don't print a newline if there are <s>only</s> exactly two fields."

Body:
I have this Input:

1 a
a
2 b b
3 c
c
4 d d
5 e e
6 f
f
7 g
g

I want this output using sed command

1 a a
2 b b
3 c c
4 d d
5 e e
6 f f
7 g g

I'm trying this without success

sed '/^[^0-9]/ x; N; { s/\n/ / }; n' file

Body:
Made it simpler with awk:

awk 'NF==2 {printf("%s ", $0); next} 1' file

Basically, "Don't print a newline if there are <s>only</s> exactly two fields."


问:
How to extract part of a string with slash constraints?
Hello I have some strings named like this:

BURGERDAY / PPA / This is a burger fest

I've tried using regex to get it but I can't seem to get it right.

The output should just get the final string of This is a burger fest (without the first whitespace)

答:
Note: This is a pythonish answer (my mistake).  I'll leave this for it's value as it could apply many languages

Another approach is to split it and then rejoin it.

```<code>data = 'BURGERDAY / PPA / This is a burger fest'
</code>```

Here it is in four steps:

```<code>parts = data.split('/')   # break into a list by '/'
parts = parts[2:]         # get a new list excluding the first 2 elements
output = '/'.join(parts)  # join them back together with a '/'
output = output.strip()   # strip spaces from each side of the output
</code>```

And in one concise line:

```<code>output= str.join('/', data.split('/')[2:]).strip()
</code>```

Note: I feel that str.join(..., ...) is more readable than '...'.join(...) in some contexts.  It is the identical call though.

Body:
Note: This is a pythonish answer (my mistake).  I'll leave this for it's value as it could apply many languages

Another approach is to split it and then rejoin it.

data = 'BURGERDAY / PPA / This is a burger fest'

Here it is in four steps:

parts = data.split('/')   # break into a list by '/'
parts = parts[2:]         # get a new list excluding the first 2 elements
output = '/'.join(parts)  # join them back together with a '/'
output = output.strip()   # strip spaces from each side of the output

And in one concise line:

output= str.join('/', data.split('/')[2:]).strip()

Note: I feel that str.join(..., ...) is more readable than '...'.join(...) in some contexts.  It is the identical call though.


问:
Postgresql: Is there any way to read from a PGDATA/base directory and import the data to a new database?
My database crashed, but I backed up PGDATA/base earlier, so I lost the
database structure and only have the base directory(maybe part of it),
so I decide to build a new database same as the old one since I lost
the structure file, but I don't know whether the data in the base
directory can be imported to the new database's table, is there any way
can do that?

Last check I have /etc/postgresql/10/main folder and
/var/lib/postgresql/10/main/ folder of the crashed database, and data folder like I said, I only have the base

Working on Ubuntu16.04 Postgresql-10

答:
If you only have $PGDATA/base, you are missing

The commit log that says which transaction was committed and which aborted, so you don't know what rows are visible.

The control file global/pg_control that tells you the state of the database and the last checkpoint and other important information.

The transaction log.

The global tablespace that contains the users and tablespaces.

In short, your database is toast. Perhaps a specialist can rescue some of the data.


问:
Why private function can't access member variable within Javascript object?
I'm having issues understanding scoping/access of fields defined with a JavaScript object.

Consider the following sample JavaScript object definition:

```<code>function SampleObject(controlName) {

    var _controlName = controlName;

    this.Display1 = function() {
        console.log(_controlName);
    }

    this.Display2 = function() {
        Display3();
    }

    Display3 = function () {
        console.log(_controlName);
    }
}
</code>```

Now consider running the above object with the following example:

```<code>var a = new SampleObject("Bob");
var b = new SampleObject("Fred");

a.Display1();  //==> Displays "Bob"
b.Display1();  //==> Displays "Fred"

a.Display2();  //==> Displays "Fred"
b.Display2();  //==> Displays "Fred"
</code>```

What I'm having difficulty understanding is how to access object fields (properties) from within private functions defined within my object.
Within my example, I am confused as to why _controlName has the value "Fred" when it is displayed via Display2() for both objects a and b.

I suspect that is either an issue with how _controlName and/or Display3() is defined or I am unclear how scoping would work in this instance. Can someone please share some light on this?

Thanks,JohnB

答:
In some other languages such as Java (where I hail from), when you are inside a method on an object, the this is implicit. In Javascript, this is NOT the case.

When you are assigning to this.Display1 and this.Display2, you are creating properties with those names on the object pointed at by this. Because of new, this is a different object each time.

However, what's happening when you assign to Display3 is that you are assigning to a global variable. If it doesn't exist, it is created for you. When you call new SampleObject("Fred"); the function which originally logged "Bob" is now gone, replaced by one which prints "Fred".

If you add 'use strict'; to the top of your SampleObject function, which suppresses this "implicit global" behavior, you get a reference error when you try to assign to the never-declared variable Display3.

Body:
I'm having issues understanding scoping/access of fields defined with a JavaScript object.

Consider the following sample JavaScript object definition:

function SampleObject(controlName) {

    var _controlName = controlName;

    this.Display1 = function() {
        console.log(_controlName);
    }

    this.Display2 = function() {
        Display3();
    }

    Display3 = function () {
        console.log(_controlName);
    }
}

Now consider running the above object with the following example:

var a = new SampleObject("Bob");
var b = new SampleObject("Fred");

a.Display1();  //==> Displays "Bob"
b.Display1();  //==> Displays "Fred"

a.Display2();  //==> Displays "Fred"
b.Display2();  //==> Displays "Fred"

What I'm having difficulty understanding is how to access object fields (properties) from within private functions defined within my object.
Within my example, I am confused as to why _controlName has the value "Fred" when it is displayed via Display2() for both objects a and b.

I suspect that is either an issue with how _controlName and/or Display3() is defined or I am unclear how scoping would work in this instance. Can someone please share some light on this?

Thanks,JohnB


问:
Programmatically reading the output of Hadoop Mapreduce Program
This may be a basic question, but I could not find an answer for it on Google.

I have a map-reduce job that creates multiple output files in its output directory.
My Java application executes this job on a remote hadoop cluster and after the job is finished, it needs to read the output programatically using org.apache.hadoop.fs.FileSystem API. Is it possible?

The application knows the output directory, but not the names of the output files generated by the map-reduce job. It seems there is no way to programatically list the contents of a directory in the hadoop file system API. How will the output files be read?

It seems such a commonplace scenario, that I am sure it has a solution. But I am missing something very obvious.

答:
The method you are looking for is called listStatus(Path).
It simply returns all files inside of a Path as a FileStatus array. Then you can simply loop over them create a path object and read it.

```<code>    FileStatus[] fss = fs.listStatus(new Path("/"));
    for (FileStatus status : fss) {
        Path path = status.getPath();
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
        IntWritable key = new IntWritable();
        IntWritable value = new IntWritable();
        while (reader.next(key, value)) {
            System.out.println(key.get() + " | " + value.get());
        }
        reader.close();
    }
</code>```

For Hadoop 2.x you can setup the reader like this:

```<code> SequenceFile.Reader reader =
           new SequenceFile.Reader(conf, SequenceFile.Reader.file(path))
</code>```

Body:
The method you are looking for is called listStatus(Path).
It simply returns all files inside of a Path as a FileStatus array. Then you can simply loop over them create a path object and read it.

    FileStatus[] fss = fs.listStatus(new Path("/"));
    for (FileStatus status : fss) {
        Path path = status.getPath();
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
        IntWritable key = new IntWritable();
        IntWritable value = new IntWritable();
        while (reader.next(key, value)) {
            System.out.println(key.get() + " | " + value.get());
        }
        reader.close();
    }

For Hadoop 2.x you can setup the reader like this:

 SequenceFile.Reader reader =
           new SequenceFile.Reader(conf, SequenceFile.Reader.file(path))


答:
Here's the explanation.

In the first call, new SampleObject("Bob"); the global variable Display3 gets set to a function that console-logs the value Bob.

In the second call, new SampleObject("Fred"); the global variable Display3 gets set to a function that console-logs the value Fred.

Now your Display1 is actually a method. Every object you create gets its own Display1 property. So Bob's Display1 logs Bob and Fred's logs Fred.

But because the Display2 methods each call the global Display3 method, they will all log what the function in the last assignment fo Display3 says to log, and that will always be Fred.

Title: Why private function can't access member variable within Javascript object?


答: You seem to be calling Action() with no parameters.  You're effectively calling Action.__init__(self), without providing the driver parameter.  That is why you're getting TypeError: __init__() takes exactly 2 arguments (1 given).  The 1 given is self, which is automatically supplied by Python, and the missing one is driver.

Title: How to call methods from class located in one python file from another python file

Body:
I am creating framework using Selenium and Python.
    My data driven Framework should consist of (so far) 3 files:

1) Config.py have class Config() that have all the nessesary methods such as:
   def setUp() -
   def tearDown()
   def click()
   def send_keys()

2) data.py - with all data

3) test.py - with all of the steps

I am currently working on click() method.

I want to pass 2 parameters to this method, it will use slice()
    to identify what kind of locators i am using and click
    accordingly. Unfortunatly no matter what i do - it keeps
    throwing me some errors.

config.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass
        elif elp[flp] == 'li':
            try:
                self.driver.find_element_by_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'na':
            try:
                self.driver.find_element_by_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cs':
            try:
                self.driver.find_element_by_css_selector(elemValue).click()
            except:
                pass
        elif elp[flp] == 'pa':
            try:
                self.driver.find_element_by_partial_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'ta':
            try:
                self.driver.find_element_by_tag_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cl':
            try:
                self.driver.find_element_by_class_name(elemValue).click()
            except:
                pass

    def send_keys(self):
        pass

test.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
from Setup import Actions

action = Actions()
action.setUp()

Error Message:

Traceback (most recent call last):
  File "/Users/a./Desktop/Automation_Work/correct_PPLS/oop/Test.py", line 9, in <module>
    action = Actions()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.153s]


问:
TypeError: Cannot read property 'employeeName' of undefined
TypeError: Cannot read property 'employeeName' of undefined.
I have a subscribe on constructor that get a value from service.
THe value is not undefined but on jasmine unit text, it says undefined. I'm new on jasmine unit test and would like a support

In the file.ts, the value of employee is defined...

```<code>export class WorkspacesComponent implements OnInit {
private employee: Employee
public user: User

    constructor(private workspacesService: WorkspacesService, private userService: UserService, private modalService: NgbModal) {
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; });
    }

    ngOnInit(): void {
        this.newForm();
        this.getWorkspaces();
        this.user.name = this.employee.employeeName
    }
}
</code>```

on test it says undefined .spec.ts

```<code>const employee: Employee = {

    UNIORG: "1460011",
    companyId: "0001000493",
    companyName: "EVERIS BRASIL CONSULTORIA DE NEGÓCIOS E TECNOLOGIA DA INFORMAÇÃO LTDA",
    departmentId: "08468",
    departmentName: "Tecnologia da Informação",
    employeeName: "LEONARDO COSTA E SILVA DE SOUZA DOS REMÉDIOS",
    endDateSituation: "",
    mail: "",
    managerId: "000699871",
    occupationId: "PPPPPP",
    occupationName: "PRESTADOR DE SERVIO",
    salaryGroupLevel: "0",
    situation: "01",
    startDateSituation: ""
}

const user: User = {
    id: '',
    name: '',
    enrollment: '',
    site: ''
}

const MockUserService = {
    user$: { subscribe: () => { user } },
    employee$: { subscribe: () => { employee } }
};

describe('WorkspacesComponent', () => {

    let component: WorkspacesComponent;
    let fixture: ComponentFixture<WorkspacesComponent>;
    let WorkspacesServiceSpy: WorkspacesService;
    let UserServiceSpy: UserService;
    let modalSpy: NgbModal;

    configureTestSuite(() => {
        TestBed.configureTestingModule({
            schemas: [NO_ERRORS_SCHEMA],
            declarations: [WorkspacesComponent],
            imports: [BrowserModule, FormsModule, MaterialModule, ReactiveFormsModule, BrowserAnimationsModule,],
            providers: [
                { provide: WorkspacesService, useValue: MockWorkspaces },
                { provide: UserService, useValue: MockUserService },
                { provide: NgbModal, useValue: MockNgbModal },
            ]
        })
            .compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(WorkspacesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        WorkspacesServiceSpy = fixture.debugElement.injector.get(WorkspacesService);
        UserServiceSpy = fixture.debugElement.injector.get(UserService);
        modalSpy = fixture.debugElement.injector.get(NgbModal);
    })

    beforeEach(async(() => {
        fixture.detectChanges();
    }));

    it('should create component', () => {
        expect(component).toBeTruthy();
    });
});

</code>```

I've done a change, after a suggestion. But now the problem is:

'WorkspacesComponent should create component
TypeError: Cannot read property 'name' of undefined'

```<code>export class WorkspacesComponent implements OnInit {
private employee: Employee
public user: User

    constructor(private workspacesService: WorkspacesService, private userService: UserService, private modalService: NgbModal) {
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; });
    }

    ngOnInit(): void {
        this.newForm();
        this.getWorkspaces();
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; this.user.name = this.employee.employeeName; });
    }
}
</code>```

答:
Put your subscribe in ngOnInit, it's better practice than using the constructor.
And then move this:

```<code>this.user.name = this.employee.employeeName;
</code>```

inside your subscribe() response

Hope this helps

Body:
TypeError: Cannot read property 'employeeName' of undefined.
I have a subscribe on constructor that get a value from service.
THe value is not undefined but on jasmine unit text, it says undefined. I'm new on jasmine unit test and would like a support

In the file.ts, the value of employee is defined...

export class WorkspacesComponent implements OnInit {
private employee: Employee
public user: User

    constructor(private workspacesService: WorkspacesService, private userService: UserService, private modalService: NgbModal) {
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; });
    }

    ngOnInit(): void {
        this.newForm();
        this.getWorkspaces();
        this.user.name = this.employee.employeeName
    }
}

on test it says undefined .spec.ts

const employee: Employee = {

    UNIORG: "1460011",
    companyId: "0001000493",
    companyName: "EVERIS BRASIL CONSULTORIA DE NEGÓCIOS E TECNOLOGIA DA INFORMAÇÃO LTDA",
    departmentId: "08468",
    departmentName: "Tecnologia da Informação",
    employeeName: "LEONARDO COSTA E SILVA DE SOUZA DOS REMÉDIOS",
    endDateSituation: "",
    mail: "",
    managerId: "000699871",
    occupationId: "PPPPPP",
    occupationName: "PRESTADOR DE SERVIO",
    salaryGroupLevel: "0",
    situation: "01",
    startDateSituation: ""
}

const user: User = {
    id: '',
    name: '',
    enrollment: '',
    site: ''
}

const MockUserService = {
    user$: { subscribe: () => { user } },
    employee$: { subscribe: () => { employee } }
};

describe('WorkspacesComponent', () => {

    let component: WorkspacesComponent;
    let fixture: ComponentFixture<WorkspacesComponent>;
    let WorkspacesServiceSpy: WorkspacesService;
    let UserServiceSpy: UserService;
    let modalSpy: NgbModal;

    configureTestSuite(() => {
        TestBed.configureTestingModule({
            schemas: [NO_ERRORS_SCHEMA],
            declarations: [WorkspacesComponent],
            imports: [BrowserModule, FormsModule, MaterialModule, ReactiveFormsModule, BrowserAnimationsModule,],
            providers: [
                { provide: WorkspacesService, useValue: MockWorkspaces },
                { provide: UserService, useValue: MockUserService },
                { provide: NgbModal, useValue: MockNgbModal },
            ]
        })
            .compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(WorkspacesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        WorkspacesServiceSpy = fixture.debugElement.injector.get(WorkspacesService);
        UserServiceSpy = fixture.debugElement.injector.get(UserService);
        modalSpy = fixture.debugElement.injector.get(NgbModal);
    })

    beforeEach(async(() => {
        fixture.detectChanges();
    }));

    it('should create component', () => {
        expect(component).toBeTruthy();
    });
});

I've done a change, after a suggestion. But now the problem is:

'WorkspacesComponent should create component
TypeError: Cannot read property 'name' of undefined'

export class WorkspacesComponent implements OnInit {
private employee: Employee
public user: User

    constructor(private workspacesService: WorkspacesService, private userService: UserService, private modalService: NgbModal) {
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; });
    }

    ngOnInit(): void {
        this.newForm();
        this.getWorkspaces();
        this.userService.user$.subscribe(user => { this.user = user });
        this.userService.employee$.subscribe(employee => { this.employee = employee; this.user.name = this.employee.employeeName; });
    }
}

Body:
Put your subscribe in ngOnInit, it's better practice than using the constructor.
And then move this:

this.user.name = this.employee.employeeName;

inside your subscribe() response

Hope this helps


问:
optimize sql query on 5B records table in postgresql database
My postgresql database has the table electrical_measurement which contains approximately 5 billion records. I have indexes on every column. I am trying to perform the following query but it never ends. Wondering how I can modify it to run faster.

```<code>SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND em.net_id_in IN
 (SELECT em.net_id_in
  FROM electrical_measurement AS em
  WHERE em.assembly_id = 1
  AND em.avg_meas_voltage > 0
  GROUP BY em.net_id_in)
ORDER BY em.timestamp
</code>```

This is the result from EXPLAIN:

```<code>-------------------------------------------------------------------------------------------------------------------------------------------------------
 Gather Merge  (cost=373158311.30..573643901.29 rows=1718327938 width=63)
   Workers Planned: 2
   ->  Sort  (cost=373157311.28..375305221.20 rows=859163969 width=63)
         Sort Key: em."timestamp"
         ->  Hash Join  (cost=84935808.04..171830022.94 rows=859163969 width=63)
               Hash Cond: (em.net_id_in = mb_pad_map.net_id)
               ->  Hash Join  (cost=84935424.26..161155613.60 rows=118993479 width=41)
                     Hash Cond: (em.net_id_in = em_1.net_id_in)
                     ->  Parallel Bitmap Heap Scan on electrical_measurement em  (cost=2996320.29..78903135.78 rows=118993479 width=37)
                           Recheck Cond: (assembly_id = 1)
                           ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                 Index Cond: (assembly_id = 1)
                     ->  Hash  (cost=81939087.68..81939087.68 rows=1303 width=4)
                           ->  HashAggregate  (cost=81939061.62..81939074.65 rows=1303 width=4)
                                 Group Key: em_1.net_id_in
                                 ->  Bitmap Heap Scan on electrical_measurement em_1  (cost=2953194.68..81656356.93 rows=113081878 width=4)
                                       Recheck Cond: (assembly_id = 1)
                                       Filter: (avg_meas_voltage > '0'::numeric)
                                       ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                             Index Cond: (assembly_id = 1)
               ->  Hash  (cost=266.17..266.17 rows=9408 width=38)
                     ->  Hash Join  (cost=42.32..266.17 rows=9408 width=38)
                           Hash Cond: (mb_pad_map.net_id = tvt_net.id)
                           ->  Seq Scan on main_board_pad_map mb_pad_map  (cost=0.00..199.08 rows=9408 width=16)
                           ->  Hash  (cost=26.03..26.03 rows=1303 width=22)
                                 ->  Seq Scan on tvt_net  (cost=0.00..26.03 rows=1303 width=22)
(26 rows)
</code>```

Do you have any suggestions?
Thanks

答:
The sub-select only is one of your issues, but you could use EXISTS instead:

SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND EXISTS (SELECT 1
  FROM electrical_measurement AS tmp
  WHERE tmp.avg_meas_voltage > 0
  AND tmp.net_id_in = em.net_id_in)
ORDER BY em.timestamp
```

Then, you should have an index covering at least both, net_id_in and avg_meas_voltage. By that, you should be eliminating the Bitmap Heap Scan, the Group Key and the HashAggregate in one shot.

Last but not least, you are dealing with time-series information and you are querying all of the data, sorted by time, which is going to be really slow (most likely reverting to a disk sort, instead of in-memory) with so many estimated rows (~1.7B).

If you really, really need all of the data from the beginning of all time in your big table and you really need to sort it, then make sure that you have a separate low-latency, high-throughput storage available, create a tablespace and set temp_tablespaces option to it (disk sorts then will go there instead of the default tablespace).

Body:
My postgresql database has the table electrical_measurement which contains approximately 5 billion records. I have indexes on every column. I am trying to perform the following query but it never ends. Wondering how I can modify it to run faster.

SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND em.net_id_in IN
 (SELECT em.net_id_in
  FROM electrical_measurement AS em
  WHERE em.assembly_id = 1
  AND em.avg_meas_voltage > 0
  GROUP BY em.net_id_in)
ORDER BY em.timestamp

This is the result from EXPLAIN:

-------------------------------------------------------------------------------------------------------------------------------------------------------
 Gather Merge  (cost=373158311.30..573643901.29 rows=1718327938 width=63)
   Workers Planned: 2
   ->  Sort  (cost=373157311.28..375305221.20 rows=859163969 width=63)
         Sort Key: em."timestamp"
         ->  Hash Join  (cost=84935808.04..171830022.94 rows=859163969 width=63)
               Hash Cond: (em.net_id_in = mb_pad_map.net_id)
               ->  Hash Join  (cost=84935424.26..161155613.60 rows=118993479 width=41)
                     Hash Cond: (em.net_id_in = em_1.net_id_in)
                     ->  Parallel Bitmap Heap Scan on electrical_measurement em  (cost=2996320.29..78903135.78 rows=118993479 width=37)
                           Recheck Cond: (assembly_id = 1)
                           ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                 Index Cond: (assembly_id = 1)
                     ->  Hash  (cost=81939087.68..81939087.68 rows=1303 width=4)
                           ->  HashAggregate  (cost=81939061.62..81939074.65 rows=1303 width=4)
                                 Group Key: em_1.net_id_in
                                 ->  Bitmap Heap Scan on electrical_measurement em_1  (cost=2953194.68..81656356.93 rows=113081878 width=4)
                                       Recheck Cond: (assembly_id = 1)
                                       Filter: (avg_meas_voltage > '0'::numeric)
                                       ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                             Index Cond: (assembly_id = 1)
               ->  Hash  (cost=266.17..266.17 rows=9408 width=38)
                     ->  Hash Join  (cost=42.32..266.17 rows=9408 width=38)
                           Hash Cond: (mb_pad_map.net_id = tvt_net.id)
                           ->  Seq Scan on main_board_pad_map mb_pad_map  (cost=0.00..199.08 rows=9408 width=16)
                           ->  Hash  (cost=26.03..26.03 rows=1303 width=22)
                                 ->  Seq Scan on tvt_net  (cost=0.00..26.03 rows=1303 width=22)
(26 rows)

Do you have any suggestions?
Thanks

Body:
The sub-select only is one of your issues, but you could use EXISTS instead:

SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND EXISTS (SELECT 1
  FROM electrical_measurement AS tmp
  WHERE tmp.avg_meas_voltage > 0
  AND tmp.net_id_in = em.net_id_in)
ORDER BY em.timestamp

Then, you should have an index covering at least both, net_id_in and avg_meas_voltage. By that, you should be eliminating the Bitmap Heap Scan, the Group Key and the HashAggregate in one shot.

Last but not least, you are dealing with time-series information and you are querying all of the data, sorted by time, which is going to be really slow (most likely reverting to a disk sort, instead of in-memory) with so many estimated rows (~1.7B).

If you really, really need all of the data from the beginning of all time in your big table and you really need to sort it, then make sure that you have a separate low-latency, high-throughput storage available, create a tablespace and set temp_tablespaces option to it (disk sorts then will go there instead of the default tablespace).


问:
How to apply Image TranslateTranform to an Image by step (Jump a few Pixel)
I currently using the TranslateTransform on an image by code in my App and it's working correctly.

But I would like the image to move by step, let's say jump 10 or 20 pixel on each movement. Is there a way to do this. This to give a retro flavor to the movement.

I was thinking something like TranslateTransform.Step = 10;

```<code>            Duration durationX = new TimeSpan(0, 0, 0, 0, 600);
            Duration durationY = new TimeSpan(0, 0, 0, 0, 400);

            DoubleAnimation moveX = new DoubleAnimation();
            moveX.Duration = durationX;
            moveX.To = ((ImgCanvasCoordinates[cardSource][0] - ImgCanvasCoordinates[cardTarget][0]) * -1);
            DoubleAnimation moveY = new DoubleAnimation();
            moveY.Duration = durationY;
            moveY.To = ((ImgCanvasCoordinates[cardSource][1] - ImgCanvasCoordinates[cardTarget][1]) * -1);

            Storyboard story1 = new Storyboard();
            story1.Children.Add(moveX);
            story1.Children.Add(moveY);
            Storyboard.SetTarget(moveX, imgGhost);
            Storyboard.SetTarget(moveY, imgGhost);
            Storyboard.SetTargetProperty(moveX, "(Image.RenderTransform).(TranslateTransform.X)");
            Storyboard.SetTargetProperty(moveY, "(Image.RenderTransform).(TranslateTransform.Y)");

            story1.Begin();
</code>```

答:
You can use a custom EasingFunction to achieve this.

By writing an EasingFunction you can fully control the movement of animation. I've written a StepEasingFunction as shown below:

```<code>public class StepEasingFunction : EasingFunctionBase
{
    public double NormalizedStep { get; set; }

    protected override Freezable CreateInstanceCore()
    {
        return new StepEasingFunction {NormalizedStep = NormalizedStep};
    }

    protected override double EaseInCore(double normalizedTime)
    {
        var stepIndex = Math.Round(normalizedTime / NormalizedStep);
        return NormalizedStep * stepIndex;
    }
}
</code>```

Then, just add an EasingFunction assigning to the animations:

```<code>moveX.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};
moveY.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};
</code>```

Then, how to calculate the value of the NormalizedStep property?

You said that you want a 10-pixel movement for each step, so calculate the step total count and use 1 / stepTotalCount to calculate the final NormalizedStep property.

Body:
I currently using the TranslateTransform on an image by code in my App and it's working correctly.

But I would like the image to move by step, let's say jump 10 or 20 pixel on each movement. Is there a way to do this. This to give a retro flavor to the movement.

I was thinking something like TranslateTransform.Step = 10;

            Duration durationX = new TimeSpan(0, 0, 0, 0, 600);
            Duration durationY = new TimeSpan(0, 0, 0, 0, 400);

            DoubleAnimation moveX = new DoubleAnimation();
            moveX.Duration = durationX;
            moveX.To = ((ImgCanvasCoordinates[cardSource][0] - ImgCanvasCoordinates[cardTarget][0]) * -1);
            DoubleAnimation moveY = new DoubleAnimation();
            moveY.Duration = durationY;
            moveY.To = ((ImgCanvasCoordinates[cardSource][1] - ImgCanvasCoordinates[cardTarget][1]) * -1);

            Storyboard story1 = new Storyboard();
            story1.Children.Add(moveX);
            story1.Children.Add(moveY);
            Storyboard.SetTarget(moveX, imgGhost);
            Storyboard.SetTarget(moveY, imgGhost);
            Storyboard.SetTargetProperty(moveX, "(Image.RenderTransform).(TranslateTransform.X)");
            Storyboard.SetTargetProperty(moveY, "(Image.RenderTransform).(TranslateTransform.Y)");

            story1.Begin();

Body:
You can use a custom EasingFunction to achieve this.

By writing an EasingFunction you can fully control the movement of animation. I've written a StepEasingFunction as shown below:

public class StepEasingFunction : EasingFunctionBase
{
    public double NormalizedStep { get; set; }

    protected override Freezable CreateInstanceCore()
    {
        return new StepEasingFunction {NormalizedStep = NormalizedStep};
    }

    protected override double EaseInCore(double normalizedTime)
    {
        var stepIndex = Math.Round(normalizedTime / NormalizedStep);
        return NormalizedStep * stepIndex;
    }
}

Then, just add an EasingFunction assigning to the animations:

moveX.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};
moveY.EasingFunction = new StepEasingFunction {NormalizedStep = 0.2};

Then, how to calculate the value of the NormalizedStep property?

You said that you want a 10-pixel movement for each step, so calculate the step total count and use 1 / stepTotalCount to calculate the final NormalizedStep property.


问:
Silverlight Simple and Complex Properties
I was asked recently in an interview to give an example of a simple property and a complex property in Silverlight.  I think they were asking about dependency properties and attached properties but I'm not sure.  I've never heard the term Silverlight Simple Property or Silverlight Complex Property and googling hasn't helped.  Are these common terms that I've just missed up until now?  If so, what do they refer to?</p>

答:
Haven't heard anything like that before either but...

...maybe they were referring to lazy setting for simple:

```<code>SimpleProperty { get; set; }
</code>```

and complex to customizing the setter:

```<code>ComplexProperty
{
   get
   {
      return _complexProperty
   }
   set
   {
      //Do some "complex" stuff here like maybe computing how many steps to the moon then add it to the current value before setting to the field :))
      _complexProperty = value;
      RaisePropertyChanged("ComplexProperty");
   }
}
</code>```

Body:
Haven't heard anything like that before either but...

...maybe they were referring to lazy setting for simple:

SimpleProperty { get; set; }

and complex to customizing the setter:

ComplexProperty
{
   get
   {
      return _complexProperty
   }
   set
   {
      //Do some "complex" stuff here like maybe computing how many steps to the moon then add it to the current value before setting to the field :))
      _complexProperty = value;
      RaisePropertyChanged("ComplexProperty");
   }
}


问:
return insert id on none laravel db set up
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

```<code>$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}
</code>```

I need to get the id of the insert.

答:
This is a little complex without using the Laravel structured queries, as you said.  If you can tweak your query a little, and make sure you validate the input data ahead of your insert to prevent SQL injection, you should be able to use insertGetId.  You'll have to do some work, but something along the lines of:

```<code>$id = DB::table('whateverYourTableNameIs')->insertGetId([
    'assocID' => $request->input('assocID'),
    'yourSelectField' => DB::raw("yourRawSelect"),
    // etc.
]);
</code>```

Body:
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.

This is the insert I am using.

$results = DB::insert("
            SELECT * FROM insrdata.add_user(
                :assocID,
                :accountID,
                :firstName,
                :middleName,
                :lastName,
                :address1,
                :address2,
                :city,
                :state,
                :zipCode,
                :phone,
                :email,
                :birthDateMMDDYYYY,
                :gradeLevelID,
                :commentText
            )
        ",
        [
            'assocID' => $request->input('assocID'),
            'accountID' => $request->input('accountID'),
            'firstName' => $request->input('firstName'),
            'middleName' => $request->input('middleName'),
            'lastName' => $request->input('lastName'),
            'address1' => $request->input('address1'),
            'address2' => $request->input('address2'),
            'city' => $request->input('city'),
            'state' => $request->input('state'),
            'zipCode' => $request->input(''),
            'phone' => $request->input(''),
            'email' => $request->input('email'),
            'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
            'gradeLevelID' => $request->input('gradeLevelID'),
            'commentText' => $request->input('commentText')
        ]
    );

if($results) {
    $return_array = array(
        'p_contact_id' => "",
        'p_result' => "O.K."
    );
}

I need to get the id of the insert.

Body:
This is a little complex without using the Laravel structured queries, as you said.  If you can tweak your query a little, and make sure you validate the input data ahead of your insert to prevent SQL injection, you should be able to use insertGetId.  You'll have to do some work, but something along the lines of:

$id = DB::table('whateverYourTableNameIs')->insertGetId([
    'assocID' => $request->input('assocID'),
    'yourSelectField' => DB::raw("yourRawSelect"),
    // etc.
]);