问:
How do we make keyboard appear below textView in swift?
I have done keyboard appearing below textfield using

on View did Load adding a observer()

```<code>    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
</code>```

And then updating the frame

```<code>weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}
</code>```

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

答:
Find the correct height of keyboard and assign it to the bottom constraint of the textView or reduce the y position of textView.
Like:

Step-1:
make a property keyboardHeight in you viewController.

var keyboardHeight: CGFloat = 0.0

Step-2: Make @IBOutlet of bottom constraint of the textView.

@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!

Step-3:

```<code>fileprivate func addKeyboardNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

fileprivate func removeKeyboardNotification() {
    IQKeyboardManager.shared().isEnabled = true
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
</code>```

Copy & paste these functions to your view controllers, and call self.addKeyboardNotification() in viewDidLoad() and  of you viewController

Step-4:

```<code>deinit {
    self.removeKeyboardNotification()
}
</code>```

also add this code to your viewController.

Step-5:

```<code>    func keyboardWillShow(_ notification: Notification) {
    if let keboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue, self.keyboardHeight <= 0.0 {
        self.keyboardHeight = keboardFrame.height + 45.0 //(Add 45 if your keyboard have toolBar if not then remove it)
    }

    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = self.keyboardHeight
    }, completion: { (success) in
    })
}

func keyboardWillHide(_ notification: Notification) {
    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = 0.0
    }, completion: { (success) in
    })
}
</code>```

That's it to manage the textView with keyboard.
If you don't want to use textViewBottomConstraint the you can work with the y position of the textView.

Body:
I have done keyboard appearing below textfield using

on View did Load adding a observer()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

And then updating the frame

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

Body:
Find the correct height of keyboard and assign it to the bottom constraint of the textView or reduce the y position of textView.
Like:

Step-1:
make a property keyboardHeight in you viewController.

var keyboardHeight: CGFloat = 0.0

Step-2: Make @IBOutlet of bottom constraint of the textView.

@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!

Step-3:

fileprivate func addKeyboardNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

fileprivate func removeKeyboardNotification() {
    IQKeyboardManager.shared().isEnabled = true
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Copy & paste these functions to your view controllers, and call self.addKeyboardNotification() in viewDidLoad() and  of you viewController

Step-4:

deinit {
    self.removeKeyboardNotification()
}

also add this code to your viewController.

Step-5:

    func keyboardWillShow(_ notification: Notification) {
    if let keboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue, self.keyboardHeight <= 0.0 {
        self.keyboardHeight = keboardFrame.height + 45.0 //(Add 45 if your keyboard have toolBar if not then remove it)
    }

    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = self.keyboardHeight
    }, completion: { (success) in
    })
}

func keyboardWillHide(_ notification: Notification) {
    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = 0.0
    }, completion: { (success) in
    })
}

That's it to manage the textView with keyboard.
If you don't want to use textViewBottomConstraint the you can work with the y position of the textView.


来源: stackexchange

问:
Scraping multiple tables and storing each table header as rows in csv
I'm trying to scrape multiple tables which have a table name stored under a h3 tag. There is Columns of data I can scrape no problem and when I feed the next url I can append this data to the csv file.
The problem I can't solve is to get the table header and store this relative to each row of table. The reason for this is when the next table is fed I need to know which table it belongs. Is it possible to use a len loop on we say 'Round' to establish the table length and then write the table header to each row? is it possible to do with item exports?

Here's my code
spider.py

```<code>from bigcrawler.items import BigcrawlerItem
from scrapy import Spider, Request, Selector

from scrapy.selector import Selector

from bigcrawler.items import MatchStatItemLoader

class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]
def parse_header(self , response):
    hxs = Selector(response)
    for tb in hxs.css('tr.match'):

      heading = tb.xpath('//*[@id="AWS"]/div/h3/text()').extract()[0]

        for td in tb.xpath(".//tr[contains(@class,
                    'match')]/td[contains(@class, 'round')]/text()"):
            il = BigcrawlerItem(selector=td)

            il.add_value('event_title' , heading)
            yield il.load_item()

 def parse(self , response):
    for row in response.css('tr.match'):
        il = MatchStatItemLoader(selector=row)
        il.add_css('round' , '.round::text')
        il.add_css('event1' , '.event-name a::text')
        il.add_css('player_1' , '.player-name:nth-child(2) a::text')
        il.add_css('player_2' , '.player-name:nth-child(3) a::text')
        il.add_css('player_1_odds' , '.odds-td.odds-0
       [payout]::text')
        il.add_css('player_2_odds' , '.odds-td.odds-1
       [payout]::text')
        il.add_css('h_2_h' , 'a.h2h::text')
        yield il.load_item()
</code>```

items.py

```<code>   import scrapy

   from scrapy.loader import ItemLoader
   from scrapy.loader.processors import TakeFirst, MapCompose
   from operator import methodcaller
   from scrapy import Spider, Request, Selector

   class BigcrawlerItem(scrapy.Item):
  # define the fields for your item here like:

       event_title = scrapy.Field()

       round = scrapy.Field()

       event1 = scrapy.Field()

      player_1 = scrapy.Field()

      player_2 = scrapy.Field()

      player_1_odds = scrapy.Field()

     player_2_odds = scrapy.Field()

     h_2_h = scrapy.Field()

  class MatchStatItemLoader(ItemLoader):
  default_item_class = BigcrawlerItem
  default_input_processor = MapCompose(methodcaller('strip'))
  default_output_processor = TakeFirst()
</code>```

答:
I would suggest completely not use Items class and use start_requests method instead of start_urls as they are really confusing. See the fully working code here. Also notice the match_heading variable.

