问:
get the text in the display with ncurses
Is there any way to get back the characters outputted into a variable on ncurses ?

let's say I do:

```<code>printw("test");
</code>```

then I want to be able to:

```<code>somefunc(strbuffer);
printf("%s",strbuffer); // test
</code>```

I need a function to get back all characters on the screen into a variable, scr_dump get's close but the output format is unreadable..

答:
There are two sets of functions for retrieving data from the screen.  If your printw uses only (as in the question) text which is represented as an 8-bit encoding (ASCII, POSIX, ISO-8859-1), then inch and inchstr work:

inch retrieves a single cell along with its attributes

inchstr retrieves multiple cells along with their attributes

or more simply using instr and its variations.  These functions return the data without additional need for masking the attributes from the characters.

However, if the data uses a multibyte encoding (such as UTF-8), then you must use a different interface for retrieving the characters.  These are the equivalents of inch and inchstr:

in_wch,  etc. - extract a complex character and
   rendition from a window

in_wchstr, etc. - get an array of complex
   characters and renditions from a curses window

A complex character is a structure, which X/Open Curses treats as opaque.  You must use getcchar to extract data (such as a wide-character string) from each cell's data.

A (little) more simply, you can read the wide-character string information from a window:

inwstr,  etc. - get a string of wchar_t characters from a curses window

there is no single-character form; you must retrieve data as a one-character string.

In summary, while your application can put data as an array of char (or individual chtype values), in a UTF-8 environment it must retrieve it as complex characters or wide-characters.  If you happen to be using Linux, you can generally treat wchar_t as Unicode values.  Given data as an array of wchar_t values, you would use other (non-curses) functions to obtain a multibyte (UTF-8) string.

Since the question said ncurses rather than simply curses, it's appropriate to point out that applications using ncurses can differ from X/Open Curses in the way they put data on the screen (which can affect your expectations about retrieving it).  In ncurses, addch (and similar char-oriented functions) will handle bytes in a multi-byte string such as UTF-8, storing the result as wide-characters.  None of the other X/Open Curses implementations to date do this.  The others treat those bytes as independent, and may represent them as invalid wide-characters.

By the way, since the question was asked in 2010, ncurses' scr_dump format has been extended, making it "readable".

Body:
Is there any way to get back the characters outputted into a variable on ncurses ?

let's say I do:

printw("test");

then I want to be able to:

somefunc(strbuffer);
printf("%s",strbuffer); // test

I need a function to get back all characters on the screen into a variable, scr_dump get's close but the output format is unreadable..


来源: stackexchange

问:
Angular 4 nested *ngFor for a number of times
I have one Json object containing file hierarchy list like below:

```<code>{
    "path": "\\Users\\ad00440946\\Downloads\\Angular2-
                 GettingStarted-master",
    "name": "Angular2-GettingStarted-master",
    "type": "folder",
    "children": [
        {
           "path":
               "\\Users\\ad00440946\\Downloads\\Angular2-
                GettingStarted-master/Angular2-GettingStarted-master",
            "name": "Angular2-GettingStarted-master",
            "type": "folder",
           "children": []
        }
   ]
 }
</code>```

And the list goes on till it reaches to end of a file where children array will be empty.
i have to print all this files in a tree view like this. The layout is working fine but problem is i don't know how many levels of children it will have and how many times do i need to iterate. Is there any work arround?

Here's my HTML code:

```<code><!--FILE TREE START-->
<div class="TreeContainer" *ngIf="!searchViewFlag">
    <div class="ParentPlace">
        <span>{{allFilesData.name}}</span>
    </div>
    <br><br>
    <ul class="tree">
        <li *ngFor="let childl1 of allFilesData.children">
            <!--<span>1</span>-->
            <img src="../../assets/Images/ChildNode.png" />
            <a> {{childl1.name}} </a>
            <ul>
                <li *ngFor="let childl2 of childl1.children">
                    <!--<span>3</span>-->
                    <img src="../../assets/Images/ChildNode.png" />
                    <a>{{childl2.name}}</a>
                    <ul>
                        <li *ngFor="let childl3 of childl2.children">
                            <!--<span>3</span>-->
                            <img src="../../assets/Images/ChildNode.png" />
                            <a>{{childl3.name}}</a>
                        </li>
                    </ul>

                </li>
            </ul>
        </li>

    </ul>
</div>
</code>```

答:
You should make a separate component which renders children, which you can use in your parent:

```<code><div class="TreeContainer" *ngIf="!searchViewFlag">
  <tree-item [data]="allFilesData"></tree-item>
</div>
</code>```

And have a TreeItemComponent which you can repeat if the data has children:

```<code>@Component({
  selector: 'tree-item',
  template: `
    <div class="ParentPlace">
      <span>{{data.name}}</span>
    </div>
    <ul *ngIf="data.children && data.children.length > 0">
       <li *ngFor="let child of data.children">
         <tree-item [data]="child"></tree-item>
       </li>
    </ul>
  `
})
export class TreeItemComponent {
  @Input()
  public data: any = {};
}
</code>```

beware that this is untested code, and merely a guideline for you. Basic concept is, use a component which renders children, and will render children of children if it's necessary

ContentLicense: CC BY-SA 3.0

Body:
I have one Json object containing file hierarchy list like below:

{
    "path": "\\Users\\ad00440946\\Downloads\\Angular2-
                 GettingStarted-master",
    "name": "Angular2-GettingStarted-master",
    "type": "folder",
    "children": [
        {
           "path":
               "\\Users\\ad00440946\\Downloads\\Angular2-
                GettingStarted-master/Angular2-GettingStarted-master",
            "name": "Angular2-GettingStarted-master",
            "type": "folder",
           "children": []
        }
   ]
 }

And the list goes on till it reaches to end of a file where children array will be empty.
i have to print all this files in a tree view like this. The layout is working fine but problem is i don't know how many levels of children it will have and how many times do i need to iterate. Is there any work arround?

Here's my HTML code:

        {{allFilesData.name}}

             {{childl1.name}}

                    {{childl2.name}}

                            {{childl3.name}}

Body:
You should make a separate component which renders children, which you can use in your parent:

<div class="TreeContainer" *ngIf="!searchViewFlag">
  <tree-item [data]="allFilesData"></tree-item>
</div>

And have a TreeItemComponent which you can repeat if the data has children:

@Component({
  selector: 'tree-item',
  template: `
    <div class="ParentPlace">
      <span>{{data.name}}</span>
    </div>
    <ul *ngIf="data.children && data.children.length > 0">
       <li *ngFor="let child of data.children">
         <tree-item [data]="child"></tree-item>
       </li>
    </ul>
  `
})
export class TreeItemComponent {
  @Input()
  public data: any = {};
}

beware that this is untested code, and merely a guideline for you. Basic concept is, use a component which renders children, and will render children of children if it's necessary


问:
THREAD 1: EXC_BREAKPOINT CALayer removeAllAnimations message sent to deallocated
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

```<code>let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }
</code>```

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

```<code>DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }
</code>```

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

```<code>tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
</code>```

Then I've table view delegate and datasource:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }
</code>```

and in the cell class there is just:

```<code>import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
</code>```

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0

答:
I'm gonna make some small suggestions to clean up your code. Not sure if it will solve the problem but it will help to ensure that your issue isn't based on something trivial.

I'm not sure where you're calling it, but in the request load completion handler make sure to capture self weakly.

Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { [weak self] response in

This way you're not forcing the object to stay alive until the loading finishes, which may cause it to load in the wrong place.

Make sure that the completion block (mentioned above) is running on the main thread. You're making calls to UI, so just check it to be safe.

Your IB outlets should be declared as @IBOutlet weak var foo: UIView? You might be causing yourself problems by strongly referencing the views.

dequeueReusableCell(withReuseIdentifier:) can return nil. You should be using dequeueReusableCell(withReuseIdentifier:for:) - and don't forget to register the cell using register(_:forCellWithReuseIdentifier:) first.

Body:
There are a lot of question with the same title but somehow I felt that every case is different as my problem is still not resolved and I've no clue why and also there are not enough solutions for Swift. So here is my scenerio:

I've used CarbonKit to show 4 view controllers in a single view controller. The FourthViewController sends a get call using AlamoFire. It successfully loads the data and reload tableView. However when I drag this table view my app crashes and I get EXC_BREAKPOINT and sometimes EXC_BAD_ACCESS for the same thing.

Here is what I've tried:

Upon searching I came to know about zombies. So I enabled it and when the app gives me EXC I get this:

-[CALayer removeAllAnimations]: message sent to deallocated instance

So as I checked there was no animation I might have been using in this class. But considering it's inside CarbonKit they might have something to do with it but I'm unable to figure it out.

I run Product > Analyze from xCode and the most of the blue icons are on FBSDK which have nothing to do with this class so it was not useful to debug at all.

Here are the screenshots:
 and
and here is what Instruments 9.0 zombies message gave me:
 and

I get this in console of xCode:

If you need more information I'll update my questions.

UPDATE

Here is my code when I'm getting the data from web using Alamofire. Now this call runs successfully and I can scroll down to view all the data that is loaded in the table. But when i scroll up then it crashes with the above errors.

let headers = [
            "security-token": "MY_SECURITY_CODE_HERE",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let url = "URL_GOES_HERE"
        //print(url)
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if let result = response.result.value as? [String: AnyObject] {

                switch response.result {
                case .success:
                    if result["status"] as! Int == 0
                    {
                        self.clearAllNotice()
                        let alert = UIAlertController(title: "Error",
                                                      message: "\(result["msg"] ?? "Our Server is not responding at the moment. Try again later!" as AnyObject)",
                            preferredStyle: UIAlertControllerStyle.alert)

                        let cancelAction = UIAlertAction(title: "OK",
                                                         style: .cancel, handler: nil)

                        alert.addAction(cancelAction)
                        self.present(alert, animated: true)
                    }
                    else
                    {
                        self.clearAllNotice()

                        for docReviewDict in (result["data"] as! [AnyObject]) {

                            let docReview = DoctorReview(dict: docReviewDict as! [String : AnyObject])
                            self.mainDoctorReviewsArray.append(docReview)
                        }

                        self.tableView.reloadData()
                    }
                case .failure(let error):
                    self.clearAllNotice()
                    let alert = UIAlertController(title: "Something is wrong",
                                                  message: error.localizedDescription,
                                                  preferredStyle: UIAlertControllerStyle.alert)

                    let cancelAction = UIAlertAction(title: "OK",
                                                     style: .cancel, handler: nil)

                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                }
            } else {
              print("Somethins is wrong with the URL")
            }
        }

Just in case here is the cell which is loaded in the tableview.

Latest:

Based on the comment I've done this:

DispatchQueue.main.async {
                        self.tableView.reloadData()
                        }

but still the same result I'am getting

Thread 1: EXC_BAD_ACCESS (code=1, address=0xb4c4beb8)

on let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell line when I drag down on table view.

IMPLEMENTATION OF CELL

The class name is ReviewsViewController which has a @IBOutlet fileprivate var tableView: UITableView!.

Then in viewDidLoad():

tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()

Then I've table view delegate and datasource:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainDoctorReviewsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell") as! ReviewsTableViewCell //WHEN THE APP IS CRASHED AS I DRAG THE TABLE VIEW IT CRASH ON THIS LINE. As this line is highlighted in red with message "Thread 1: EXC_BREAKPOINT (code=1, subcode=0x186ddd61c)"

        cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.width / 2;
        cell.userPhoto.layer.masksToBounds = true

        cell.userName.text = mainDoctorReviewsArray[indexPath.row].name

        cell.starRating.settings.fillMode = .precise

        if let rate = mainDoctorReviewsArray[indexPath.row].rating
        {
            cell.starRating.rating = Double(rate)!
        }
        else {
            cell.starRating.rating = 0
        }

        cell.desc.text = mainDoctorReviewsArray[indexPath.row].feedback
        cell.dateOfReview.text = mainDoctorReviewsArray[indexPath.row].dates
        cell.timeOfReview.text = mainDoctorReviewsArray[indexPath.row].times

        return cell
    }

and in the cell class there is just:

import UIKit
import Cosmos

class ReviewsTableViewCell: UITableViewCell {

    @IBOutlet var timeOfReview: UILabel!
    @IBOutlet var dateOfReview: UILabel!
    @IBOutlet var desc: UITextView!
    @IBOutlet var starRating: CosmosView!
    @IBOutlet var userName: UILabel!
    @IBOutlet var userPhoto: UIImageView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

The screenshot of tableView is above in this question.

This is the parent class under which 4 ViewControllers loads: dropbox.com/s/d5sh4ej1ssv6873/… And this is the class which has the tableview is and on scroll it crashed the app: dropbox.com/s/3kiju9hn3uewzar/ReviewsViewController.swift?dl=0


问:
Using Selenium to test Polymer elements and shadow DOMs
I'm having problems using Selenium with elements that are inside a shadow DOM. Is there a trick to this? Am I doing something wrong?

Here's my variety of attempts:

```<code>var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('chrome').build();

driver.get('https://shop.polymer-project.org/');

// Goal is to find shop-app #shadow-root app-header
//

// This is OK; no shadow DOMs
driver.findElement(webdriver.By.css('shop-app'));

// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app /deep/ app-header'));

// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app::shadow app-header'));

// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app /deep/ app-header');
}));

// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app::shadow app-header');
}));

// This fails because:
// WebDriverError: unknown error: Cannot read property 'querySelector' of null
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app').shadowRoot.querySelector('app-header');
}));

// This fails because:
// WebDriverError: unknown error: Cannot read property 'header' of undefined
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app').$.header;
}));
</code>```

I'm running node 7.1.0 and selenium-webdriver 3.0.1.

答:
I think is better to use the selenium selectors and inject the script just to take the shadow root:

```<code>def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()
</code>```

To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:

```<code>import selenium
from selenium import webdriver
driver = webdriver.Chrome()

def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)

root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)

root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)

search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()
</code>```

Doing the same approach suggested in the other answers has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:

```<code>search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()
</code>```

Body:
I'm having problems using Selenium with elements that are inside a shadow DOM. Is there a trick to this? Am I doing something wrong?

Here's my variety of attempts:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('chrome').build();

driver.get('https://shop.polymer-project.org/');

// Goal is to find shop-app #shadow-root app-header
//

// This is OK; no shadow DOMs
driver.findElement(webdriver.By.css('shop-app'));

// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app /deep/ app-header'));

// This fails because:
// NoSuchElementError: no such element: Unable to locate element
driver.findElement(webdriver.By.css('shop-app::shadow app-header'));

// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app /deep/ app-header');
}));

// This fails because:
// TypeError: Custom locator did not return a WebElement
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app::shadow app-header');
}));

// This fails because:
// WebDriverError: unknown error: Cannot read property 'querySelector' of null
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app').shadowRoot.querySelector('app-header');
}));

// This fails because:
// WebDriverError: unknown error: Cannot read property 'header' of undefined
driver.findElement(webdriver.By.js(function() {
    return document.querySelector('shop-app').$.header;
}));

I'm running node 7.1.0 and selenium-webdriver 3.0.1.

Body:
I think is better to use the selenium selectors and inject the script just to take the shadow root:

def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

outer = expand_shadow_element(driver.find_element_by_css_selector("#test_button"))
inner = outer.find_element_by_id("inner_button")
inner.click()

To put this into perspective I just added a testable example with Chrome's download page, clicking the search button needs open 3 nested shadow root elements:

import selenium
from selenium import webdriver
driver = webdriver.Chrome()

def expand_shadow_element(element):
  shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)
  return shadow_root

driver.get("chrome://downloads")
root1 = driver.find_element_by_tag_name('downloads-manager')
shadow_root1 = expand_shadow_element(root1)

root2 = shadow_root1.find_element_by_css_selector('downloads-toolbar')
shadow_root2 = expand_shadow_element(root2)

root3 = shadow_root2.find_element_by_css_selector('cr-search-field')
shadow_root3 = expand_shadow_element(root3)

search_button = shadow_root3.find_element_by_css_selector("#search-button")
search_button.click()

Doing the same approach suggested in the other answers has the drawback that it hard-codes the queries, is less readable and you cannot use the intermediary selections for other actions:

search_button = driver.execute_script('return document.querySelector("downloads-manager").shadowRoot.querySelector("downloads-toolbar").shadowRoot.querySelector("cr-search-field").shadowRoot.querySelector("#search-button")')
search_button.click()


问:
Wcf remote procedure calls
I have created a custom release/deployment log application for a large organization. Front end has been implemented in Adobe AIR backed up by PHP using amfphp for communication. Performance has been excellent. Currently, I have been asked to integrate some windows features (i.e outlook calendar, sharepoint). I thought it would be easier going with a native client and I tried creating a mockup in wpf(managed, but still native) and it looks really  good. My problem though is on the server side. I had in mind wcf, but to my surprise it is a soap framework(xml) and does not support object exchange between the client and the server. So my problem is how to sent to the client a "user" object as I already do with amphph?</p>

答:
The problem is that you're using a proprietary technology on your server side - amfphp, it's a flash specific thing, you need to implement something standard that your client can consume, and there are a lot of options.

SOAP services from PHP ( http://au2.php.net/soap )

JSON ( http://pear.php.net/package/Services_JSON ) consume it in .NET with JSON.NET ( http://json.codeplex.com/ )

Simple REST (Define your own text based data structures)

I think SOAP is a bit verbose, and rolling your own is tedious. Coming from a web/PHP background I imagine JSON will be a comfortable fit.

(You may need to use the .NET WebClient class as well)

ContentLicense: CC BY-SA 2.5

Title: Wcf remote procedure calls


问:
Get Opencart Order ID in COD Payment Module Redirect Link
First of all thank you for giving your valuable time to help me.

My Situation -

I am using Opencart 2.1.0.1

Cash on Delivery Payment Method

Custom OnePageCheckout

Custom Theme

I have implemented a custom process which verifies the customer from our own database via a cron job running every minute.

This is the default code in Opencart
  catalog/view/theme/template/payment/cod.tpl

```<code><div class="buttons">
  <div class="pull-right">
    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />
  </div>