```<code>class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]

    def start_requests(self):
       match_urls =   [

          'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
          'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                    ]

        for url in match_urls:

            yield Request(url=url, callback=self.parse_matches)

    def parse_matches(self , response):
        match_heading = response.xpath('//*[@id="AWS"]/div/h3/text()').extract_first()

        for row in response.css('tr.match'):

            match = {}
            match['heading'] = match_heading
            match['round'] = row.css(".round::text").extract_first()
            match['event1'] = row.css(".event-name a::text").extract_first()
            match['player_1'] = row.css(".player-name:nth-child(2) a::text").extract_first()
            match['player_2'] = row.css(".player-name:nth-child(3) a::text").extract_first()
            match['player_1_odds'] = row.css(".odds-td.odds-0 [payout]::text").extract_first()
            match['player_2_odds'] = row.css(".odds-td.odds-1 [payout]::text").extract_first()
            match['h_2_h'] = row.css("a.h2h::text::text").extract_first()

            yield match
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to scrape multiple tables which have a table name stored under a h3 tag. There is Columns of data I can scrape no problem and when I feed the next url I can append this data to the csv file.
The problem I can't solve is to get the table header and store this relative to each row of table. The reason for this is when the next table is fed I need to know which table it belongs. Is it possible to use a len loop on we say 'Round' to establish the table length and then write the table header to each row? is it possible to do with item exports?

Here's my code
spider.py

from bigcrawler.items import BigcrawlerItem
from scrapy import Spider, Request, Selector

from scrapy.selector import Selector

from bigcrawler.items import MatchStatItemLoader

class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]
def parse_header(self , response):
    hxs = Selector(response)
    for tb in hxs.css('tr.match'):

      heading = tb.xpath('//*[@id="AWS"]/div/h3/text()').extract()[0]

        for td in tb.xpath(".//tr[contains(@class,
                    'match')]/td[contains(@class, 'round')]/text()"):
            il = BigcrawlerItem(selector=td)

            il.add_value('event_title' , heading)
            yield il.load_item()

 def parse(self , response):
    for row in response.css('tr.match'):
        il = MatchStatItemLoader(selector=row)
        il.add_css('round' , '.round::text')
        il.add_css('event1' , '.event-name a::text')
        il.add_css('player_1' , '.player-name:nth-child(2) a::text')
        il.add_css('player_2' , '.player-name:nth-child(3) a::text')
        il.add_css('player_1_odds' , '.odds-td.odds-0
       [payout]::text')
        il.add_css('player_2_odds' , '.odds-td.odds-1
       [payout]::text')
        il.add_css('h_2_h' , 'a.h2h::text')
        yield il.load_item()

items.py

   import scrapy

   from scrapy.loader import ItemLoader
   from scrapy.loader.processors import TakeFirst, MapCompose
   from operator import methodcaller
   from scrapy import Spider, Request, Selector

   class BigcrawlerItem(scrapy.Item):
  # define the fields for your item here like:

       event_title = scrapy.Field()

       round = scrapy.Field()

       event1 = scrapy.Field()

      player_1 = scrapy.Field()

      player_2 = scrapy.Field()

      player_1_odds = scrapy.Field()

     player_2_odds = scrapy.Field()

     h_2_h = scrapy.Field()

  class MatchStatItemLoader(ItemLoader):
  default_item_class = BigcrawlerItem
  default_input_processor = MapCompose(methodcaller('strip'))
  default_output_processor = TakeFirst()

Body:
I would suggest completely not use Items class and use start_requests method instead of start_urls as they are really confusing. See the fully working code here. Also notice the match_heading variable.

class CrawlbotSpider(Spider):
   name = 'bigcrawler'
   allowed_domains = ['www.matchstat.com']
   start_urls =   [

      'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
      'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                ]

    def start_requests(self):
       match_urls =   [

          'https://matchstat.com/tennis/tournaments/w/Taipei/2015',
          'https://matchstat.com/tennis/tournaments/w/Hong%20Kong/2017',
                    ]

        for url in match_urls:

            yield Request(url=url, callback=self.parse_matches)

    def parse_matches(self , response):
        match_heading = response.xpath('//*[@id="AWS"]/div/h3/text()').extract_first()

        for row in response.css('tr.match'):

            match = {}
            match['heading'] = match_heading
            match['round'] = row.css(".round::text").extract_first()
            match['event1'] = row.css(".event-name a::text").extract_first()
            match['player_1'] = row.css(".player-name:nth-child(2) a::text").extract_first()
            match['player_2'] = row.css(".player-name:nth-child(3) a::text").extract_first()
            match['player_1_odds'] = row.css(".odds-td.odds-0 [payout]::text").extract_first()
            match['player_2_odds'] = row.css(".odds-td.odds-1 [payout]::text").extract_first()
            match['h_2_h'] = row.css("a.h2h::text::text").extract_first()

            yield match


问:
How to launch website on widget click?
I have a basic widget that displays a text field. I'm trying to figure out how to launch a website url when a user clicks on the widget itself. I can't seem to find any code on the matter.</p>

答:
set that TextView to be clickable with TextView.setOnClickListener(this) and then let your activity implement the OnClickListener interface and define the public void onClick(View v) method.

Inside the onClick(View v) method, do this:

```<code>public void onClick(View v){
 startActivity(new Intent(Intent.ACTION_VIEW, url));
}
</code>```

This will open the url in the device browser.

You can also have another activity that uses WebView to display the website.

I hope it was helpful.

ContentLicense: CC BY-SA 2.5

Title: How to launch website on widget click?

Body:
set that TextView to be clickable with TextView.setOnClickListener(this) and then let your activity implement the OnClickListener interface and define the public void onClick(View v) method.

Inside the onClick(View v) method, do this:

public void onClick(View v){
 startActivity(new Intent(Intent.ACTION_VIEW, url));
}

This will open the url in the device browser.

You can also have another activity that uses WebView to display the website.

I hope it was helpful.


问:
when I minimize the app, the app is not showing in task manager
I have developed android app its working fine but when I minimize the app, the app is not showing in task manager

after opening the app press on home button app need to be displayed in taskmanger running apps to resume app

答:
My guess is, may be in your Manifest file, in the launcher activity you have defined this tag, if you want to see your app in the recent list, just remove this tag.</p>

```<code>android:excludeFromRecents="true"
</code>```

Body:
My guess is, may be in your Manifest file, in the launcher activity you have defined this tag, if you want to see your app in the recent list, just remove this tag.

android:excludeFromRecents="true"


问:
use kafka to start Kylin Stream
When I use kafka to start Kylin Stream,I got the following exception as picture,hope someone can help me ,thanks very much:enter image description here</p>

答: checked the image .It seems to be the WARN not Exception.Check the input and try with the stable version of Kylin</p>

Title: use kafka to start Kylin Stream


问:
How to verify WIFI wake lock using adb command
Can someone tell me is there any adb command to verify wifi wake lock in android phone. I am trying to check that wake lock is active or not after acquire from my application but not found this information in following file:

```<code> adb shell "cat /sys/kernel/debug/wakeup_sources"
</code>```

Is it written somewhere else ?

答:
To list the wifilocks active in android device, use the following command.

adb shell dumpsys wifi | grep "your wake_lock tag name"

Example:

adb shell dumpsys wifi | grep wake_lock_next

output:

WifiLock{wake_lock_next type=2 binder=android.os.BinderProxy@420bcfd0}

Body:
Can someone tell me is there any adb command to verify wifi wake lock in android phone. I am trying to check that wake lock is active or not after acquire from my application but not found this information in following file:

 adb shell "cat /sys/kernel/debug/wakeup_sources"

Is it written somewhere else ?


问:
How to Print Alphabet sequentially in PHP?
I have an array variable $arr = array('A','B','C','D');

```<code>$number = 5; (This is dynamic)
</code>```

My new array value should be

```<code>$arr = array('A','B','C','D','E','F','G','H','I');
</code>```

If

```<code>$number = 3;
</code>```

Output should be:

```<code>$arr = array('A','B','C','D','E','F','G');
</code>```

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

答:
Here is example to add chars from alphabet to array with offset. This works for one char. If you wish to work for more chars use loop in loop.

```<code>for ($c = ord('A') + $offset ;$c <= ord('Z');$c++) {
  Array[] += chr($c);
</code>```

}

Body:
I have an array variable $arr = array('A','B','C','D');

$number = 5; (This is dynamic)

My new array value should be

$arr = array('A','B','C','D','E','F','G','H','I');

If

$number = 3;

Output should be:

$arr = array('A','B','C','D','E','F','G');

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

Body:
Here is example to add chars from alphabet to array with offset. This works for one char. If you wish to work for more chars use loop in loop.

for ($c = ord('A') + $offset ;$c <= ord('Z');$c++) {
  Array[] += chr($c);

}


问:
How to know if a string is already escaped special with special characters?
I have this URL:

```<code>"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
</code>```

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

```<code>let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
</code>```

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

答:
I don't know but might be work.

You can check your URL is valid or not, If Its valid then no need to escaping agin if not then you should escape it.

Like check URL is valid or not

```<code>func isValidMyURL (_ urlString: NSString) -> Bool {
    let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
    return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString)
}
</code>```

And then

```<code>if !isValidMyURL(originalString) { // If not valid then escape it
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}
</code>```

Other wise directly use escapedString.

Body:
I have this URL:

"http://www.somedomain.com/folder/مرحبا المستخدم.jpg"

So I needs to escape these Arabic values else it will not able to create URL object.

I am doing it like this,

let originalString = "http://www.somedomain.com/folder/مرحبا المستخدم.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

This will be the output of escapedString:

http://www.somedomain.com/folder/%D9%85%D8%B1%D8%AD%D8%A8%D8%A7%20%D8%A7%D9%84%D9%85%D8%B3%D8%AA%D8%AE%D8%AF%D9%85.jpg

So far so good. But when I force to try to escape an already escaped URL then the result is weird.

How to check if a string is already encoded?

Body:
I don't know but might be work.

You can check your URL is valid or not, If Its valid then no need to escaping agin if not then you should escape it.

Like check URL is valid or not

func isValidMyURL (_ urlString: NSString) -> Bool {
    let urlRegEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
    return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluateWithObject(urlString)
}

And then

if !isValidMyURL(originalString) { // If not valid then escape it
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}

Other wise directly use escapedString.


问:
accordion menu in aurelia
I have this accordion working using just pure css with html: https://jsfiddle.net/11wunqqz/6/

but the problem is when I tried insert it in a aurelia code did not work.

reason? I am using href='#accordion' to make it work.

```<code><a href="#accordion1" id="open-accordion1" title="open">First Accordion</a>
</code>```

so when I click redirects me to the age localhost/#/accordion1

someone know best way to fix it? thank you

答:
Try to add data-toggle="collapse" and data-parent to that anchor element. It will resolve your issue.

or else remove anchor tag and add replace with span element.

Title: accordion menu in aurelia

Body:
I have this accordion working using just pure css with html: https://jsfiddle.net/11wunqqz/6/

but the problem is when I tried insert it in a aurelia code did not work.

reason? I am using href='#accordion' to make it work.

First Accordion

so when I click redirects me to the age localhost/#/accordion1

someone know best way to fix it? thank you


问:
Verilog: primitives or continuous assignment
I am running this code

```<code>module neuron_xor(x0, x1, y4);
    input signed [4:0] x0, x1;
    reg signed [4:0] w02, w03, w12, w13, w24, w34;
    reg signed [4:0] th2, th3, th4;
    wire signed [4:0] y2, y3;
    output signed [4:0] y4;

    neuron n2(x0, x1, w02, w12, th2, y2);
    neuron n3(x0, x1, w03, w13, th3, y3);

    neuron n4(y2, y3, w24, w34, th4, y4);

    initial begin
    w02 = 2; w03 = -2;
    w12 = 2; w13 = -2;
    w24 = 2; w34 = 2;

    th2 = 1; th3 = -3; th4 = 3;
    end