</div>
<script type="text/javascript"><!--
$('#button-confirm').on('click', function() {
    $.ajax({
        type: 'get',
        url: 'index.php?route=payment/cod/confirm',
        cache: false,
        beforeSend: function() {
            $('#button-confirm').button('loading');
        },
        complete: function() {
            $('#button-confirm').button('reset');
        },
        success: function() {
            location = '<?php echo $continue; ?>';
        }
    });
});
//--></script>
</code>```

As I want to redirect the customer to the following page after successful checkout.
https://www.myopencartstore.com/confirm.php?order_id=$order_id

Required Action  : I want to pass on the order_id variable in the url parameter as highlighted in bold above.

My Modified Code -

```<code><div class="buttons">
  <div class="pull-right">
    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />
  </div>
</div>
<script type="text/javascript"><!--
$('#button-confirm').on('click', function() {
    $.ajax({
        type: 'get',
        url: 'index.php?route=payment/cod/confirm',
        cache: false,
        beforeSend: function() {
            $('#button-confirm').button('loading');
        },
        complete: function() {
            $('#button-confirm').button('reset');
        },
        success: function() {
            location = '<?php echo 'confirm-success.php'; ?>';
        }
    });
});
//--></script>
</code>```

Please help how to do the same.

I want to bye-pass the checkout/success page.

I've tried implementing $this->session->data['order_id']; to get the Order ID parameter.

I've tried all my efforts and thus maximum I could do is to just redirect to the desired page but without any parameters.

答:
I hope this will work for you

Kindly Replace in this file as
catalog/controller/extension/payment/cod.php

```<code>$data['continue'] = $this->url->link('checkout/success');
</code>```

to

```<code>$data['continue'] = HTTP_SERVER.'confirm.php?order_id='.$this->session->data['order_id'];
</code>```

Body:
First of all thank you for giving your valuable time to help me.

My Situation -

I am using Opencart 2.1.0.1

Cash on Delivery Payment Method

Custom OnePageCheckout

Custom Theme

I have implemented a custom process which verifies the customer from our own database via a cron job running every minute.

This is the default code in Opencart
  catalog/view/theme/template/payment/cod.tpl

    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />

As I want to redirect the customer to the following page after successful checkout.
https://www.myopencartstore.com/confirm.php?order_id=$order_id

Required Action  : I want to pass on the order_id variable in the url parameter as highlighted in bold above.

My Modified Code -

    <input type="button" value="<?php echo $button_confirm; ?>" id="button-confirm" class="btn btn-primary" data-loading-text="<?php echo $text_loading; ?>" />

Please help how to do the same.

I want to bye-pass the checkout/success page.

I've tried implementing $this->session->data['order_id']; to get the Order ID parameter.

I've tried all my efforts and thus maximum I could do is to just redirect to the desired page but without any parameters.

Body:
I hope this will work for you

Kindly Replace in this file as
catalog/controller/extension/payment/cod.php

$data['continue'] = $this->url->link('checkout/success');

to

$data['continue'] = HTTP_SERVER.'confirm.php?order_id='.$this->session->data['order_id'];

ContentLicense: CC BY-SA 4.0


问:
Java substring from right-hand direction, until a specific character
I want to select specific substring from the input string:

```<code>String i = "example/test/foo-foo";
</code>```

How to get only the substring foo-foo as a new string?

Expected output:

```<code>String newString = "foo-foo";
</code>```

答:
There are many options to solve that. For example via regex search/replace or the substring methods of class String.

Regex approach:

```<code>Optional<String> resultA = Optional.of(string.replaceAll("^.*/([^/]+)$", "$1"));
</code>```

Substring approach:

```<code>int start = string.lastIndexOf('/');
Optional<String> resultB = Optional.of(start > 0 && start + 1 < string.length() ? string.substring(start) : null);
</code>```

There are plenty of more elaborate solutions for this problem on stackoverflow btw., so you might be better off with a thorough stackoverflow search.

Body:
I want to select specific substring from the input string:

String i = "example/test/foo-foo";

How to get only the substring foo-foo as a new string?

Expected output:

String newString = "foo-foo";

Body:
There are many options to solve that. For example via regex search/replace or the substring methods of class String.

Regex approach:

Optional<String> resultA = Optional.of(string.replaceAll("^.*/([^/]+)$", "$1"));

Substring approach:

int start = string.lastIndexOf('/');
Optional<String> resultB = Optional.of(start > 0 && start + 1 < string.length() ? string.substring(start) : null);

There are plenty of more elaborate solutions for this problem on stackoverflow btw., so you might be better off with a thorough stackoverflow search.


问:
vanilla js alternative to jquery method to perform safe html decode?
I've got a single dependency on jQuery that I don't want, and need a browser-safe method to decode server-side html encoded content.

The effect I'm going for is to replace an existing DOM element with the the html that gets decoded, along the following lines:

```<code>$('#targetId').replaceWith($('<div/>').html(value).text());
</code>```

where value contains an html-encoded string.

Alternatively, an more direct approach would also be welcome.

答:
Real world alternative. I mix some PHP because reasons.

var Lang = Lang || new Object();

Lang._t  = function(str) {
    var buf = [];

    for (var i=str.length-1;i>=0;i--) {
        buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
    }

    return buf.join('');
},

Lang.same_password = Lang._t(<?php echo json_encode($langtextos->same_password); ?>);

function foo(pass1, pass2){
   if( pass1 == pass2){
       message.innerHTML = Lang.same_pass;
       return false;
   }

   return true;
}```

Body:
I've got a single dependency on jQuery that I don't want, and need a browser-safe method to decode server-side html encoded content.

The effect I'm going for is to replace an existing DOM element with the the html that gets decoded, along the following lines:

$('#targetId').replaceWith($('
').html(value).text());

where value contains an html-encoded string.

Alternatively, an more direct approach would also be welcome.


问:
How do i turn an object array into a formgroup array?
I want to use the array function of the formbuilder in order to work with formcontrol arrays. I have an existing custom object array that needs to be added to that FormArray however it only takes FormGroup as arguments. How do I transform my array of custom objects into FormGroup objects so that those can be added into the FormArray? I've already tried this:

```<code>let formGroupArray: FormGroup[] = [];
    for(let i=0; i < account.laborperiods.length; i++){
      let formGroup = this.fb.group({
        id: this.account.laborperiods[i].id,
        beginDate: this.account.laborperiods[i].beginDate,
        endDate: this.account.laborperiods[i].endDate,
        hours: this.account.laborperiods[i].hours,
        account: this.account.laborperiods[i].account
      })
        formGroupArray.push(formGroup)
    }
    this.laborPeriodArray = new FormArray(formGroupArray);
</code>```

But this is giving me the error "ERROR TypeError: Circular reference in value argument not supported"

So can anyone tell me how I convert a custom object array into a FormGroup array? Or maybe there is a more convenient way where the custom object array can be transformed directly into a FormArray?

答:
Try:</p>

```<code>let formGroupArray:FormArray
for(let i=0; i < account.laborperiods.length; i++){
      let formGroup = this.fb.group({
          ...
      })
      if (!formGroupArray)
        formGroupArray=new FormArray(formGroup);
      else
        formGroupArray.push(formGroup)
}
//Change this line
this.laborPeriodArray = formGroupArray;
</code>```

Body:
I want to use the array function of the formbuilder in order to work with formcontrol arrays. I have an existing custom object array that needs to be added to that FormArray however it only takes FormGroup as arguments. How do I transform my array of custom objects into FormGroup objects so that those can be added into the FormArray? I've already tried this:

let formGroupArray: FormGroup[] = [];
    for(let i=0; i < account.laborperiods.length; i++){
      let formGroup = this.fb.group({
        id: this.account.laborperiods[i].id,
        beginDate: this.account.laborperiods[i].beginDate,
        endDate: this.account.laborperiods[i].endDate,
        hours: this.account.laborperiods[i].hours,
        account: this.account.laborperiods[i].account
      })
        formGroupArray.push(formGroup)
    }
    this.laborPeriodArray = new FormArray(formGroupArray);

But this is giving me the error "ERROR TypeError: Circular reference in value argument not supported"

So can anyone tell me how I convert a custom object array into a FormGroup array? Or maybe there is a more convenient way where the custom object array can be transformed directly into a FormArray?

Body:
Try:

let formGroupArray:FormArray
for(let i=0; i < account.laborperiods.length; i++){
      let formGroup = this.fb.group({
          ...
      })
      if (!formGroupArray)
        formGroupArray=new FormArray(formGroup);
      else
        formGroupArray.push(formGroup)
}
//Change this line
this.laborPeriodArray = formGroupArray;


问:
How to call observable that loads additional contents to a object transforming it in another observable?
I have this MyCollectionInteractor that loads all CollectionItemVO from a firebase database:

```<code>public interface MyCollectionInteractor extends BaseInteractor{
    Single<List<CollectionItemVO>> load ();
}
</code>```

CollectionItemVO is:

```<code>public class CollectionItemVO {
    String beerId;
    long timestamp;
    int quantity;

    public CollectionItemVO() {
    }

    public CollectionItemVO(String beerId, long timestamp, int quantity) {
        this.beerId = beerId;
        this.timestamp = timestamp;
        this.quantity = quantity;
    }
}
</code>```

So I have this CollectionItem:

```<code>public class CollectionItem {

    private final CollectionItemVO itemVOList;
    private final Beer beer;

    public CollectionItem(Beer beer, CollectionItemVO itemVOList) {
        this.beer = beer;
        this.itemVOList = itemVOList;
    }

}
</code>```

That has a complete Beer object. To load that object I use this other interactor:

```<code>public interface LoadBeerInteractor extends BaseInteractor {
    Flowable<Beer> load(String beerId);
}
</code>```

I want to transform this CollectionInteractor.load call into an Observable that emits CollectionItem and I want to use LoadBeerInteractor.load(beerId) to delivery CollectionItem with full beer object.

For what I studied, I believe it is possible to do that using flatmap but I have not been able to achieve the desired result yet.

答:
I think you need to do something like this:

```<code>MyCollectionInteractor collections = ...
LoadBeerInteractor beers = ...

Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMapIterable(it -> it) // unpack from Flow<List<T>> to Flow<T>
    .flatMap(it ->
        beers
            .load(it.beerId)
            .map(beer -> new CollectionItem(beer, it))
    )
</code>```

This might also work:

```<code>Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMap(list ->
        Flowable
            .from(list)
            .flatMap(it ->
                beers
                    .load(it.beerId)
                    .map(beer -> new CollectionItem(beer, it))
            )
    )
</code>```

Body:
I have this MyCollectionInteractor that loads all CollectionItemVO from a firebase database:

public interface MyCollectionInteractor extends BaseInteractor{
    Single<List<CollectionItemVO>> load ();
}

CollectionItemVO is:

public class CollectionItemVO {
    String beerId;
    long timestamp;
    int quantity;

    public CollectionItemVO() {
    }

    public CollectionItemVO(String beerId, long timestamp, int quantity) {
        this.beerId = beerId;
        this.timestamp = timestamp;
        this.quantity = quantity;
    }
}

So I have this CollectionItem:

public class CollectionItem {

    private final CollectionItemVO itemVOList;
    private final Beer beer;

    public CollectionItem(Beer beer, CollectionItemVO itemVOList) {
        this.beer = beer;
        this.itemVOList = itemVOList;
    }

}

That has a complete Beer object. To load that object I use this other interactor:

public interface LoadBeerInteractor extends BaseInteractor {
    Flowable<Beer> load(String beerId);
}

I want to transform this CollectionInteractor.load call into an Observable that emits CollectionItem and I want to use LoadBeerInteractor.load(beerId) to delivery CollectionItem with full beer object.

For what I studied, I believe it is possible to do that using flatmap but I have not been able to achieve the desired result yet.

Body:
I think you need to do something like this:

MyCollectionInteractor collections = ...
LoadBeerInteractor beers = ...

Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMapIterable(it -> it) // unpack from Flow<List<T>> to Flow<T>
    .flatMap(it ->
        beers
            .load(it.beerId)
            .map(beer -> new CollectionItem(beer, it))
    )

This might also work:

Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMap(list ->
        Flowable
            .from(list)
            .flatMap(it ->
                beers
                    .load(it.beerId)
                    .map(beer -> new CollectionItem(beer, it))
            )
    )


问:
Kotlin coroutines in Android: Why use bg() from Anko instead of async()?
I started using Kotlin coroutines on Android today and I noticed that Anko has its own set of helper methods for them. I understand why asReference() exists, but I can't figure out why bg() does, given that the core coroutines lib already has async().

The bg() code is quite simple and it uses async() inside:

```<code>@PublishedApi
internal var POOL = newFixedThreadPoolContext(2 * Runtime.getRuntime().availableProcessors(), "bg")

inline fun <T> bg(crossinline block: () -> T): Deferred<T> = async(POOL) {
    block()
}
</code>```

So what is the advantage of using bg() instead of async()? Is async() inefficient in some way for Android apps?

答:
As you can see, bg uses POOL as its CoroutineDispatcher, read about it here.

Basically this function only exists to wrap the pool in which these tasks are executed. Using async directly would require you to provide one. So in the end, each task started via bg is ensured to be executed in the same pool.

Body:
I started using Kotlin coroutines on Android today and I noticed that Anko has its own set of helper methods for them. I understand why asReference() exists, but I can't figure out why bg() does, given that the core coroutines lib already has async().

The bg() code is quite simple and it uses async() inside:

@PublishedApi
internal var POOL = newFixedThreadPoolContext(2 * Runtime.getRuntime().availableProcessors(), "bg")

inline fun <T> bg(crossinline block: () -> T): Deferred<T> = async(POOL) {
    block()
}

So what is the advantage of using bg() instead of async()? Is async() inefficient in some way for Android apps?


问:
How to create LAN among machines on internet
Say i have home PC and office PC (both Windows 7) having internet connections. How to bring them together on a LAN ?

Another is if there is an existing LAN, then how to join these PCs to that LAN ?

VPN ? If yes, How to identify each machine, which IP to use ?


问:
Find sql connected component between many to many entities
I have two basic entities: financial plan and purchase request. Theese two entities are in many-to-many relationship:

```<code>CREATE TABLE FinancialPlan
(
    ID int NOT NULL,
    PRIMARY KEY (ID)
);

CREATE TABLE PurchaseRequest
(
    ID int NOT NULL,
    PRIMARY KEY (ID)
);

CREATE TABLE FP_PR
(
    FP_ID FOREIGN KEY REFERENCES FinancialPlan(ID),
    PR_ID FOREIGN KEY REFERENCES PurchaseRequest(ID)
);
</code>```

Problem: find all requests, related to specified plan, and all plans, related to requests, related to specified plan, ...

Model could be represented as a graph, where each node represents a plan, or a request, and each edge represents a relationship, then the problem could be rephrased as find connected component, which specified node belongs to.

Example:

```<code>Plan     Request    FP_PR

ID  |    ID  |      FP_ID|PR_ID|
----|    ----|      -----|-----|
1   |    1   |      1    |1    |
2   |    2   |      2    |1    |
3   |    3   |      2    |2    |
4   |               3    |2    |
5   |               4    |2    |
                    5    |3    |
</code>```

Find connected component of finplan ID=1

Desired output:

```<code>FP_ID | PR_ID|
------+------+
1     | 1    |
2     | 1    |
2     | 2    |
3     | 2    |
4     | 2    |
</code>```

I am currently doing it recursively on app side, which may generate to many requests and hang the DB server, could this be done with some recursive DB approach?

Visualization:

Starting entity is marked by arrow.
Desired output is circled.

答:
SQL Server solution

I guess the main problem is you need to compare by PR_ID then FP_ID. So in recursive part there must be a CASE statement. On 1 run we take data by FP_ID on second by PR_ID and etc with the help of modulo.

```<code>DECLARE @fp int = 1

;WITH cte AS (
    SELECT  f.FP_ID,
            f.PR_ID,
            1 as lev
    FROM #FP_PR f
    WHERE f.FP_id = @fp
    UNION ALL
    SELECT  f.FP_ID,
            f.PR_ID,
            lev+1
    FROM cte c
    CROSS JOIN #FP_PR f -- You can use INNER JOIN instead
    WHERE CASE (lev+1)%2 WHEN 0 THEN f.PR_ID WHEN 1 THEN f.FP_ID END = CASE (lev+1)%2 WHEN 0 THEN c.PR_ID WHEN 1 THEN c.FP_ID END
    AND NOT (f.PR_ID = c.PR_ID AND f.FP_ID = c.FP_ID)
)

SELECT *
FROM cte
</code>```

Output:

```<code>FP_ID   PR_ID   lev
1       1       1
2       1       2
2       2       3
3       2       4
4       2       4
</code>```

Body:
I have two basic entities: financial plan and purchase request. Theese two entities are in many-to-many relationship:

CREATE TABLE FinancialPlan
(
    ID int NOT NULL,
    PRIMARY KEY (ID)
);

CREATE TABLE PurchaseRequest
(
    ID int NOT NULL,
    PRIMARY KEY (ID)
);

CREATE TABLE FP_PR
(
    FP_ID FOREIGN KEY REFERENCES FinancialPlan(ID),
    PR_ID FOREIGN KEY REFERENCES PurchaseRequest(ID)
);

Problem: find all requests, related to specified plan, and all plans, related to requests, related to specified plan, ...

Model could be represented as a graph, where each node represents a plan, or a request, and each edge represents a relationship, then the problem could be rephrased as find connected component, which specified node belongs to.

Example:

Plan     Request    FP_PR

ID  |    ID  |      FP_ID|PR_ID|
----|    ----|      -----|-----|
1   |    1   |      1    |1    |
2   |    2   |      2    |1    |
3   |    3   |      2    |2    |
4   |               3    |2    |
5   |               4    |2    |
                    5    |3    |

Find connected component of finplan ID=1

Desired output:

FP_ID | PR_ID|
------+------+
1     | 1    |
2     | 1    |
2     | 2    |
3     | 2    |
4     | 2    |

I am currently doing it recursively on app side, which may generate to many requests and hang the DB server, could this be done with some recursive DB approach?

Visualization:

Starting entity is marked by arrow.
Desired output is circled.

Body:
SQL Server solution

I guess the main problem is you need to compare by PR_ID then FP_ID. So in recursive part there must be a CASE statement. On 1 run we take data by FP_ID on second by PR_ID and etc with the help of modulo.

DECLARE @fp int = 1

;WITH cte AS (
    SELECT  f.FP_ID,
            f.PR_ID,
            1 as lev
    FROM #FP_PR f
    WHERE f.FP_id = @fp
    UNION ALL
    SELECT  f.FP_ID,
            f.PR_ID,
            lev+1
    FROM cte c
    CROSS JOIN #FP_PR f -- You can use INNER JOIN instead
    WHERE CASE (lev+1)%2 WHEN 0 THEN f.PR_ID WHEN 1 THEN f.FP_ID END = CASE (lev+1)%2 WHEN 0 THEN c.PR_ID WHEN 1 THEN c.FP_ID END
    AND NOT (f.PR_ID = c.PR_ID AND f.FP_ID = c.FP_ID)
)

SELECT *
FROM cte

Output:

FP_ID   PR_ID   lev
1       1       1
2       1       2
2       2       3
3       2       4
4       2       4


问:
RabbitMQ Mirrored Queues on Multiple Clusters
Is it possible to use RabbitMQ HA using multiple(2) RabbitMQ clusters?

Here is my requirement:

We have 2 RabbitMQ clusters (each with 4 nodes). All the nodes in both the clusters will be using same Erlang cookie. So that, even though these 2 clusters are physically in separate locations, but will act as a single cluster with 8 nodes.

We are planning to use HAProxy to load balance both the clusters (8 nodes). Both publisher and consumer will be using this proxy to connect to the broker.

We would like to use mirrored queues for HA with ha-mode:exactly, ha-params:4, ha-sync-mode:automatic along with auto-heal for cluster_partition_handling.

Question:

In case of HA, is there a way we can specify to use 2 nodes from the first cluster and 2 nodes from the second cluster. As I understand, this can be done via policy ha-mode:nodes and use node names but that way it will always use the same node, can this setup be dynamic?

As both the clusters are very reliable, will it be the right approach to use auto-heal for cluster_partition_handling (in case of split brain)?

As per this "By default, queues within a RabbitMQ cluster are located on a single node (the node on which they were first declared). This is in contrast to exchanges and bindings, which can always be considered to be on all nodes.". Does this mean exchanges are mirrored by default? So when a message arrives at an exchange and that node goes down, will the message be available on the other exchange on the other node?

答:
The RabbitMQ team monitors this mailing list and only sometimes answers questions on StackOverflow.

So that, even though these 2 clusters are physically in separate locations, but will act as a single cluster with 8 nodes.

Please do not do this. RabbitMQ clusters require reliable network connections with low latency. If your cluster crosses a WAN or availability zone your chance of having network partitions greatly increases. See this section of the docs for more information. You should use either the shovel or federation feature.

Does this mean exchanges are mirrored by default? So when a message arrives at an exchange and that node goes down, will the message be available on the other exchange on the other node?

Yes and yes.


问:
Yii 1.1: Forms --> define correct minimum rule
since hours i am trying to find out what the problem could be here:

--> I have a Yii Form looks like this:

```<code><?php $form=$this->beginWidget('CActiveForm', array(
                        'id'=>'withdrawal-request-form',
                        'enableAjaxValidation'=>true,
                    )); ?>
...
...
...

$form->textField($model,'amount', array(
           'class' => 'form-control name-field',
           'placeholder' => $model->getAttributeLabel('Amount'),
           'type' => 'number',
           'min' => 10));
</code>```

then i have my controller rules defined like this:

```<code>public function rules()
{
    return array(
        // username and password are required
        array('IBAN, BIC, amount, payment_id, email', 'required'),
        array('payment_id', 'numerical', 'integerOnly'=>true),
        array('email', 'email'),
        array('amount', 'numerical', 'min'=>10)
    );
}
</code>```

My goal to disallow values less then '10'

** what i have tried already**

The really strange thing is all other rules, like 'required', and wrong email field without @ letter etc. works really really great, so the connection between the form and the rules are working great. This test was successfull

When i try to enter a letter e.g. an "A" into my amount field, i am gettin imediatley an red HTML5 error back (perfect, works also fine)

but when i try to enter a number less then 10 for examnple 1 --> then i am getting no error back (first strange thing) and the next big problem is, after submit, i am getting only a blank white page back :(

i have also added this here "enableClientValidation'=>true" to my Form Code (also no success)

and then I have also tried to implement some validation rules directly into the yii form element like this
here:

$form->textField($model,'amount', array(
                                'class' => 'form-control name-field',
                                'placeholder' => $model->getAttributeLabel('Amount'),
                                'type' => 'number',
                                'min' => '10'

--> also no success!

the crazy thing is when i remove my

```<code>array('amount', 'numerical', 'min'=>10)
</code>```

rule out of my rules block, the submit an redirect process works great! but then i have numbers less then 10 in there becasue the "min=10 rule" was removed. BUT

when i add this line here again in to my rules

```<code>array('amount', 'numerical', 'min'=>10)
</code>```

and then i am entering "1" into the amount field and then submit the form, yii is only displaying a white page!

so yii is recognizing, that i have entered a wrong value, but is only showing a white page

YES, I have already tried to check the log file. no new entry!!

YES, I have also reading the manual, but i followed exactly the steps and the way to set some new rules...

I really have no idea what the problem could be :(

Could you maybe give me any hint?!?

Thank you so much for any help!

Edit:
ok I have found out, that the problem is that in my controller my
    $model->validate()
is not true, and thats why the whole script will be skipped... i will check everything again and give a feedback here soon.

答:
oh my god :)

I have found my bug!

the thing is, my rules / validation part was working perfectly the whole time! The white page cam only beacuse in my controller there was and if block like this defined:

```<code>if(validation){
    // do great stuff
}
</code>```

but there was no !validation part defined, thats why after submit unvalid values, i only get an empty white blank page ;)

so if anybody will have a similar problem in the future!

Check Your Controller, if you have defined 2 cases

success case (validation part is ok)
error case (validation part is invalid)

then you can redirect to the same page and let the user know something like

"You have entered an invalid amount. Minimum is 10.00$"

by settin some Yii errors and display them at the same page near the text fields where the user have entered the wrong amounts...

i did it now like this:

```<code>if($_POST['WithdrawalRequestForm']['amount'] < 10){
                Yii::app()->user->setFlash('error', "Please enter a wihtdraw amount with at aleast 10.00 €");
                $this->redirect('withdrawalRequest');
            }
</code>```

Hope this will help other peoples also! ;)

Body:
since hours i am trying to find out what the problem could be here:

--> I have a Yii Form looks like this:

<?php $form=$this->beginWidget('CActiveForm', array(
                        'id'=>'withdrawal-request-form',
                        'enableAjaxValidation'=>true,
                    )); ?>
...
...
...

$form->textField($model,'amount', array(
           'class' => 'form-control name-field',
           'placeholder' => $model->getAttributeLabel('Amount'),
           'type' => 'number',
           'min' => 10));

then i have my controller rules defined like this:

public function rules()
{
    return array(
        // username and password are required
        array('IBAN, BIC, amount, payment_id, email', 'required'),
        array('payment_id', 'numerical', 'integerOnly'=>true),
        array('email', 'email'),
        array('amount', 'numerical', 'min'=>10)
    );
}

My goal to disallow values less then '10'

** what i have tried already**

The really strange thing is all other rules, like 'required', and wrong email field without @ letter etc. works really really great, so the connection between the form and the rules are working great. This test was successfull

When i try to enter a letter e.g. an "A" into my amount field, i am gettin imediatley an red HTML5 error back (perfect, works also fine)

but when i try to enter a number less then 10 for examnple 1 --> then i am getting no error back (first strange thing) and the next big problem is, after submit, i am getting only a blank white page back :(

i have also added this here "enableClientValidation'=>true" to my Form Code (also no success)

and then I have also tried to implement some validation rules directly into the yii form element like this
here:

$form->textField($model,'amount', array(
                                'class' => 'form-control name-field',
                                'placeholder' => $model->getAttributeLabel('Amount'),
                                'type' => 'number',
                                'min' => '10'

--> also no success!

the crazy thing is when i remove my

array('amount', 'numerical', 'min'=>10)

rule out of my rules block, the submit an redirect process works great! but then i have numbers less then 10 in there becasue the "min=10 rule" was removed. BUT

when i add this line here again in to my rules

array('amount', 'numerical', 'min'=>10)

and then i am entering "1" into the amount field and then submit the form, yii is only displaying a white page!

so yii is recognizing, that i have entered a wrong value, but is only showing a white page

YES, I have already tried to check the log file. no new entry!!

YES, I have also reading the manual, but i followed exactly the steps and the way to set some new rules...

I really have no idea what the problem could be :(

Could you maybe give me any hint?!?

Thank you so much for any help!

Edit:
ok I have found out, that the problem is that in my controller my
    $model->validate()
is not true, and thats why the whole script will be skipped... i will check everything again and give a feedback here soon.

Body:
oh my god :)

I have found my bug!

the thing is, my rules / validation part was working perfectly the whole time! The white page cam only beacuse in my controller there was and if block like this defined:

if(validation){
    // do great stuff
}

but there was no !validation part defined, thats why after submit unvalid values, i only get an empty white blank page ;)

so if anybody will have a similar problem in the future!

Check Your Controller, if you have defined 2 cases

success case (validation part is ok)
error case (validation part is invalid)

then you can redirect to the same page and let the user know something like

"You have entered an invalid amount. Minimum is 10.00$"

by settin some Yii errors and display them at the same page near the text fields where the user have entered the wrong amounts...

i did it now like this:

if($_POST['WithdrawalRequestForm']['amount'] < 10){
                Yii::app()->user->setFlash('error', "Please enter a wihtdraw amount with at aleast 10.00 €");
                $this->redirect('withdrawalRequest');
            }

Hope this will help other peoples also! ;)


问:
How Do I Clear The Credentials In AWS Configure?
I have deleted the AWS credentials in sudo nano ~/.aws/config. But, the credentials are still in aws configure. Is there a way to reset aws configure with clear state?

答:
Do not delete the files if you have multiple profiles created as all will be lost if you delete these files!
unless thats what you want :)

Go to each of the file -

```<code> - ~/.aws/credentials
 - ~/.aws/config
</code>```

and remove just the part profiles you want to delete. Eg.

~/.aws/credentials

```<code>[default]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey

[user2]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey
</code>```

and

~/.aws/config

```<code>[default]
region=us-west-2
output=json

[profile user2]
region=us-east-1
output=text
</code>```

Just delete entries corresponding to user2 profile if thats what you want. And you should also give a profile name to profile you configure -

```<code>aws configure --profile user2
</code>```

Else it will just be [default]

More details - http://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html

Body:
Do not delete the files if you have multiple profiles created as all will be lost if you delete these files!
unless thats what you want :)

Go to each of the file -

 - ~/.aws/credentials
 - ~/.aws/config

and remove just the part profiles you want to delete. Eg.

~/.aws/credentials

[default]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey

[user2]
aws_access_key_id=yourAccessKeyId
aws_secret_access_key=yourSecretAccessKey

and

~/.aws/config

[default]
region=us-west-2
output=json

[profile user2]
region=us-east-1
output=text

Just delete entries corresponding to user2 profile if thats what you want. And you should also give a profile name to profile you configure -

aws configure --profile user2

Else it will just be [default]

More details - http://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html


问:
Positionning button from bottom screen
I am doing some XML for an android app.

I have images, text, and button in my view.

I used a Linear layout, but I think it's not what I need.

I would like to set my last button to 80 dp from the bottom screen. Regardless the smartphone and the size of the screen.
I want my button to be at 80 dp from the bottom of all device.

I have no idea how to do it if someone can help me it could be cool!

I tried with a LinearLayout but i think i can't do it.

Now I'm trying with a constraintLayout but I'm not sure it will work.

Thanks

答:
This is one of the ways to achieve your goal using Relative layout as parent:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bottom Button"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="80dp"/>

</RelativeLayout>
</code>```

Title: Positionning button from bottom screen

Body:
This is one of the ways to achieve your goal using Relative layout as parent:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bottom Button"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="80dp"/>

</RelativeLayout>


问:
Javascript Comparing String Not Working
I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.

This is my HTML Code:

```<code> <label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">
</code>```

This is my javascript code:

```<code>        <script>
        function val() {
        var input = document.getElementById("freightcostmode_insert").value;
        var calculation = document.getElementById("freightCost_insert").value;
        if(inputing == "Percentage"){
            document.getElementById('freight').value = calculation*1.5;
        }if else(inputing == 'Monetary'){

        }

        }
        </script>
</code>```

答:
Working Code

function val() {
  var input = document.getElementById("freightcostmode_insert").value,
    calculation = document.getElementById("freightcost_insert").value

  document.getElementById('freight').value = input === "Percentage" ?
    calculation * 1.5 : calculation * 2.5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
   <option>Percentage</option>
   <option>Monetary</option>

 </select>

<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight"></code>```

Title: Javascript Comparing String Not Working

Body:
I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.

This is my HTML Code:

 Freight Cost Mode
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">

This is my javascript code:

Body:
Working Code

function val() {
  var input = document.getElementById("freightcostmode_insert").value,
    calculation = document.getElementById("freightcost_insert").value

  document.getElementById('freight').value = input === "Percentage" ?
    calculation * 1.5 : calculation * 2.5;
}

<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
   <option>Percentage</option>
   <option>Monetary</option>

 </select>

<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">


问:
Keyboard shortcut to run maven goals in Intellij IDEA?
Is there a way to run a maven goal using keyboard shortcut in Intellij IDEA?</p>

答:
Pretty old question but still of interest (at least for me):

So, for IntelliJ 2017 go to Preferences | Keymap then assign your shortcut to Plug-ins | Maven Integration | Execute Maven Goal


问:
Why Error "System.String does not contain a method named 'AppendChild'"
Why does this PowerShell Script not work:

[xml]$xml = '<products></products>'

$newproduct = $xml.CreateElement('product')
$attr = $xml.CreateAttribute('code')
$attr.Value = 'id1'
$newproduct.Attributes.Append($attr)

$products = $xml.products
$products.AppendChild($newproduct)
```

<p>Error is</p>

<pre class="lang-none prettyprint-override"><code>Method invocation failed because [System.String] does not contain a method named 'AppendChild'.
At line:1 char:1
+ $products.AppendChild($newproduct)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
</code>```

If I replace

$products = $xml.products
```

<p>by</p>

<pre class="lang-psh prettyprint-override"><code>$products = $xml.SelectSingleNode('//products')
</code>```

it will work, but I'd like to know why first syntax does not work because it is illogical for me. $xml.products should be a valid XML object and thus provide the method AppendChild().

答:
```<code>$xml.configuration.SelectSingleNode("connectionStrings").AppendChild($newnode)
</code>```

would work fine, but an interesting & dirty hack: given this empty node:

```<code>  <connectionStrings>
  </connectionStrings>
</code>```

the script

```<code>$xml.configuration.connectionStrings.AppendChild($newnode)
</code>```

gives a "Method invocation failed because [System.String] does not contain a method named 'AppendChild'" error

but this:

```<code>  <connectionStrings>
        <!-- random comment -->
  </connectionStrings>
</code>```

works perfectly fine

Body:
Why does this PowerShell Script not work:

[xml]$xml = '<products></products>'

$newproduct = $xml.CreateElement('product')
$attr = $xml.CreateAttribute('code')
$attr.Value = 'id1'
$newproduct.Attributes.Append($attr)

$products = $xml.products
$products.AppendChild($newproduct)

Error is

Method invocation failed because [System.String] does not contain a method named 'AppendChild'.
At line:1 char:1
+ $products.AppendChild($newproduct)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

If I replace

$products = $xml.products

by

$products = $xml.SelectSingleNode('//products')

it will work, but I'd like to know why first syntax does not work because it is illogical for me. $xml.products should be a valid XML object and thus provide the method AppendChild().

Body:
$xml.configuration.SelectSingleNode("connectionStrings").AppendChild($newnode)

would work fine, but an interesting & dirty hack: given this empty node:

  <connectionStrings>
  </connectionStrings>

the script

$xml.configuration.connectionStrings.AppendChild($newnode)

gives a "Method invocation failed because [System.String] does not contain a method named 'AppendChild'" error

but this:

  <connectionStrings>
        <!-- random comment -->
  </connectionStrings>

works perfectly fine


问:
How can I add a value in my list when a condition is true?
I have a dict with alot of items:

```<code>{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}
</code>```

I need to create a list with all three elements inside.
I'm expecting a list like this:

```<code><type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]
</code>```

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

```<code>for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])
</code>```

The problem is I get this list all time splitet:

```<code><type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]
</code>```

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

答:
You can use defaultdict() with a default list of 2 items to make it more flexible:

```<code>from collections import defaultdict

def default_list():
    return [None, None]

request = {'id-quantity-60': u'1', 'id-quantity-71': u'0', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on'}
result = defaultdict(default_list)

for key, value in request.items():
  _, pattern, productid = key.split('-')

  if pattern == 'quantity':
    result[productid][0] = value
    result[productid][1] = 'on' if int(value) else 'off'
  elif pattern == 'product':
    result[productid][1] = value
</code>```

Returns:

```<code>defaultdict(<function default_list at 0x7faa3d3efe18>,
            {'35': ['3', 'on'],
             '60': ['1', 'on'],
             '71': ['0', 'off']})
</code>```

In case you really need a list:

```<code>resultList = [[k]+v for (k,v) in result.items()]
>>> [['60', '1', 'on'], ['71', '0', 'off'], ['35', '3', 'on']]
</code>```

Body:
I have a dict with alot of items:

{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

I need to create a list with all three elements inside.
I'm expecting a list like this:

<type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])

The problem is I get this list all time splitet:

<type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

Body:
You can use defaultdict() with a default list of 2 items to make it more flexible:

from collections import defaultdict

def default_list():
    return [None, None]

request = {'id-quantity-60': u'1', 'id-quantity-71': u'0', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on'}
result = defaultdict(default_list)

for key, value in request.items():
  _, pattern, productid = key.split('-')

  if pattern == 'quantity':
    result[productid][0] = value
    result[productid][1] = 'on' if int(value) else 'off'
  elif pattern == 'product':
    result[productid][1] = value

Returns:

defaultdict(<function default_list at 0x7faa3d3efe18>,
            {'35': ['3', 'on'],
             '60': ['1', 'on'],
             '71': ['0', 'off']})

In case you really need a list:

resultList = [[k]+v for (k,v) in result.items()]
>>> [['60', '1', 'on'], ['71', '0', 'off'], ['35', '3', 'on']]


问:
TYPO3 Custom Element colorpicker
I'm new to TYPO3 (first project) and I have some understanding issues of the creation of a custom element with a colorpicker. In this project I already have created a few elements but I only use predetermined fields for the backend input. For the element I need next I need the user to choose a color. I haven't found a fitting existing element. My setup that doesn't work is in the TCA/Overrides/tt_content.php file and looks like this.

```<code>$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Color';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
    'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
        header;Title,
        subheader;Background,
        header_link;Target,
        item_0;Color,
        bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
        ');
</code>```

The item_0 was a try to create a colorpicker but it doesn't seem to work. Do I need something different in a different file? The first few lines I added to define my field. Is there a better way to do this?

All other files in my custom extension work (since all other custom elements work fine). The only difference is, as said, the need of a way to choose a color in the new one.

Just for a clearer look here the other files

setup.txt:

```<code>lib.contentElement {
  templateRootPaths {
    100 = EXT:wostyle/Resources/Private/Template
  }
}
tt_content {
    wo_mitem < lib.contentElement
    wo_mitem {
        templateName = MItem
    }
}
</code>```

tt_content.php

```<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
   array(
      'WO_Item (ItemBox, Text only)',
      'wo_mitem',
      'content-image'
   ),
   'CType',
   'wostyle'
);

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Farbe';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');
</code>```

typo.ts

```<code>mod.wizards.newContentElement.wizardItems.wo_extra {
   header = WO Elemente
   after = common
  elements {
    wo_mitem {
         iconIdentifier = content-image
         title = WO_Item (ItemBox, Text only)
         description = Ein Produktfeld mit Text
         tt_content_defValues {
            CType = wo_mitem
         }
      }
   }
   show := addToList(wo_mitem)
}
</code>```

MItem.html

```<code><div class="item-text">
    <f:link.typolink parameter="{data.header_link}">
        <div class="item-front">
            <f:if condition="{data.subheader}!=''">
            <f:then>
            <div class="item-bg">
                <f:format.html>{data.subheader}</f:format.html>
            </div>
            </f:then>
            </f:if>
            <div class="item-title">
                <f:format.html>{data.header}</f:format.html>
            </div>
        </div>
        <div class="item-back">
            <f:format.html>{data.bodytext}</f:format.html>
        </div>
    </f:link.typolink>
</div>
<f:debug>{data}</f:debug>
</code>```

EDIT: I use typo3 8.7.8

答:
With the help of webMan and some internet searches I could adopt my code a little.
I added the file "ext_tables.sql" with the content

```<code>CREATE TABLE tt_content (
    item_0 varchar(10) DEFAULT '' NOT NULL,
);
</code>```

And changed the tt_content.php in TCA/Overrides to:

```<code>$temporaryColumns = Array(
    "item_0" => Array(
        'label' => 'Color',
        'config' => Array(
            'type' => 'input',
            'renderType' => 'colorpicker',
            'size' => 10
        )
    )
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content',$temporaryColumns);

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');
</code>```

There are still a view things missing in compare to webMans code but at least this is the first working version I have so i figured i show it since my question is answered:).

Title: TYPO3 Custom Element colorpicker

Body:
I'm new to TYPO3 (first project) and I have some understanding issues of the creation of a custom element with a colorpicker. In this project I already have created a few elements but I only use predetermined fields for the backend input. For the element I need next I need the user to choose a color. I haven't found a fitting existing element. My setup that doesn't work is in the TCA/Overrides/tt_content.php file and looks like this.

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Color';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
    'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
        header;Title,
        subheader;Background,
        header_link;Target,
        item_0;Color,
        bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
        ');

The item_0 was a try to create a colorpicker but it doesn't seem to work. Do I need something different in a different file? The first few lines I added to define my field. Is there a better way to do this?

All other files in my custom extension work (since all other custom elements work fine). The only difference is, as said, the need of a way to choose a color in the new one.

Just for a clearer look here the other files

setup.txt:

lib.contentElement {
  templateRootPaths {
    100 = EXT:wostyle/Resources/Private/Template
  }
}
tt_content {
    wo_mitem < lib.contentElement
    wo_mitem {
        templateName = MItem
    }
}

tt_content.php

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
   array(
      'WO_Item (ItemBox, Text only)',
      'wo_mitem',
      'content-image'
   ),
   'CType',
   'wostyle'
);

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Farbe';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');