endmodule
</code>```

With this testbench:

```<code>`timescale 1ns/100ps

module tb_neuron_xor();

    reg signed [4:0] x0, x1;
    reg signed [4:0] w02, w03, w12, w13, w24, w34;
    reg signed [4:0] th2, th3, th4;
    wire signed [4:0] y2, y3;
    wire signed [4:0] y4;
    reg signed [4:0] ctrl;
    integer i, j, flag;

    neuron n2(x0, x1, w02, w12, th2, y2);
    neuron n3(x0, x1, w03, w13, th3, y3);
    neuron n4(y2, y3, w24, w34, th4, y4);

    initial begin

        $dumpfile("tb_neu_xor.vcd");
        $dumpvars;

        flag = 0;

        #10;
        for (i = -16; i < 15; i = i + 1) begin
            for (j = -16; j < 15; j = j + 1) begin

                x0 = i; x1 = j;
                ctrl = x0 ^ x1;

                if (ctrl != y4) begin
                    flag = 1;
                    $display("Error: x0=%b, x1=%b, y4=%b, ctrl=%b", x0,x1,y4,ctrl);
                end
                $display("y4=%d, ctrl=%d", y4, ctrl);
            end
        end

        if (flag == 0) begin
            $display("No Error!");
        end

        #10;
        $finish;

    end
endmodule
</code>```

I get y4=X for each and every iteration. As far as I understand, this happens, because no initial value has been given to y4, and the default is X. However, I cannot change the type of y4 to reg in order to assign a value to it. That would result in an error message saying in the test bench, line 15, neuron n4:

tb_neuron_xor.v:15: error: reg y4; cannot be driven by primitives or continuous assignment.
  tb_neuron_xor.v:15: error: Output port expression must support continuous assignment.
  tb_neuron_xor.v:15:      : Port y0 of neuron is connected to y4

How could I work my way around this?

In case a better context is needed, here is how neuron module is defined:

```<code>module neuron(x0, x1, w0, w1, th0, y0);
    input signed [4:0] x0, x1;
    input signed [4:0] w0, w1;
    input signed [4:0] th0;
    output reg signed [4:0] y0;

    reg signed [11:0] a0, a1, a2;

    always @(x0 or x1 or w0 or w1 or th0)
    begin
        a0 = x0*w0;
        a1 = x1*w1;
        a2 = a0 + a1;

        if (a2 >= th0)
            y0 = 1;
        else
            y0 = 0;
    end

endmodule
</code>```

答:
Why not assign default value to y0 of neuron() ?

```<code>output reg signed [4:0] y0=0;
</code>```

I would also suggest that you use a reset on your regs, and reset them at the beginning of the simulation.

Body:
I am running this code

module neuron_xor(x0, x1, y4);
    input signed [4:0] x0, x1;
    reg signed [4:0] w02, w03, w12, w13, w24, w34;
    reg signed [4:0] th2, th3, th4;
    wire signed [4:0] y2, y3;
    output signed [4:0] y4;

    neuron n2(x0, x1, w02, w12, th2, y2);
    neuron n3(x0, x1, w03, w13, th3, y3);

    neuron n4(y2, y3, w24, w34, th4, y4);

    initial begin
    w02 = 2; w03 = -2;
    w12 = 2; w13 = -2;
    w24 = 2; w34 = 2;

    th2 = 1; th3 = -3; th4 = 3;
    end
endmodule

With this testbench:

`timescale 1ns/100ps

module tb_neuron_xor();

    reg signed [4:0] x0, x1;
    reg signed [4:0] w02, w03, w12, w13, w24, w34;
    reg signed [4:0] th2, th3, th4;
    wire signed [4:0] y2, y3;
    wire signed [4:0] y4;
    reg signed [4:0] ctrl;
    integer i, j, flag;

    neuron n2(x0, x1, w02, w12, th2, y2);
    neuron n3(x0, x1, w03, w13, th3, y3);
    neuron n4(y2, y3, w24, w34, th4, y4);

    initial begin

        $dumpfile("tb_neu_xor.vcd");
        $dumpvars;

        flag = 0;

        #10;
        for (i = -16; i < 15; i = i + 1) begin
            for (j = -16; j < 15; j = j + 1) begin

                x0 = i; x1 = j;
                ctrl = x0 ^ x1;

                if (ctrl != y4) begin
                    flag = 1;
                    $display("Error: x0=%b, x1=%b, y4=%b, ctrl=%b", x0,x1,y4,ctrl);
                end
                $display("y4=%d, ctrl=%d", y4, ctrl);
            end
        end

        if (flag == 0) begin
            $display("No Error!");
        end

        #10;
        $finish;

    end
endmodule

I get y4=X for each and every iteration. As far as I understand, this happens, because no initial value has been given to y4, and the default is X. However, I cannot change the type of y4 to reg in order to assign a value to it. That would result in an error message saying in the test bench, line 15, neuron n4:

tb_neuron_xor.v:15: error: reg y4; cannot be driven by primitives or continuous assignment.
  tb_neuron_xor.v:15: error: Output port expression must support continuous assignment.
  tb_neuron_xor.v:15:      : Port y0 of neuron is connected to y4

How could I work my way around this?

In case a better context is needed, here is how neuron module is defined:

module neuron(x0, x1, w0, w1, th0, y0);
    input signed [4:0] x0, x1;
    input signed [4:0] w0, w1;
    input signed [4:0] th0;
    output reg signed [4:0] y0;

    reg signed [11:0] a0, a1, a2;

    always @(x0 or x1 or w0 or w1 or th0)
    begin
        a0 = x0*w0;
        a1 = x1*w1;
        a2 = a0 + a1;

        if (a2 >= th0)
            y0 = 1;
        else
            y0 = 0;
    end

endmodule

Body:
Why not assign default value to y0 of neuron() ?

output reg signed [4:0] y0=0;

I would also suggest that you use a reset on your regs, and reset them at the beginning of the simulation.


问:
How to specify common error page excluding 404 and 500 in web.xml

I already have two web pages designed for 404 and 500 error pages in web.xml

```<code> <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/error/500.jsp</location>
    </error-page>
</code>```

I want to redirect to a predesignated page for all the other errors.

Please help.
Thank you

答:
This should be sufficient, along with few customer error related pages, you can add default page. So all error other than 404, 500 , will be redirected to generic page error.html

```<code><error-page>
    <location>/error.html</location>
</error-page>
</code>```

or more customized, using Exception class, can be your custom exception class as well.

```<code><error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/error.html</location>
</error-page>
</code>```

So code becomes,

```<code><error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/error/404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/error/500.jsp</location>
</error-page>
<error-page>
    <location>/error.html</location>
</error-page>
</code>```

Body:
I already have two web pages designed for 404 and 500 error pages in web.xml

 <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/error/500.jsp</location>
    </error-page>

I want to redirect to a predesignated page for all the other errors.

Please help.
Thank you

Body:
This should be sufficient, along with few customer error related pages, you can add default page. So all error other than 404, 500 , will be redirected to generic page error.html

<error-page>
    <location>/error.html</location>
</error-page>

or more customized, using Exception class, can be your custom exception class as well.

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/error.html</location>
</error-page>

So code becomes,

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/error/404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/error/500.jsp</location>
</error-page>
<error-page>
    <location>/error.html</location>
</error-page>


问:
Pivoting the data
This is my SQL statement

```<code>select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')
</code>```

which produces below result

```<code>ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2
</code>```

I need to get result in kind of pivoted format like this

```<code>id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2
</code>```

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.

答:
```<code>select id,name,[display],[contact],[ship]

from #b