typo.ts

mod.wizards.newContentElement.wizardItems.wo_extra {
   header = WO Elemente
   after = common
  elements {
    wo_mitem {
         iconIdentifier = content-image
         title = WO_Item (ItemBox, Text only)
         description = Ein Produktfeld mit Text
         tt_content_defValues {
            CType = wo_mitem
         }
      }
   }
   show := addToList(wo_mitem)
}

MItem.html

    <f:link.typolink parameter="{data.header_link}">

            <f:if condition="{data.subheader}!=''">
            <f:then>

                <f:format.html>{data.subheader}</f:format.html>

            </f:then>
            </f:if>

                <f:format.html>{data.header}</f:format.html>

            <f:format.html>{data.bodytext}</f:format.html>

    </f:link.typolink>

<f:debug>{data}</f:debug>

EDIT: I use typo3 8.7.8

Body:
With the help of webMan and some internet searches I could adopt my code a little.
I added the file "ext_tables.sql" with the content

CREATE TABLE tt_content (
    item_0 varchar(10) DEFAULT '' NOT NULL,
);

And changed the tt_content.php in TCA/Overrides to:

$temporaryColumns = Array(
    "item_0" => Array(
        'label' => 'Color',
        'config' => Array(
            'type' => 'input',
            'renderType' => 'colorpicker',
            'size' => 10
        )
    )
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content',$temporaryColumns);

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');

There are still a view things missing in compare to webMans code but at least this is the first working version I have so i figured i show it since my question is answered:).


问:
Run uglify js on windows
I want to run this command from npm

```<code>./node_modules/uglify-js/bin/uglifyjs dist/bundles/npm-module-seed.umd.js --screw-ie8 --compress --mangle --comments --output dist/bundles/npm-module-seed.umd.min.js
</code>```

I get .' is not recognized as an internal or external command,

Omiting ./ gives : node_modules' is not recognized as an internal or external command,

Can somebody help me please?

答:
The same command should be working without providing the full path to uglifyjs. Use the package exposed commands instead, at the root of your project:</p>

```<code>uglifyjs dist/bundles/npm-module-seed.umd.js --screw-ie8 --compress --mangle --comments --output dist/bundles/npm-module-seed.umd.min.js
</code>```

Title: Run uglify js on windows

Body:
I want to run this command from npm

./node_modules/uglify-js/bin/uglifyjs dist/bundles/npm-module-seed.umd.js --screw-ie8 --compress --mangle --comments --output dist/bundles/npm-module-seed.umd.min.js

I get .' is not recognized as an internal or external command,

Omiting ./ gives : node_modules' is not recognized as an internal or external command,

Can somebody help me please?

Body:
The same command should be working without providing the full path to uglifyjs. Use the package exposed commands instead, at the root of your project:

uglifyjs dist/bundles/npm-module-seed.umd.js --screw-ie8 --compress --mangle --comments --output dist/bundles/npm-module-seed.umd.min.js