pivot(max(value) for type in([display],[contact],[ship])) As d
</code>```

Title: Pivoting the data

Body:
This is my SQL statement

select  id , name, type,  value  from table1 a
INNER JOIN table2 b on a.id = b.id
where  b.type in ('display','contact','ship')

which produces below result

ID  name     type           value
5   test     display        display1
5   test     contact        contact1
5   test     ship           ship1
6   test2    display        display2
6   test2    contact        contact2
6   test2    ship           ship2

I need to get result in kind of pivoted format like this

id  name   display   contact   ship
5   test   display1  contact1 ship1
6   test2  display2  contact2 ship2

I tried this solution : https://stackoverflow.com/a/6849706/2645738 ,but its giving me the same result (3 rows for each data). It's like i need to group by id and name,but don't know how to make display,contact,ship as columns.

Would you please help me for the same.


问:
Return Html page loaded with JSON data in NodeJS
I have a NodeJs server that fetches JSon data from a rest API.

Once the data is loaded, I'd like to return an HTML page and load it in a table there.

EDIT

I figured out that I needed express (example below updated), with the right version (3.x to old!) to use res.SendFile(). So the Html file is returned now. However still don't know how to load the data in the page.

Ideally I'd also want to be able to filter on the data using datatables.

NodeJS server route

```<code>var express = require('express');
var app = express();

var path = require('path');
const Request = require('request');
const ServerAddress = ...;