问:
Pandas to_datetime loses timezone
My raw data has a column with timestamps in ISO8601 format like this:

'2017-07-25T06:00:02+02:00'

Since the data is in CSV format, it will be read as object/string. Therefore I'm converting it to datetime like this.

```<code>import pandas pd
df['time'] = pd.to_datetime(df['time'], utc=False)

#df['time'][0]
df['time'][0].isoformat()
</code>```

Unfortunately this results in UTC timestamps and the timezone is lost. For instance df['time'][0].tzinfo is not set.

Timestamp('2017-07-25 04:00:02')

'2017-07-25T04:00:02'

I'm looking for a way to keep the timezone info in each of the timezone objects. But without re-setting it to CEST (Central European Summer Time) afterwards since this information is already included in the ISO8601 timezone offset in the raw-data. Any idea how to do this?

答:
So here's how I solved it.

There's a great article about Timezones and Python, which helped me to come to a solution. It relies on the ISO8601 Python packages.

```<code>import iso8601

times = ['2017-07-25 06:00:02+02:00',
         '2017-07-25 08:15:08+02:00',
         '2017-07-25 12:08:00+02:00',
         '2017-07-25 13:10:12+02:00',
         '2017-07-25 15:11:55+02:00',
         '2017-07-25 16:00:00+02:00'
        ]

df = pd.DataFrame(times, columns=['time'])
df['time'] = df['time'].apply(iso8601.parse_date)
df['time'][0]
</code>```

Which produces the following output and keeps the timezone information.

Timestamp('2017-07-25 06:00:02+0200', tz='+02:00')

Title: Pandas to_datetime loses timezone

Body:
My raw data has a column with timestamps in ISO8601 format like this:

'2017-07-25T06:00:02+02:00'

Since the data is in CSV format, it will be read as object/string. Therefore I'm converting it to datetime like this.

import pandas pd
df['time'] = pd.to_datetime(df['time'], utc=False)

#df['time'][0]
df['time'][0].isoformat()

Unfortunately this results in UTC timestamps and the timezone is lost. For instance df['time'][0].tzinfo is not set.

Timestamp('2017-07-25 04:00:02')

'2017-07-25T04:00:02'

I'm looking for a way to keep the timezone info in each of the timezone objects. But without re-setting it to CEST (Central European Summer Time) afterwards since this information is already included in the ISO8601 timezone offset in the raw-data. Any idea how to do this?

Body:
So here's how I solved it.

There's a great article about Timezones and Python, which helped me to come to a solution. It relies on the ISO8601 Python packages.

import iso8601

times = ['2017-07-25 06:00:02+02:00',
         '2017-07-25 08:15:08+02:00',
         '2017-07-25 12:08:00+02:00',
         '2017-07-25 13:10:12+02:00',
         '2017-07-25 15:11:55+02:00',
         '2017-07-25 16:00:00+02:00'
        ]

df = pd.DataFrame(times, columns=['time'])
df['time'] = df['time'].apply(iso8601.parse_date)
df['time'][0]

Which produces the following output and keeps the timezone information.

Timestamp('2017-07-25 06:00:02+0200', tz='+02:00')


问:
How to pack Java Desktop Application made using eclipse with MySQL database with all the Data?
I have made a JAVA Desktop Application using Eclipse and MySQL as a database. I want to use the application in another PC with all my created schema and data. How can I bundle or make an installation file so that it installs mysql with the required schema and the JAR file of my application into another pc?

Note: I know we can use embedded Database like H2, Sqlite but I want it to be done using MySQL only. So no suggestions on using other database for my application.

答:
Not sure how your application architecture but below point or solution could help you.

Solution 1 :

You can create DDL for schema database and the insert data. Once your application successfully install, you just run the script to execute this DDL file. Can be done in automation installation script.

Solution 2 :

You can dump mysql and restore to other PC. No worry about the structure, it completely clone from the original including data. Can be done in automation installation script. Dump mysqlDB link

Solution 3 (not recommended):

You can copy entire mysql data in directory and paste to other machine mysql directory. Based on my experience, never success.  But look at this guy link

There is a pro and cons using embedded SQL or centralize SQL. If you stick with this kind of architecture, you should consider use embedded SQL like you mention.


问:
How to use two href in single anchor tag
I did this way its executing printInvoice only, but I'm unable to execute PrintOrder, I want to execute both by just single clicking submit

```<code><a href="PrintInvoice?invoiceID=<s:property value="invDetail.arInvNum"/>"
   href="PrintOrder?orderID=<s:property value="ordDetail.orderID"/>"> submit
</a>
</code>```

答:
You can call two separate functions on click of submit.

Let's assume submit is a button.

You can call two separate functions on click of submit.

Let's assume submit is a button.

```<code><button onclick="printInvoice('<s:property value='+invDetail.arInvNum+'/>');printOrder('<s:property value='+ordDetail.orderID+'/>');">Submit</button>
</code>```

You can do similar for anchor tag you have used.

your functions might be:

```<code>function printInvoice(invoiceId){
    document.location.href = "PrintInvoice?invoiceID="+invoiceId;
}

function printOrder(orderId){
    document.location.href = "PrintOrder?orderID="+orderID;
}
</code>```

Body:
I did this way its executing printInvoice only, but I'm unable to execute PrintOrder, I want to execute both by just single clicking submit

<a href="PrintInvoice?invoiceID=<s:property value="invDetail.arInvNum"/>"
   href="PrintOrder?orderID=<s:property value="ordDetail.orderID"/>"> submit

Body:
You can call two separate functions on click of submit.

Let's assume submit is a button.

You can call two separate functions on click of submit.

Let's assume submit is a button.

<button onclick="printInvoice('<s:property value='+invDetail.arInvNum+'/>');printOrder('<s:property value='+ordDetail.orderID+'/>');">Submit</button>

You can do similar for anchor tag you have used.

your functions might be:

function printInvoice(invoiceId){
    document.location.href = "PrintInvoice?invoiceID="+invoiceId;
}

function printOrder(orderId){
    document.location.href = "PrintOrder?orderID="+orderID;
}


问:
Keep cells format while getting cells values from Excel
I am getting cells value from excel file into object matrix by using this:

```<code>Object[,] values = (Object[,])worksheet.UsedRange.Cells.Value;
</code>```

The issue is because in the excel I sometimes have decimal numbers and sometimes percent numbers.

When calling Cells.Value, I am getting percent number in decimal format. For example for the number 60.32% I get 0.6032 in values and I would like to keep this decimal format and get 60.32%.

I've tried by using worksheet.UsedRange.Cells.Text but it returns me null as UsedRange.Cells has different formats in excel.

So, how could I keep percentage in the number?

答:
For ClosedXML API: Instead of UsedRange.Cells.Value try with UsedRange.Cells.GetFormattedString()

If you are working with interop API, you need to do some extra work on your side.

If all cells in range are formatted as percentage, then you can get format using Range.NumberFormat and then accordingly you can multiply each cell value by 100 and appending '%' character to the end.

Range.NumberFormat will return null, if cells present in range are of different types.Then you need to iterate through each cell present in that particular range. Check NumberFormat for particular cell (E.g. ((Range)wks.Cells[1,1]).NumberFormat) and perform operation accordingly.

Body:
I am getting cells value from excel file into object matrix by using this:

Object[,] values = (Object[,])worksheet.UsedRange.Cells.Value;

The issue is because in the excel I sometimes have decimal numbers and sometimes percent numbers.

When calling Cells.Value, I am getting percent number in decimal format. For example for the number 60.32% I get 0.6032 in values and I would like to keep this decimal format and get 60.32%.

I've tried by using worksheet.UsedRange.Cells.Text but it returns me null as UsedRange.Cells has different formats in excel.

So, how could I keep percentage in the number?


问:
How to capture mouse movements C# form application?
How to capture mouse movements C# form application?</p>

答:
This one works for ALL controls within the form. NOT just the form itself!</p>

```<code>    ....
InitializeComponent();
        foreach (Control ctrl in this.Controls)
                {
                    ctrl.MouseMove += new MouseEventHandler(globalMouseMove);
                }
    ....

     private void globalMouseMove(object sender, MouseEventArgs e)
            {
                //TODO
            }
</code>```

Body:
This one works for ALL controls within the form. NOT just the form itself!

    ....
InitializeComponent();
        foreach (Control ctrl in this.Controls)
                {
                    ctrl.MouseMove += new MouseEventHandler(globalMouseMove);
                }
    ....

     private void globalMouseMove(object sender, MouseEventArgs e)
            {
                //TODO
            }