exports.showAll = function(req, res) {
    Request.get(ServerAddress + '/data', function (error, response, body) {
        if (error) {
            throw error;
        }
        const data = JSON.parse(body);
        return res.sendFile(path.resolve(__dirname + '/../index.html'), { result: data });
    });
</code>```

index.html

```<code><html>
    <head>
        <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
        <script src="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"></script>
    </head>
    <body>
        <div class="data">
            <table id="resultsTable">
                <thead>
                    <tr>
                        <th>Col1</th>
                        <th>Col2</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                        </td>
                        <td>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>
</code>```

Thank you!

答:
I suggest EJS. It works great in Node and is easy to pick up if you only know HTML.
http://www.embeddedjs.com/getting_started.html
https://www.npmjs.com/package/ejs</p>

Body:
I have a NodeJs server that fetches JSon data from a rest API.

Once the data is loaded, I'd like to return an HTML page and load it in a table there.

EDIT

I figured out that I needed express (example below updated), with the right version (3.x to old!) to use res.SendFile(). So the Html file is returned now. However still don't know how to load the data in the page.

Ideally I'd also want to be able to filter on the data using datatables.

NodeJS server route

var express = require('express');
var app = express();

var path = require('path');
const Request = require('request');
const ServerAddress = ...;

exports.showAll = function(req, res) {
    Request.get(ServerAddress + '/data', function (error, response, body) {
        if (error) {
            throw error;
        }
        const data = JSON.parse(body);
        return res.sendFile(path.resolve(__dirname + '/../index.html'), { result: data });
    });

index.html

                        Col1
                        Col2

Thank you!


问:
tanf() function returns wrong value in iOS
I got a problem, but can't find the error. I'm trying to calculate the tangent of an angle. I tried both in radians and in degree, i got wrong answer. My code:

```<code>CGFloat tiltAngleDegrees = tiltAngle * 180.0f / M_PI - 90.0f; // in degrees
NSLog(@"Tan Angle: %f", tanf(tiltAngleDegrees));
</code>```

I tried for Angle:-6.027872

I got answer: 0.261010

Answer that i calculated on calculator: -0.105596

I thought it was going to be a simple task, but i hit a wall - can't find what's going wrong. I hope some of you can point me in the right direction.

Thanks.

答:
as @rmaddy said tanf requires radians

In your case I suppose your angle is in radians

```<code>tiltAngle = -6.027872 //in radians
</code>```

so

```<code>float tangent = tanf(-6.027872);
</code>```

gives you 0.26101 which is the correct answer.

In your code sample you convert tiltAngle from radians to degrees but also substract 90°. Is there any reason for that ? At that moment the correct result will be -3.8313.

However the problem is that you set your calculator in degrees. If -6.027872 is in degrees at that moment you will get -0.105596 which is wrong.

Body:
I got a problem, but can't find the error. I'm trying to calculate the tangent of an angle. I tried both in radians and in degree, i got wrong answer. My code:

CGFloat tiltAngleDegrees = tiltAngle * 180.0f / M_PI - 90.0f; // in degrees
NSLog(@"Tan Angle: %f", tanf(tiltAngleDegrees));

I tried for Angle:-6.027872

I got answer: 0.261010

Answer that i calculated on calculator: -0.105596

I thought it was going to be a simple task, but i hit a wall - can't find what's going wrong. I hope some of you can point me in the right direction.

Thanks.

Body:
as @rmaddy said tanf requires radians

In your case I suppose your angle is in radians

tiltAngle = -6.027872 //in radians

so

float tangent = tanf(-6.027872);

gives you 0.26101 which is the correct answer.

In your code sample you convert tiltAngle from radians to degrees but also substract 90°. Is there any reason for that ? At that moment the correct result will be -3.8313.

However the problem is that you set your calculator in degrees. If -6.027872 is in degrees at that moment you will get -0.105596 which is wrong.


问:
Inserting a Link to a Webpage in an IPython Notebook
How is this done?  I'd like to have the link be in a markdown cell.</p>

答:
Just another tip, using magic expression.

```<code>%%html
<a href="your_url_here">Showing Text</a>
</code>```

Improved. Thanks to the comment of calocedrus.

ContentLicense: CC BY-SA 4.0

Body:
Just another tip, using magic expression.

%%html
<a href="your_url_here">Showing Text</a>

Improved. Thanks to the comment of calocedrus.


问:
What are some best practices for optimizing multiple column LIKE SQL queries?
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

```<code>INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName
</code>```

Does anyone have any recommendations on how I could improve the performance of the query?

答:
Avoid "OR"s - they in general prevent the use of indexes

Never put a "%" on the left side. - same reason.

OwnerDisplayName: JamesEggers

Body:
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName

Does anyone have any recommendations on how I could improve the performance of the query?


问:
Linq to Sql: returning limited number of rows per group
Imagine have a Products table with following data:

```<code>
    ProductID    UserName   ProductName
    -----------------------------------
    1            User1      Product1
    2            User1      Product2
    3            User2      Product3
    4            User3      Product4
    5            User1      Product5
    6            User2      Product6
    7            User2      Product7
    8            User1      Product8
</code>```

Also there is another table named UserLimit:

```<code>
    UserName    DisplayLimit
    -------------------------
    User1       3
    User2       2
    User3       2
</code>```

This table indicates maximum number of products that should be returned for each user.

What I want to accomplish is to have a Linq to Sql query that returns this:

```<code>
    ProductID     UserName    ProductName
    --------------------------------------
    1             User1       Product1
    2             User1       Product2
    5             User1       Product5
    3             User2       Product3
    6             User2       Product6
    4             User3       Product4
</code>```

Which number of products returned for each user is limited to the DisplayLimit value in UserLimit table.

答:
Not sure how link-to-sql would fit into this but if it's possible you may try to use DENSE_RANK function. For example, the query below will return last 3 projects for each user. The limit is common for all users but nothing really prevents from linking to a table with limits.

```<code>declare @numberOfProjects int
set @numberOfProjects = 3

;with topNProjects(userid, projectid, createdtutc, dense_rank)
as (
    select p.userid, P.ProjectId, p.CreatedDtUtc, DENSE_RANK() OVER (PARTITION BY P.UserId ORDER BY P.ProjectId) AS DENSE_RANK
    from DS_Project P
)
select userid, projectid, createdtutc from topNProjects
where dense_rank <= @numberOfProjects
order by projectid desc
</code>```

EDITED: tried LINQed solution and came up with the following. I think all you will have to do is to replace my collections with references to tables in data context.

```<code>        Dictionary<int, string> userProjects = new Dictionary<int, string>
        {
            { 1, "User1" },
            { 2, "User1" },
            { 3, "User2" },
            { 4, "User3" },
            { 5, "User1" },
            { 6, "User2" },
            { 7, "User2" },
            { 8, "User1" },
        };
        Dictionary<string, int> limits = new Dictionary<string, int>
        {
            { "User1", 3 },
            { "User2", 2 },
            { "User3", 2 },
        };

        var ranked =
            from up in userProjects
            join l in limits on up.Value equals l.Key
            orderby up.Value
            where (from upr in userProjects
                   where upr.Value == up.Value && upr.Key <= up.Key
                   select upr).Count() <= l.Value
            select up;
</code>```

The result is as follows which seems is what you are looking for:

```<code>1, User1
2, User1
5, User1
3, User2
6, User2
4, User3
</code>```

Body:
Imagine have a Products table with following data:

    ProductID    UserName   ProductName
    -----------------------------------
    1            User1      Product1
    2            User1      Product2
    3            User2      Product3
    4            User3      Product4
    5            User1      Product5
    6            User2      Product6
    7            User2      Product7
    8            User1      Product8

Also there is another table named UserLimit:

    UserName    DisplayLimit
    -------------------------
    User1       3
    User2       2
    User3       2

This table indicates maximum number of products that should be returned for each user.

What I want to accomplish is to have a Linq to Sql query that returns this:

    ProductID     UserName    ProductName
    --------------------------------------
    1             User1       Product1
    2             User1       Product2
    5             User1       Product5
    3             User2       Product3
    6             User2       Product6
    4             User3       Product4

Which number of products returned for each user is limited to the DisplayLimit value in UserLimit table.

Body:
Not sure how link-to-sql would fit into this but if it's possible you may try to use DENSE_RANK function. For example, the query below will return last 3 projects for each user. The limit is common for all users but nothing really prevents from linking to a table with limits.

declare @numberOfProjects int
set @numberOfProjects = 3

;with topNProjects(userid, projectid, createdtutc, dense_rank)
as (
    select p.userid, P.ProjectId, p.CreatedDtUtc, DENSE_RANK() OVER (PARTITION BY P.UserId ORDER BY P.ProjectId) AS DENSE_RANK
    from DS_Project P
)
select userid, projectid, createdtutc from topNProjects
where dense_rank <= @numberOfProjects
order by projectid desc

EDITED: tried LINQed solution and came up with the following. I think all you will have to do is to replace my collections with references to tables in data context.

        Dictionary<int, string> userProjects = new Dictionary<int, string>
        {
            { 1, "User1" },
            { 2, "User1" },
            { 3, "User2" },
            { 4, "User3" },
            { 5, "User1" },
            { 6, "User2" },
            { 7, "User2" },
            { 8, "User1" },
        };
        Dictionary<string, int> limits = new Dictionary<string, int>
        {
            { "User1", 3 },
            { "User2", 2 },
            { "User3", 2 },
        };

        var ranked =
            from up in userProjects
            join l in limits on up.Value equals l.Key
            orderby up.Value
            where (from upr in userProjects
                   where upr.Value == up.Value && upr.Key <= up.Key
                   select upr).Count() <= l.Value
            select up;

The result is as follows which seems is what you are looking for:

1, User1
2, User1
5, User1
3, User2
6, User2
4, User3


问:
I want to merge two query to have one result
This is my first Query that it give me sum of actual and estimated expenses related to salaries

```<code>SELECT
  d.y_                                   AS `salaries`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
SELECT estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'management'
GROUP
    BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'management'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                           AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'staff salaries'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'staff salaries'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
 GROUP
 BY d.y_

ORDER
 BY d.y_;
</code>```

The result:

My second Query that it give me sum of actual and estimated expenses related to equipments

```<code>SELECT
  d.y_                                   AS `Equipments`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
    select estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle rent'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle rent'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
                  union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'generator fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'generator fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
  GROUP
  BY d.y_

ORDER
  BY d.y_;
</code>```

The result:

I want to have Salaries under it management and staff salaries

than Equipments under it Vehicle Rent, Vehicle fuel and Generator Fuel etcetera

答:
You could use UNION to merge those queries:

```<code>SELECT [First query]
UNION ALL
SELECT 'Equipments', 'Estimated', 'Actual'
UNION ALL
SELECT [Second query]
</code>```

Please note that the Select after the first UNION ALL simply selects the headlines for your second query. You also could use UNION (w/o ALL), because it does not look like you're having duplicates.

Body:
This is my first Query that it give me sum of actual and estimated expenses related to salaries

SELECT
  d.y_                                   AS `salaries`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
SELECT estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'management'
GROUP
    BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'management'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                           AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    AND it.estimated_type = 'staff salaries'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        AND it.Type_expenses_table = 'staff salaries'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
 GROUP
 BY d.y_

ORDER
 BY d.y_;

The result:

My second Query that it give me sum of actual and estimated expenses related to equipments

SELECT
  d.y_                                   AS `Equipments`
 , IFNULL(SUM(d.actual),0)               AS `Estimated`
 , IFNULL(SUM(d.estimated),0)            AS `Actual`
FROM (
    select estimated_type                       AS`y_`
    ,null                                       AS `Estimated`
    , sum(estimated_amount)                     AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle rent'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle rent'
GROUP
     BY YEAR(it.Date_expenses_table)
         union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'vehicle fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'vehicle fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
                  union all
SELECT estimated_type                         AS`y_`
    ,null                                     AS `Estimated`
    , sum(estimated_amount)                   AS `Actual`
FROM bacci.estimated_expenses_table it
WHERE it.estimated_year = '2017'
    and it.estimated_type = 'generator fuel'
GROUP
     BY YEAR(it.estimated_year)
         union all
SELECT Type_expenses_table                      AS`y_`
    ,SUM(it.Amount_expenses_table)              AS `Estimated`
    , null                                      AS `Actual`
FROM bacci.expenses_table it
WHERE it.Date_expenses_table >= '2017-01-01'
        AND it.Date_expenses_table  < '2017-01-01' + INTERVAL 1 YEAR
        and it.Type_expenses_table = 'generator fuel'
GROUP
     BY YEAR(it.Date_expenses_table)
) d
  GROUP
  BY d.y_

ORDER
  BY d.y_;

The result:

I want to have Salaries under it management and staff salaries

than Equipments under it Vehicle Rent, Vehicle fuel and Generator Fuel etcetera

Body:
You could use UNION to merge those queries:

SELECT [First query]
UNION ALL
SELECT 'Equipments', 'Estimated', 'Actual'
UNION ALL
SELECT [Second query]

Please note that the Select after the first UNION ALL simply selects the headlines for your second query. You also could use UNION (w/o ALL), because it does not look like you're having duplicates.


问:
Install Mono-Complete 4.8 on Ubuntu
I'm trying to install Mono 4.8 in a Docker image but I am failing to download. Here is the dockerfile

```<code>  RUN apt-get update \
  && apt-get install -y curl \
  && rm -rf /var/lib/apt/lists/* \
  && apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys     3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF \
  && echo "deb http://download.mono-project.com/repo/debian wheezy main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && apt-get update \
  && apt-get install -y clang \
  && apt-get install -y mono-complete=4.8.0.520-0xamarin3
</code>```

It fails to install mono-compete with this error message

```<code>E: Version '4.8.0.520-0xamarin3' for 'mono-complete' was not found
</code>```

I was wondering what should be the mono-complete 4.8 version?

答:
Pin the version to the snapshots directory:

```<code>echo "deb http://download.mono-project.com/repo/ubuntu wheezy/snapshots/4.8.0.520 main" | sudo tee /etc/apt/sources.list.d/mono-official.list
</code>```

Get the required dependencies:

```<code>sudo apt install gnupg ca-certificates
</code>```

Add the repository keys:

```<code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys A6A19B38D3D831EF
</code>```

Update the package index:

```<code>sudo apt-get update
</code>```

After modifying/update the caches, you can use apt-cache policy {package} to determine if the version you wish to install is available.

```<code>>apt-cache policy mono-complete
mono-complete:
  Installed: (none)
  Candidate: 4.8.0.520-0xamarin3
  Version table:
     4.8.0.520-0xamarin3 500
        500 http://download.mono-project.com/repo/ubuntu wheezy/snapshots/4.8.0.520/main amd64 Packages
     4.6.2.7+dfsg-1ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu artful/universe amd64 Packages
</code>```

Now you can install 4.8.0.520-0xamarin3:

```<code>sudo apt-get install -y mono-complete=4.8.0.520-0xamarin3
</code>```

Title: Install Mono-Complete 4.8 on Ubuntu

Body:
I'm trying to install Mono 4.8 in a Docker image but I am failing to download. Here is the dockerfile

  RUN apt-get update \
  && apt-get install -y curl \
  && rm -rf /var/lib/apt/lists/* \
  && apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys     3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF \
  && echo "deb http://download.mono-project.com/repo/debian wheezy main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" >> /etc/apt/sources.list.d/mono-xamarin.list \
  && apt-get update \
  && apt-get install -y clang \
  && apt-get install -y mono-complete=4.8.0.520-0xamarin3

It fails to install mono-compete with this error message

E: Version '4.8.0.520-0xamarin3' for 'mono-complete' was not found

I was wondering what should be the mono-complete 4.8 version?

Body:
Pin the version to the snapshots directory:

echo "deb http://download.mono-project.com/repo/ubuntu wheezy/snapshots/4.8.0.520 main" | sudo tee /etc/apt/sources.list.d/mono-official.list

Get the required dependencies:

sudo apt install gnupg ca-certificates

Add the repository keys:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys A6A19B38D3D831EF

Update the package index:

sudo apt-get update

After modifying/update the caches, you can use apt-cache policy {package} to determine if the version you wish to install is available.

>apt-cache policy mono-complete
mono-complete:
  Installed: (none)
  Candidate: 4.8.0.520-0xamarin3
  Version table:
     4.8.0.520-0xamarin3 500
        500 http://download.mono-project.com/repo/ubuntu wheezy/snapshots/4.8.0.520/main amd64 Packages
     4.6.2.7+dfsg-1ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu artful/universe amd64 Packages

Now you can install 4.8.0.520-0xamarin3:

sudo apt-get install -y mono-complete=4.8.0.520-0xamarin3


问:
ServiceStack select projection not working as expected
ServiceStack select projection not working as expected

Here is example

```<code>var q = db.From<Product>()
            .Select<Product>(p=>
                new
                {
                    Name = p.Name,
                    Price = p.Price,
                    ExtraVATColumn= 5*8
                }
               );
             return db.Select<object>(q);
</code>```

It returns

[{"Name":"Book","Price":1103.46,"40":40}]

instead of

[{"Name":"Book","Price":1103.46,"ExtraVATColumn":40}]

In standard ASP.NET Web Api application Linq Select projection works as expected but not in ServiceStack Api.

Can someone give explanation ?

答:
5*8 = 40

It uses the Product property names i.e p.Name, p.Price as the keys in your JSON result. In the case of ExtraVATColumn, no property/variable was supplied in your Linq. So instead, the value 40 was used as the name of the key upon serialization.

Body:
ServiceStack select projection not working as expected

Here is example

var q = db.From<Product>()
            .Select<Product>(p=>
                new
                {
                    Name = p.Name,
                    Price = p.Price,
                    ExtraVATColumn= 5*8
                }
               );
             return db.Select<object>(q);

It returns

[{"Name":"Book","Price":1103.46,"40":40}]

instead of

[{"Name":"Book","Price":1103.46,"ExtraVATColumn":40}]

In standard ASP.NET Web Api application Linq Select projection works as expected but not in ServiceStack Api.

Can someone give explanation ?


问:
How do you store datetime in MongoDB given that what I've tried has failed?
I'm trying to insert a datetime in MongoDB but I can not.

Here is the method I used:

```<code>var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date
          }
});

module.exports = mongoose.model('test', testSchema);
</code>```

答:
// You just add default: Data.now in your Schema. it will works 100%

```<code>var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date,
       default : Data.now
          }
});

module.exports = mongoose.model('test', testSchema);
</code>```

Body:
I'm trying to insert a datetime in MongoDB but I can not.

Here is the method I used:

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date
          }
});

module.exports = mongoose.model('test', testSchema);

Body:
// You just add default: Data.now in your Schema. it will works 100%

var mongoose = require('mongoose');

var testSchema = new mongoose.Schema({

    date : {
       type : Date,
       default : Data.now
          }
});

module.exports = mongoose.model('test', testSchema);


问:
Arduino UNO error
I got a problem with this code from Arduino Projects Book, a very simple code soryy if is very obvius.

This is the code I wrote:

```<code>const int greenLEDpin = 9;
const int redLEDpin = 10;
const int blueLEDpin = 11;

const int redSensorpin = A0;
const int greenSensorpin = A1;
const int blueSensorpin = A2;

int redValue = 0;
int greenValue = 0;
int blueValue = 0;

void setup() {
  Serial.begin(9600);

  pinMode(greenLEDpin,OUTPUT);
  pinMode(redLEDpin,OUTPUT);
  pinMode(blueLEDpin,OUTPUT);

}

void loop() {

  redSensorValue = analogRead(redSensorpin);
  delay (5);
  greenSensorValue = analogRead(greenSensorpin);
  delay(5);
  blueSensorValue = analogRead(blueSensorpin);

  Serial.print("Raw Sensor Values \t Red: ");
  Serial.print(redSensorValue);
  Serial.print("\t Green: ");
  Serial.print(greenSensorValue);
  Serial.print("\t Blue: ");
  Serial.println(blueSensorValue);

  redValue = redSensorValue/4;
  greenValue = greenSensorValue/4;
  blueValue = blueSensorValue/4;

  Serial.print("Mapped Sensor Values \t ReD: ");
  Serial.print(redValue);
  Serial.print("\t Green: ");
  Serial.print(greenValue);
  Serial.print("\t Blue: ");
  Serial.print(blueValue);
  analogWrite(redLEDpin, redValue);
  analogWrite(greenLEDpin, greenValue);
  analogWrite(blueLEDpin, blueValue);
}
</code>```

And here is the error:
Arduino:1.7.10 (Windows 8.1), Placa:"Arduino Uno"

```<code>LED_tricolor.ino: In function 'void loop()':

LED_tricolor.ino:24:2: error: 'redSensorValue' was not declared in this scope

LED_tricolor.ino:26:2: error: 'greenSensorValue' was not declared in this scope

LED_tricolor.ino:28:2: error: 'blueSensorValue' was not declared in this scope
</code>```

Someone knows whats happening here? I tried some things like puting the variables before, but nothing...
Hope u guys can help me ^^.

答:
You did not add any sensor pin in setup() function. Edit you function just like it.

```<code>void setup() {

  pinMode(redSensorpin,INPUT);
  pinMode(greenSensorpin,INPUT);
  pinMode(blueSensorpin,INPUT);

  pinMode(greenLEDpin,OUTPUT);
  pinMode(redLEDpin,OUTPUT);
  pinMode(blueLEDpin,OUTPUT);
  Serial.begin(9600);

}
</code>```

Title: Arduino UNO error

Body:
I got a problem with this code from Arduino Projects Book, a very simple code soryy if is very obvius.

This is the code I wrote:

const int greenLEDpin = 9;
const int redLEDpin = 10;
const int blueLEDpin = 11;

const int redSensorpin = A0;
const int greenSensorpin = A1;
const int blueSensorpin = A2;

int redValue = 0;
int greenValue = 0;
int blueValue = 0;

void setup() {
  Serial.begin(9600);

  pinMode(greenLEDpin,OUTPUT);
  pinMode(redLEDpin,OUTPUT);
  pinMode(blueLEDpin,OUTPUT);

}

void loop() {

  redSensorValue = analogRead(redSensorpin);
  delay (5);
  greenSensorValue = analogRead(greenSensorpin);
  delay(5);
  blueSensorValue = analogRead(blueSensorpin);

  Serial.print("Raw Sensor Values \t Red: ");
  Serial.print(redSensorValue);
  Serial.print("\t Green: ");
  Serial.print(greenSensorValue);
  Serial.print("\t Blue: ");
  Serial.println(blueSensorValue);

  redValue = redSensorValue/4;
  greenValue = greenSensorValue/4;
  blueValue = blueSensorValue/4;

  Serial.print("Mapped Sensor Values \t ReD: ");
  Serial.print(redValue);
  Serial.print("\t Green: ");
  Serial.print(greenValue);
  Serial.print("\t Blue: ");
  Serial.print(blueValue);
  analogWrite(redLEDpin, redValue);
  analogWrite(greenLEDpin, greenValue);
  analogWrite(blueLEDpin, blueValue);
}

And here is the error:
Arduino:1.7.10 (Windows 8.1), Placa:"Arduino Uno"

LED_tricolor.ino: In function 'void loop()':

LED_tricolor.ino:24:2: error: 'redSensorValue' was not declared in this scope

LED_tricolor.ino:26:2: error: 'greenSensorValue' was not declared in this scope

LED_tricolor.ino:28:2: error: 'blueSensorValue' was not declared in this scope

Someone knows whats happening here? I tried some things like puting the variables before, but nothing...
Hope u guys can help me ^^.

Body:
You did not add any sensor pin in setup() function. Edit you function just like it.

void setup() {

  pinMode(redSensorpin,INPUT);
  pinMode(greenSensorpin,INPUT);
  pinMode(blueSensorpin,INPUT);

  pinMode(greenLEDpin,OUTPUT);
  pinMode(redLEDpin,OUTPUT);
  pinMode(blueLEDpin,OUTPUT);
  Serial.begin(9600);

}


问:
How to play mp3 file in c++?
I'm looking for the easiest way to play an MP3 file in C++. Either a library I could use and just call the function, given the filename, or alternatively something someone has already written that will just run and quit.</p>

答:
What platform are you on? You can check these out:

In case of windows/linux:

FMOD

In case you are programming only on windows/mac osx:

BASS

I would also look for some native APIs in Windows (if you are developing on that platform).

HTH,

Sriram

Title: How to play mp3 file in c++?


问:
How to Print Alphabet sequentially in PHP?
I have an array variable $arr = array('A','B','C','D');

```<code>$number = 5; (This is dynamic)
</code>```

My new array value should be

```<code>$arr = array('A','B','C','D','E','F','G','H','I');
</code>```

If

```<code>$number = 3;
</code>```

Output should be:

```<code>$arr = array('A','B','C','D','E','F','G');
</code>```

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

答:
How about this one: https://3v4l.org/IGhoL</p>

```<code><?php

/**
 * Increments letter
 * @param int   $number
 * @param array &$arr
 */
function increment($number, &$arr) {
    $char = end($arr);
    $char++;
    for ($i = 0; $i < $number; $i++, $char++) {
        $arr[] = $char;
    }
}

$arr = range('A', 'D');
$number = 30;

increment($number, $arr);
var_dump($arr);
</code>```

Body:
I have an array variable $arr = array('A','B','C','D');

$number = 5; (This is dynamic)

My new array value should be

$arr = array('A','B','C','D','E','F','G','H','I');

If

$number = 3;

Output should be:

$arr = array('A','B','C','D','E','F','G');

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

Body:
How about this one: https://3v4l.org/IGhoL

<?php

/**
 * Increments letter
 * @param int   $number
 * @param array &$arr
 */
function increment($number, &$arr) {
    $char = end($arr);
    $char++;
    for ($i = 0; $i < $number; $i++, $char++) {
        $arr[] = $char;
    }
}

$arr = range('A', 'D');
$number = 30;

increment($number, $arr);
var_dump($arr);


问:
UIAlertView is not in window hierarchy
It says:

Attempt to present <UIAlertController: 0x106155a00> on <SignInViewController: 0x105f490a0> whose view is not in the window hierarchy!

```<code>@IBAction func signIn(_ sender: Any) {
    if let emailField = email.text, let passField = password.text {
        Auth.auth().signIn(withEmail: emailField, password: passField, completion: { (user, error) in
            if error != nil {
                guard let error = AuthErrorCode(rawValue: (error?._code)!) else {
                    return
                }
                self.fireErrorHandle(code: error)
            }else{
                if let userID = user?.uid {
                    KeychainWrapper.standard.set((userID), forKey: "uid")
                    self.performSegue(withIdentifier: "toFeed", sender: nil)
                }
            }
        })
    }
}

func fireErrorHandle(code: AuthErrorCode) {
    switch code {
    case .invalidCustomToken:
        //print("Indicates a validation error with the custom token")
        showAlert(title: "Error", message: "Validation error with the custom token.")
    case .customTokenMismatch:
        //print("Indicates the service account and the API key belong to different projects")
        showAlert(title: "Error", message: "Id Mismatch.")
    case .invalidCredential:
        //print("Indicates the IDP token or requestUri is invalid")
        showAlert(title: "Error", message: "RequestUri is invalid.")
    case .userDisabled:
        //print("Indicates the user's account is disabled on the server")
        showAlert(title: "Error", message: "Account is disabled.")
    case .operationNotAllowed:
        //print("Indicates the administrator disabled sign in with the specified identity provider")
        showAlert(title: "Error", message: "Administrator disabled sign in.")
    case .emailAlreadyInUse:
        //print("Indicates the email used to attempt a sign up is already in use.")
        showAlert(title: "Error", message: "Email already in use.")
    case .invalidEmail:
        //print("Indicates the email is invalid")
        showAlert(title: "Error", message: "Email is invalid.")
    case .wrongPassword:
        //print("Indicates the user attempted sign in with a wrong password")
        showAlert(title: "Error", message: "Wrong password.")
    case .tooManyRequests:
        //print("Indicates that too many requests were made to a server method")
        showAlert(title: "Error", message: "To many requests were made please try again late.")
    case .userNotFound:
       //print("Indicates the user account was not found")
        showAlert(title: "Error", message: "Account was not found.")
    case .accountExistsWithDifferentCredential:
        //print("Indicates account linking is required")
        showAlert(title: "Error", message: "account linking is required.")
    case .requiresRecentLogin:
        //print("Indicates the user has attemped to change email or password more than 5 minutes after signing in")
        showAlert(title: "Error", message: "Attemped to change email or password more than 5 minutes after signing in.")
    case .providerAlreadyLinked:
        //print("Indicates an attempt to link a provider to which the account is already linked")
        showAlert(title: "Error", message: "Link a provider to which the account is already linked.")
    case .noSuchProvider:
        //print("Indicates an attempt to unlink a provider that is not linked")
        showAlert(title: "Error", message: "Attempt to unlink a provider that is not linked.")
    case .invalidUserToken:
        //print("Indicates user's saved auth credential is invalid, the user needs to sign in again")
        showAlert(title: "Error", message: "Please sign in again.")
    case .networkError:
        //print("Indicates a network error occurred (such as a timeout, interrupted connection, or unreachable host). These types of errors are often recoverable with a retry. The @cNSUnderlyingError field in the @c NSError.userInfo dictionary will contain the error encountered")
        showAlert(title: "Error", message: "You have been timesout due to network error. Please try again.")
    case .userTokenExpired:
        //print("Indicates the saved token has expired, for example, the user may have changed account password on another device. The user needs to sign in again on the device that made this request")
        showAlert(title: "Error", message: "May have changed account password on another device.")
    case .invalidAPIKey:
        //print("Indicates an invalid API key was supplied in the request")
        showAlert(title: "Error", message: "error")
    case .userMismatch:
        //print("Indicates that an attempt was made to reauthenticate with a user which is not the current user")
        showAlert(title: "Error", message: "Error logging in.")
    case .credentialAlreadyInUse:
        //print("Indicates an attempt to link with a credential that has already been linked with a different Firebase account")
        showAlert(title: "Error", message: "Credential that has already been linked with a different account.")
    case .weakPassword:
        //print("Indicates an attempt to set a password that is considered too weak")
        showAlert(title: "Error", message: "Password to weak.")
    case .appNotAuthorized:
        //print("Indicates the App is not authorized to use Firebase Authentication with the provided API Key")
        showAlert(title: "Error", message: "Not authorized")
    case .keychainError:
        //print("Indicates an error occurred while attempting to access the keychain")
        showAlert(title: "Error", message: "An error has occured please try again")
    default:
        //print("Indicates an internal error occurred")
        showAlert(title: "Error", message: "Internal error, please try again.")
    }
}

func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message:message, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if Auth.auth().currentUser != nil {
        Timer.scheduledTimer(withTimeInterval: 0, repeats: false, block: { (timer) in
            self.performSegue(withIdentifier: "toFeed", sender: nil)
        })
    }

    if KeychainWrapper.standard.object(forKey: "uid") != nil {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.hideKeyboardWhenTappedAround()
    signInbutton.isEnabled = false
}
</code>```

I tried many different solutions and couldn't figure out what to do, I tried adding it to viewdidappear but I don't know how to add the AuthErrorCode to it. When I press the sign in button it performs the segue to another View Controller without any error handling.

答:
Make sure that the SignInViewController is not already presented controller on which you are going to present UIAlertController because you can not present UIAlertController on already presented UIViewController.

If you do so, you will get following error.

Attempt to present  on
   whose view is not in the window
  hierarchy!

Title: UIAlertView is not in window hierarchy

Body:
It says:

Attempt to present <UIAlertController: 0x106155a00> on <SignInViewController: 0x105f490a0> whose view is not in the window hierarchy!

@IBAction func signIn(_ sender: Any) {
    if let emailField = email.text, let passField = password.text {
        Auth.auth().signIn(withEmail: emailField, password: passField, completion: { (user, error) in
            if error != nil {
                guard let error = AuthErrorCode(rawValue: (error?._code)!) else {
                    return
                }
                self.fireErrorHandle(code: error)
            }else{
                if let userID = user?.uid {
                    KeychainWrapper.standard.set((userID), forKey: "uid")
                    self.performSegue(withIdentifier: "toFeed", sender: nil)
                }
            }
        })
    }
}

func fireErrorHandle(code: AuthErrorCode) {
    switch code {
    case .invalidCustomToken:
        //print("Indicates a validation error with the custom token")
        showAlert(title: "Error", message: "Validation error with the custom token.")
    case .customTokenMismatch:
        //print("Indicates the service account and the API key belong to different projects")
        showAlert(title: "Error", message: "Id Mismatch.")
    case .invalidCredential:
        //print("Indicates the IDP token or requestUri is invalid")
        showAlert(title: "Error", message: "RequestUri is invalid.")
    case .userDisabled:
        //print("Indicates the user's account is disabled on the server")
        showAlert(title: "Error", message: "Account is disabled.")
    case .operationNotAllowed:
        //print("Indicates the administrator disabled sign in with the specified identity provider")
        showAlert(title: "Error", message: "Administrator disabled sign in.")
    case .emailAlreadyInUse:
        //print("Indicates the email used to attempt a sign up is already in use.")
        showAlert(title: "Error", message: "Email already in use.")
    case .invalidEmail:
        //print("Indicates the email is invalid")
        showAlert(title: "Error", message: "Email is invalid.")
    case .wrongPassword:
        //print("Indicates the user attempted sign in with a wrong password")
        showAlert(title: "Error", message: "Wrong password.")
    case .tooManyRequests:
        //print("Indicates that too many requests were made to a server method")
        showAlert(title: "Error", message: "To many requests were made please try again late.")
    case .userNotFound:
       //print("Indicates the user account was not found")
        showAlert(title: "Error", message: "Account was not found.")
    case .accountExistsWithDifferentCredential:
        //print("Indicates account linking is required")
        showAlert(title: "Error", message: "account linking is required.")
    case .requiresRecentLogin:
        //print("Indicates the user has attemped to change email or password more than 5 minutes after signing in")
        showAlert(title: "Error", message: "Attemped to change email or password more than 5 minutes after signing in.")
    case .providerAlreadyLinked:
        //print("Indicates an attempt to link a provider to which the account is already linked")
        showAlert(title: "Error", message: "Link a provider to which the account is already linked.")
    case .noSuchProvider:
        //print("Indicates an attempt to unlink a provider that is not linked")
        showAlert(title: "Error", message: "Attempt to unlink a provider that is not linked.")
    case .invalidUserToken:
        //print("Indicates user's saved auth credential is invalid, the user needs to sign in again")
        showAlert(title: "Error", message: "Please sign in again.")
    case .networkError:
        //print("Indicates a network error occurred (such as a timeout, interrupted connection, or unreachable host). These types of errors are often recoverable with a retry. The @cNSUnderlyingError field in the @c NSError.userInfo dictionary will contain the error encountered")
        showAlert(title: "Error", message: "You have been timesout due to network error. Please try again.")
    case .userTokenExpired:
        //print("Indicates the saved token has expired, for example, the user may have changed account password on another device. The user needs to sign in again on the device that made this request")
        showAlert(title: "Error", message: "May have changed account password on another device.")
    case .invalidAPIKey:
        //print("Indicates an invalid API key was supplied in the request")
        showAlert(title: "Error", message: "error")
    case .userMismatch:
        //print("Indicates that an attempt was made to reauthenticate with a user which is not the current user")
        showAlert(title: "Error", message: "Error logging in.")
    case .credentialAlreadyInUse:
        //print("Indicates an attempt to link with a credential that has already been linked with a different Firebase account")
        showAlert(title: "Error", message: "Credential that has already been linked with a different account.")
    case .weakPassword:
        //print("Indicates an attempt to set a password that is considered too weak")
        showAlert(title: "Error", message: "Password to weak.")
    case .appNotAuthorized:
        //print("Indicates the App is not authorized to use Firebase Authentication with the provided API Key")
        showAlert(title: "Error", message: "Not authorized")
    case .keychainError:
        //print("Indicates an error occurred while attempting to access the keychain")
        showAlert(title: "Error", message: "An error has occured please try again")
    default:
        //print("Indicates an internal error occurred")
        showAlert(title: "Error", message: "Internal error, please try again.")
    }
}

func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message:message, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if Auth.auth().currentUser != nil {
        Timer.scheduledTimer(withTimeInterval: 0, repeats: false, block: { (timer) in
            self.performSegue(withIdentifier: "toFeed", sender: nil)
        })
    }

    if KeychainWrapper.standard.object(forKey: "uid") != nil {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.hideKeyboardWhenTappedAround()
    signInbutton.isEnabled = false
}

I tried many different solutions and couldn't figure out what to do, I tried adding it to viewdidappear but I don't know how to add the AuthErrorCode to it. When I press the sign in button it performs the segue to another View Controller without any error handling.


问:
How do I implement a TextBox that displays "Type here"?
Displaying "Type here to ..." until the user enters text into a TextBox is a well-known usability feature nowadays. How would one implement this feature in C#?

My idea is to override OnTextChanged, but the logic to handle the changes of text from and to "Type here" is a bit tricky...

Displaying "Type here" on initialization and removing it on first input is easy, but I want to display the message every time the entered text becomes empty.

答:
Based on answer of Ahmed Soliman Flasha use following class:</p>

```<code>public class TextBoxHint : TextBox
{
    string _hint;

    [Localizable(true)]
    public string Hint
    {
        get { return _hint; }
        set { _hint = value; OnHintChanged(); }
    }

    protected virtual void OnHintChanged()
    {
        SendMessage(this.Handle, EM_SETCUEBANNER, 1, _hint);
    }

    const int EM_SETCUEBANNER = 0x1501;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
}
</code>```

Body:
Based on answer of Ahmed Soliman Flasha use following class:

public class TextBoxHint : TextBox
{
    string _hint;

    [Localizable(true)]
    public string Hint
    {
        get { return _hint; }
        set { _hint = value; OnHintChanged(); }
    }

    protected virtual void OnHintChanged()
    {
        SendMessage(this.Handle, EM_SETCUEBANNER, 1, _hint);
    }

    const int EM_SETCUEBANNER = 0x1501;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
}


问:
A-Frame AR.js marker pattern not working
I'm using A-Frame and AR.js sample to create custom marker.

Link for Glitch example page : https://opposite-bike.glitch.me/testMarker.html

Link for Glitch project: https://glitch.com/edit/#!/opposite-bike

I have added two markers with .patt files, one is hiro which is available on AR.js site and other one is the custom one created using, https://jeromeetienne.github.io/AR.js/three.js/examples/marker-training/examples/generator.html

Path for the image files are,

Hiro pattern (working)

Kitten pattern (not working)

.patt files for both patterns are stored in markers folder for access.

Hiro pattern is working fine but the custom one is not.

Can anyone help, find what's missing?

Here is code

HTML

```<code><html>
  <head>
    <title>Multiple Markers - A-Frame School</title>
    <meta name="description" content="Multiple Markers - A-Frame School">
    <script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script>
    <!-- include ar.js for A-Frame -->
<script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>

  </head>
<body style="margin : 0px; overflow: hidden;">
  <a-scene embedded arjs="sourceType: webcam;">
    <!-- handle marker with your own pattern -->
    <a-marker type="pattern" patternurl="markers/hiro-m.patt">
      <a-sphere position="0 0.5 0" radius="0.25" rotation="0 10 0" color="#EF2D5E"></a-sphere>
    </a-marker>
    <a-marker type="pattern" patternurl="kmarkers/kitten.patt">
      <a-sphere position="0 0.5 0" radius="0.25" rotation="0 10 0" color="#ffccff"></a-sphere>
    </a-marker>
    <!-- handle marker with hiro preset -->
    <a-marker preset="hiro">
      <a-box position="0 0.5 0" material="color: green;"></a-box>
    </a-marker>
    <!-- handle barcode marker -->
    <a-marker type="barcode" value="5">
      <a-box position="0 0.5 0" material="color: blue;"></a-box>
    </a-marker>
    <!-- add a simple camera -->
    <a-entity camera></a-entity>
  </a-scene>
</body>
</html>
</code>```

答:
Is it because the image of the kitten is very complexed.

If you will see and open the insides of the PATT file that is being provided by AR.js once you trained a marker, you can see like this.

The pattern trainer just creates a file full of only 0's and 255's and it is the one that serves as the guide for the camera to identify the user.

In your case, the trainer will not recognize the image of the cat because it has very complex sides and edges.

In my case here, I tried to train a marker (which is the roundel of the Philippine Air Force), the marker trainer just generated a bunch of 0's in the PATT file because for AR.js, my image here is very complex.

In your case, the trainer maybe generated a PATT file containing bunch of 0's as well.

Body:
I'm using A-Frame and AR.js sample to create custom marker.

Link for Glitch example page : https://opposite-bike.glitch.me/testMarker.html

Link for Glitch project: https://glitch.com/edit/#!/opposite-bike

I have added two markers with .patt files, one is hiro which is available on AR.js site and other one is the custom one created using, https://jeromeetienne.github.io/AR.js/three.js/examples/marker-training/examples/generator.html

Path for the image files are,

Hiro pattern (working)

Kitten pattern (not working)

.patt files for both patterns are stored in markers folder for access.

Hiro pattern is working fine but the custom one is not.

Can anyone help, find what's missing?

Here is code

HTML

    <title>Multiple Markers - A-Frame School</title>
    <meta name="description" content="Multiple Markers - A-Frame School">