问:
need to be able to email a document or a content of UIView
a noob question here.

i would like to give the user a button that would prep an email with the content of a UIView attached.

is this (easily) doable ? I know how to create a basic email, but not with attachments and certainly not with a dump of an UIView content. I am guessing this would be a two step process. First get the content of the UIView into a "attachable form" (how ? #1). Then attach it. (how ? #2)

could someone please point me the right direction ?

thank you!

答:
i think you can start by converting the UIView to an image.

```<code>UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</code>```

after that you can read that to see how to attach the image to the mail

http://howtomakeiphoneapps.com/2009/07/how-to-make-your-iphone-app-send-email-with-attachments/

good luck

Body:
i think you can start by converting the UIView to an image.

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

after that you can read that to see how to attach the image to the mail

http://howtomakeiphoneapps.com/2009/07/how-to-make-your-iphone-app-send-email-with-attachments/

good luck


来源: stackexchange

问:
Chrome remove a certificate from personal store
I'm creating an API using node js and express. As we are moving towards production, I decided to encrypt the api using ssl, (simply adding the require 'https' option and creating the requires key and cert files using openssl).

I want to continue working on the API using postman (chrome plugin), so to enable me to do this, I  visited the API using Chrome, saved the cert for the API to disk and then imported that cert file (cer format) to the "personal" certificate store in Chrome. So far, so simple.

I was then able to start using the API over ssl as expected. Great.

Now, where it is starting to get a bit odd is that if I want to then remove that certificate from my personal certificate store in chrome, I was expecting to be able to just open up the settings - > htttps  - > manage certificates and then to be able to remove the certificate, however the certificate is not visible in the list of certs. It's clearly been imported and is working, it's just not showing in the list. The machine in question is running win 10, so I also checked the certificate management console for the machine and I searched for the cert and cannot find it anywhere.

I think that this should be really simple, so where is that cert that I imported (and which is clearly imported and working) so that I can remove it?

Thanks!

答: So, I finally found the solution to this. From the command line start "certmgr" and from there I can see the installed certificate and remove it. Not sure why it doesn't show up when viewed from within Chrome?!</p>

ContentLicense: CC BY-SA 3.0


问:
Get data from each row of a column in C #
It's as follows, I have a DataGridView with multiple columns. In each row of the DataGridView will be the version of the installation path of a program. With this value, I would like to use for the size of the folder and put it in the new column.

I have a method to calculate the size of a string:

```<code>private static long ObterTamanhoDiretorio(string tamanhoDir)
{
    DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
    return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}
</code>```

I do not know if it's something like that that I have to use.

```<code>foreach (DataGridViewRow item in dataGridView1.Rows)
{

}
</code>```

This is what I got:

```<code>ObjectQuery query8 = new ObjectQuery("SELECT Description, Version, InstallDate, Vendor, InstallLocation FROM Win32_Product");

ManagementObjectSearcher searcher8 = new ManagementObjectSearcher(scope, query8);

DataTable dt = new DataTable();
dt.Columns.Add("Program");
dt.Columns.Add("Version");
dt.Columns.Add("Installing Date");
dt.Columns.Add("Company");
dt.Columns.Add("Install Location");
dt.Columns.Add("Size");

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    foreach (ManagementObject queryObj in searcher8.Get())
    {
        var paths = new List<string>();
        var installPathColumnPos = 0;
        string s = item.Cells[installPathColumnPos].Value.ToString();
        dt.Rows.Add(new object[] { queryObj["Description"], queryObj["Version"], FormatDateTime(queryObj["InstallDate"]), queryObj["Vendor"], queryObj["InstallLocation"], s });
    }
}
dataGridView1.DataSource = dt;
</code>```

What I would like to know is how to get this value seeing on each line. If you have any ideas, thank you.

答:
```<code>var existingValues = dataGridView1.Rows
                                  .OfType<DataGridViewRow>()
                                  .Where(x => x.Cells[installPathColumnPos].Value != null)
                                  .Select(x => x.Cells[installPathColumnPos].Value.ToString())
</code>```

you can get the values by Linq please check this.

Body:
It's as follows, I have a DataGridView with multiple columns. In each row of the DataGridView will be the version of the installation path of a program. With this value, I would like to use for the size of the folder and put it in the new column.

I have a method to calculate the size of a string:

private static long ObterTamanhoDiretorio(string tamanhoDir)
{
    DirectoryInfo dire = new DirectoryInfo(tamanhoDir.ToString());
    return dire.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}

I do not know if it's something like that that I have to use.

foreach (DataGridViewRow item in dataGridView1.Rows)
{

}

This is what I got:

ObjectQuery query8 = new ObjectQuery("SELECT Description, Version, InstallDate, Vendor, InstallLocation FROM Win32_Product");

ManagementObjectSearcher searcher8 = new ManagementObjectSearcher(scope, query8);

DataTable dt = new DataTable();
dt.Columns.Add("Program");
dt.Columns.Add("Version");
dt.Columns.Add("Installing Date");
dt.Columns.Add("Company");
dt.Columns.Add("Install Location");
dt.Columns.Add("Size");

foreach (DataGridViewRow item in dataGridView1.Rows)
{
    foreach (ManagementObject queryObj in searcher8.Get())
    {
        var paths = new List<string>();
        var installPathColumnPos = 0;
        string s = item.Cells[installPathColumnPos].Value.ToString();
        dt.Rows.Add(new object[] { queryObj["Description"], queryObj["Version"], FormatDateTime(queryObj["InstallDate"]), queryObj["Vendor"], queryObj["InstallLocation"], s });
    }
}
dataGridView1.DataSource = dt;

What I would like to know is how to get this value seeing on each line. If you have any ideas, thank you.

Body:
var existingValues = dataGridView1.Rows
                                  .OfType<DataGridViewRow>()
                                  .Where(x => x.Cells[installPathColumnPos].Value != null)
                                  .Select(x => x.Cells[installPathColumnPos].Value.ToString())

you can get the values by Linq please check this.


问:
MSVCR110.dll is missing wamp can't start although MSVCR package is intalled
i am facing this problem and i don't know how to fix it.i have installed VCR 2010, VCR 2012, VCR 2013 and VCR 2010 (x86) on my machine but still when i want to start WAMP it gives me this message MSVCR110.dll is missing.

This snip shot is from my window control panel as you can see i have installed VCR packages.

This is the message when i want to run WAMP

答:
If you check on the WAMPServer Forum there is a document called WAMPServer 3 All you need to know

In that document there is a link to the Secondary repository of Wampserver files

In there, if you scroll to the bottom of the page you will find a link to an installer which will install all the possible required MSVC C/C++ runtime libraries that any version of Apache that WAMPServer can have installed might possibly need called
Microsoft VC++ packages VC2008, 2010, 2012, 2013, 2015, 2017 zip files

Click the link that matches the WAMPServer you have installed, 32bit or 64bit and run the installer.

For some unknown reason, Microsoft keep messing with the pages that are supposed to link to their downloads of these libraries, and ending up with broken links. V Annoying

Also remember that if you are using the WAMPSevrer 64bit you need to install BOTH the 32bit and 64bit versions of these MSVC Runtimes.


问:
Get images from internet into a collection
Hi all I am learning by trying to create. I have a demo code I am working with and wanted to know if there was a way of changing the image it shows (hard written in)(names of the cars) and change it so it shows an image from an url instead. because I'm newt this stuff i am trying to learn and can get examples of how to do it for other things but seem to struggle to get it into this code. I hope you can help.

I have a class call Post and I am getting images from firebase. So I use: post.imageUrl1 for the image url.

```<code>class DemoViewController: ExpandingViewController {
@IBAction func backPressed(_ sender: Any) {
}

   var post: Post!

 typealias ItemInfo = (imageName: String, title: String)
fileprivate var cellsIsOpen = [Bool]()
fileprivate let items: [ItemInfo] = [("Ferrari", "Ferrari"),("Bug",  "Bugatti"),("car", "Mustang"),("BM", "BMW")]

@IBOutlet weak var pageLabel: UILabel!
@IBOutlet weak var titleImageView: UIImageView!
@IBOutlet weak var titleImageViewXConstraint: NSLayoutConstraint!

}

// MARK: - Lifecycle
extension DemoViewController {

override func viewDidLoad() {
itemSize = CGSize(width: 256, height: 335)
super.viewDidLoad()

registerCell()
fillCellIsOpenArray()
addGesture(to: collectionView!)
configureNavBar()
 }

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let titleView = navigationItem.titleView else { return }
let center = UIScreen.main.bounds.midX
let diff = center - titleView.frame.midX
titleImageViewXConstraint.constant = diff
}

}

// MARK: Helpers
extension DemoViewController {

 fileprivate func registerCell() {

   let nib = UINib(nibName: String(describing:       DemoCollectionViewCell.self), bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier:  String(describing: DemoCollectionViewCell.self))
  }

  fileprivate func fillCellIsOpenArray() {
  cellsIsOpen = Array(repeating: false, count: items.count)
   }

fileprivate func getViewController() -> ExpandingTableViewController {
let storyboard = UIStoryboard(storyboard: .Main)
let toViewController: DemoTableViewController = storyboard.instantiateViewController()
return toViewController
}

fileprivate func configureNavBar() {
navigationItem.leftBarButtonItem?.image =  navigationItem.leftBarButtonItem?.image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
 }

 }

/// MARK: Gesture
extension DemoViewController {

fileprivate func addGesture(to view: UIView) {
let upGesture = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
  $0.direction = .up
 }

 let downGesture = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
  $0.direction = .down
 }
view.addGestureRecognizer(upGesture)
view.addGestureRecognizer(downGesture)
}

func swipeHandler(_ sender: UISwipeGestureRecognizer) {
let indexPath = IndexPath(row: currentIndex, section: 0)
guard let cell  = collectionView?.cellForItem(at: indexPath) as?  DemoCollectionViewCell else { return }
// double swipe Up transition
if cell.isOpened == true && sender.direction == .up {
  pushToViewController(getViewController())

  if let rightButton = navigationItem.rightBarButtonItem as?  AnimatingBarButton {
    rightButton.animationSelected(true)
   }
   }

  let open = sender.direction == .up ? true : false
  cell.cellIsOpen(open)
  cellsIsOpen[indexPath.row] = cell.isOpened
  }

  }

// MARK: UIScrollViewDelegate
extension DemoViewController {

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
 pageLabel.text = "\(currentIndex+1)/\(items.count)"
}

}

// MARK: UICollectionViewDataSource
extension DemoViewController {

 override func collectionView(_ collectionView: UICollectionView,   willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
guard let cell = cell as? DemoCollectionViewCell else { return }

let index = indexPath.row % items.count
let info = items[index]
cell.backgroundImageView?.image = UIImage(named: info.imageName)
cell.customTitle.text = info.title
cell.cellIsOpen(cellsIsOpen[index], animated: false)
}

 func collectionView(_ collectionView: UICollectionView,  didSelectItemAtIndexPath indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? DemoCollectionViewCell
      , currentIndex == indexPath.row else { return }

if cell.isOpened == false {
  cell.cellIsOpen(true)
} else {
  pushToViewController(getViewController())

  if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
    rightButton.animationSelected(true)
   }
  }
 }

}

// MARK: UICollectionViewDataSource
extension DemoViewController {

override func collectionView(_ collectionView: UICollectionView,  numberOfItemsInSection section: Int) -> Int {
 return items.count
}

 override func collectionView(_ collectionView: UICollectionView,   cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 return collectionView.dequeueReusableCell(withReuseIdentifier:  String(describing: DemoCollectionViewCell.self), for: indexPath)

  }

 }
</code>```

答:
You can download a picture from an URL using the designated constructor of Data: let imageData = Data(contentsOf: "exampleURL.com")

Then you just use this in your Collection View data source method:

```<code>override func collectionView(_ collectionView: UICollectionView,   willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
    guard let cell = cell as? DemoCollectionViewCell else { return }

    let index = indexPath.row % items.count
    let info = items[index]
    //here I assumed you would create a .url property of ItemInfo, but you can access the URL any way you want to
    guard let imageUrl = URL(string: info.url) else { return }
    do {
        let imageData = try Data(contentsOf: imageUrl)
    } catch {
        //handle error here
    }
    cell.backgroundImageView?.image = UIImage(data: imageData)
    cell.customTitle.text = info.title
    cell.cellIsOpen(cellsIsOpen[index], animated: false)
}
</code>```

Body:
Hi all I am learning by trying to create. I have a demo code I am working with and wanted to know if there was a way of changing the image it shows (hard written in)(names of the cars) and change it so it shows an image from an url instead. because I'm newt this stuff i am trying to learn and can get examples of how to do it for other things but seem to struggle to get it into this code. I hope you can help.

I have a class call Post and I am getting images from firebase. So I use: post.imageUrl1 for the image url.

class DemoViewController: ExpandingViewController {
@IBAction func backPressed(_ sender: Any) {
}

   var post: Post!

 typealias ItemInfo = (imageName: String, title: String)
fileprivate var cellsIsOpen = [Bool]()
fileprivate let items: [ItemInfo] = [("Ferrari", "Ferrari"),("Bug",  "Bugatti"),("car", "Mustang"),("BM", "BMW")]

@IBOutlet weak var pageLabel: UILabel!
@IBOutlet weak var titleImageView: UIImageView!
@IBOutlet weak var titleImageViewXConstraint: NSLayoutConstraint!

}

// MARK: - Lifecycle
extension DemoViewController {

override func viewDidLoad() {
itemSize = CGSize(width: 256, height: 335)
super.viewDidLoad()

registerCell()
fillCellIsOpenArray()
addGesture(to: collectionView!)
configureNavBar()
 }

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let titleView = navigationItem.titleView else { return }
let center = UIScreen.main.bounds.midX
let diff = center - titleView.frame.midX
titleImageViewXConstraint.constant = diff
}

}

// MARK: Helpers
extension DemoViewController {

 fileprivate func registerCell() {

   let nib = UINib(nibName: String(describing:       DemoCollectionViewCell.self), bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier:  String(describing: DemoCollectionViewCell.self))
  }

  fileprivate func fillCellIsOpenArray() {
  cellsIsOpen = Array(repeating: false, count: items.count)
   }

fileprivate func getViewController() -> ExpandingTableViewController {
let storyboard = UIStoryboard(storyboard: .Main)
let toViewController: DemoTableViewController = storyboard.instantiateViewController()
return toViewController
}

fileprivate func configureNavBar() {
navigationItem.leftBarButtonItem?.image =  navigationItem.leftBarButtonItem?.image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
 }

 }

/// MARK: Gesture
extension DemoViewController {

fileprivate func addGesture(to view: UIView) {
let upGesture = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
  $0.direction = .up
 }

 let downGesture = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
  $0.direction = .down
 }
view.addGestureRecognizer(upGesture)
view.addGestureRecognizer(downGesture)
}

func swipeHandler(_ sender: UISwipeGestureRecognizer) {
let indexPath = IndexPath(row: currentIndex, section: 0)
guard let cell  = collectionView?.cellForItem(at: indexPath) as?  DemoCollectionViewCell else { return }
// double swipe Up transition
if cell.isOpened == true && sender.direction == .up {
  pushToViewController(getViewController())

  if let rightButton = navigationItem.rightBarButtonItem as?  AnimatingBarButton {
    rightButton.animationSelected(true)
   }
   }

  let open = sender.direction == .up ? true : false
  cell.cellIsOpen(open)
  cellsIsOpen[indexPath.row] = cell.isOpened
  }

  }

// MARK: UIScrollViewDelegate
extension DemoViewController {

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
 pageLabel.text = "\(currentIndex+1)/\(items.count)"
}

}

// MARK: UICollectionViewDataSource
extension DemoViewController {

 override func collectionView(_ collectionView: UICollectionView,   willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
guard let cell = cell as? DemoCollectionViewCell else { return }

let index = indexPath.row % items.count
let info = items[index]
cell.backgroundImageView?.image = UIImage(named: info.imageName)
cell.customTitle.text = info.title
cell.cellIsOpen(cellsIsOpen[index], animated: false)
}

 func collectionView(_ collectionView: UICollectionView,  didSelectItemAtIndexPath indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? DemoCollectionViewCell
      , currentIndex == indexPath.row else { return }

if cell.isOpened == false {
  cell.cellIsOpen(true)
} else {
  pushToViewController(getViewController())

  if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
    rightButton.animationSelected(true)
   }
  }
 }

}

// MARK: UICollectionViewDataSource
extension DemoViewController {

override func collectionView(_ collectionView: UICollectionView,  numberOfItemsInSection section: Int) -> Int {
 return items.count
}

 override func collectionView(_ collectionView: UICollectionView,   cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 return collectionView.dequeueReusableCell(withReuseIdentifier:  String(describing: DemoCollectionViewCell.self), for: indexPath)

  }

 }

Body:
You can download a picture from an URL using the designated constructor of Data: let imageData = Data(contentsOf: "exampleURL.com")

Then you just use this in your Collection View data source method:

override func collectionView(_ collectionView: UICollectionView,   willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
    guard let cell = cell as? DemoCollectionViewCell else { return }

    let index = indexPath.row % items.count
    let info = items[index]
    //here I assumed you would create a .url property of ItemInfo, but you can access the URL any way you want to
    guard let imageUrl = URL(string: info.url) else { return }
    do {
        let imageData = try Data(contentsOf: imageUrl)
    } catch {
        //handle error here
    }
    cell.backgroundImageView?.image = UIImage(data: imageData)
    cell.customTitle.text = info.title
    cell.cellIsOpen(cellsIsOpen[index], animated: false)
}


问:
NodeJS - The Package of mysql respects the names of the columns on having done an INSERT INTO... SET?
I am developing a Rest API using NodeJS and MySQL as the atabase. I use the standard package of npm for MySQL. I am using the following statement at the moment of insert data into DB:

```<code>INSERT INTO DATABASE.TABLE SET ?
</code>```

And the JSON that I am trying to insert is:

```<code>{
     name    : "Lorem",
     surname : "Ipsum",
     email   : "lorem.ipsum@mail.com"
}
</code>```

But in the database the order of columns is:

Do you know if the order of the fields matters, or does the NodeJS mysql package  respect the name of the columns?

答:
It doesn't matter.

According to the JSON spec the order of the attributes is not significant.

And as you don't have brackets arround keys (which is required for valid JSON) I suppose you're missing it with regular JavaScript object which doesn't have ordering guaranties as well.

Body:
I am developing a Rest API using NodeJS and MySQL as the atabase. I use the standard package of npm for MySQL. I am using the following statement at the moment of insert data into DB:

INSERT INTO DATABASE.TABLE SET ?

And the JSON that I am trying to insert is:

{
     name    : "Lorem",
     surname : "Ipsum",
     email   : "lorem.ipsum@mail.com"
}

But in the database the order of columns is:

Do you know if the order of the fields matters, or does the NodeJS mysql package  respect the name of the columns?


问:
Debounce input to http service call
What I am currently doing is set the input 2-way-binding to appRequestParams.appName, and on every keyup event, the fetchApps() method will be called.

I am trying to debounce the input such that it will not fire off a backend http request on every keyup immediately.

I have read up on ways to go about doing it and here what I have come out with.

HTML

```<code><input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(searchBox.value)" />
</code>```

Typescript

```<code>private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           this.fetchApps();
       });
   }
</code>```

Error on line of .switchMap():

```<code>Argument of type '(value: string) => void' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.
</code>```

答:
I ended up using this and it works perfectly.</p>

```<code>   this.searchTerms
   .debounceTime(300)
   .distinctUntilChanged()
   .switchMap(
    (term) => {
        console.log('Term:' + term);
        this.appRequestParams.appName = term;
        this.fetchApps();
        return term;
    })
    .subscribe();
}
</code>```

Title: Debounce input to http service call

Body:
What I am currently doing is set the input 2-way-binding to appRequestParams.appName, and on every keyup event, the fetchApps() method will be called.

I am trying to debounce the input such that it will not fire off a backend http request on every keyup immediately.

I have read up on ways to go about doing it and here what I have come out with.

HTML

<input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(searchBox.value)" />

Typescript

private searchTerms = new Subject<string>();

search(value: string): void {
       this.searchTerms.next(value);
   }

fetchApps() {
       this.appService.query({
           appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
       }).subscribe(
           (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
           (res: ResponseWrapper) => this.onError(res.json)
       );
   }

ngOnInit() {
       this.searchTerms
       .debounceTime(300)
       .distinctUntilChanged()
       .switchMap((value: string) => {
           this.appRequestParams.appName = value;
           this.fetchApps();
       });
   }

Error on line of .switchMap():

Argument of type '(value: string) => void' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'.
  Type 'void' is not assignable to type 'ObservableInput<{}>'.

Body:
I ended up using this and it works perfectly.

   this.searchTerms
   .debounceTime(300)
   .distinctUntilChanged()
   .switchMap(
    (term) => {
        console.log('Term:' + term);
        this.appRequestParams.appName = term;
        this.fetchApps();
        return term;
    })
    .subscribe();
}


问:
how to create html table in php
I have the following snippet of code that basically uses explode to split out these values:

```<code><?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>
</code>```

Data: (prod.txt)

```<code>PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
</code>```

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

```<code>PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2
</code>```

答:
```<code>echo '<table><tr><td>PREFIX</td><td>Part</td>File</td></tr>';
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   $count=count($pieces);

   echo '<tr>';
   for ($counter=0; $counter <$count; $counter++)
   {
     echo '<td>'.$pieces[$counter].'<td>';
   }
  echo '</tr>';
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to create html table in php

Body:
I have the following snippet of code that basically uses explode to split out these values:

<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>

Data: (prod.txt)

PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2


问:
MySQL - ORDER BY, CASE and DESC
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";
</code>```

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";
</code>```

This one throws a syntax error. How can I achieve this?

答:
CASE only can return one expression, so you will have several cases:

```<code>CASE WHEN $var = 1 THEN myText1 END,
CASE WHEN $var = 2 THEN myText2 END,
CASE WHEN $var = 3 THEN someNumber END DESC
</code>```

OR, optimized

```<code>CASE
     WHEN $var = 1 THEN myText1,
     WHEN $var = 2 THEN myText2
END,
CASE WHEN $var = 3 THEN someNumber END DESC
</code>```

Title: MySQL - ORDER BY, CASE and DESC

Body:
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";

This one throws a syntax error. How can I achieve this?

Body:
CASE only can return one expression, so you will have several cases:

CASE WHEN $var = 1 THEN myText1 END,
CASE WHEN $var = 2 THEN myText2 END,
CASE WHEN $var = 3 THEN someNumber END DESC

OR, optimized

CASE
     WHEN $var = 1 THEN myText1,
     WHEN $var = 2 THEN myText2
END,
CASE WHEN $var = 3 THEN someNumber END DESC


问:
Count number of times the get method in a dict returns the second option
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

```<code>dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]
</code>```

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

```<code>list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)
</code>```

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

```<code>dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1
</code>```

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?

答:
```<code>from collections import defaultdict
cnt = 0
def count_missing():
    global cnt
    cnt += 1
    return 0
d = defaultdict(count_missing)
d['foo'] = 1
d['bar'] = 2
list_values = [d[k] for k in ['foo', 'bar', 'baz']]
print(cnt)
</code>```

Body:
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?


问:
how to break a line java script
i am setting a text of a h4 through java script what i want to do is add new line here's the code

```<code>$("#description").text("for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");
</code>```

now i tried it with multiple solutions but still not working here's another one

```<code>$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");
</code>```

any help?

答:
use the html() function to put the raw html inside an element as</p>

```<code>$("#description").html("for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");
</code>```

Title: how to break a line java script

Body:
i am setting a text of a h4 through java script what i want to do is add new line here's the code

$("#description").text("for CCAET and has received significant international scientific recognition.
 \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");

now i tried it with multiple solutions but still not working here's another one

$("#description").text("or CCAET and has received significant international scientific recognition.Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management."+
                        "abc"+
                         "def");

any help?

Body:
use the html() function to put the raw html inside an element as

$("#description").html("for CCAET and has received significant international scientific recognition. <br /> \n Dr. Armogan has also been responsible for many surgical firsts in retina and cataract management.");


问:
Replace default Android Maps API v2 Change MyLocation icon
I would like to replace the default icon that Android Maps V2 uses for 'My Location' with my own image. I've created my own tile provider that brings in a few maps which are predominantly blue and as such the default My Location icon, the little blue arrow, is very hard to see.

Previously I would have just overridden the draw method of the MyLocationOverlay, but there doesn't seem to be one in the new API.

I also need the icon to be able to rotate, the same way that the arrow does depending on which way you are facing. So I can't just use a normal marker. Basically I just need to create a custom image for that arrow.

答:
Here is the code to access location button:</p>

```<code>View mv=findViewById(R.id.map);
        View locationButton = ((View) mv.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        rlp.setMargins(0, 180, 180, 0);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the code to access location button:

View mv=findViewById(R.id.map);
        View locationButton = ((View) mv.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        rlp.setMargins(0, 180, 180, 0);


问:
Browser helper object not working properly
Am working on adding addon to IE11 (64bit) in windows7 and followed the  below link

Brwserhelperobject

Iam able to see addon in my IE manage addon's but, iam not able to see message box.

Can any one say what iam missing.

答:
In the given link
the following event is not triggered  some times due to this message box is not popped out

```<code>webBrowser.BeforeNavigate2 += new
        DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
</code>```

so instead of using above event use the below code

```<code> webBrowser.BeforeNavigate2+= WebBrowser_BeforeNavigate2;
</code>```

which generates  a method

```<code> private void WebBrowser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{
</code>```

//write messegebox here
    }

Body:
In the given link
the following event is not triggered  some times due to this message box is not popped out

webBrowser.BeforeNavigate2 += new
        DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);

so instead of using above event use the below code

 webBrowser.BeforeNavigate2+= WebBrowser_BeforeNavigate2;

which generates  a method

 private void WebBrowser_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{

//write messegebox here
    }


问:
Query DynamoDB in .NET using DynamoDBContext.Query<T> with QueryOperator vs using QueryFilter with List<ScanCondition>
I'm trying to query a DynamoDB table using a Global Secondary Index with an HashKey and a RangeKey.

I want to QUERY the IndexCustomerId by CustomerId and DateTime range (from-to). There's no option to set the Index RangeKey as a DateTime. The only choices are: String, Number and Binary.

I'm using C# Object Persistence Model Amazon.DynamoDBv2.DataModel API on .NET Framework v3.5.

Table:

```<code>+-------------------+----------+---------------------------+----------------+------------+
| InputFlowCode     |  Counter |  OrderIssueDate           |  OrderTypeCode | CustomerId |
+-------------------+----------+---------------------------+----------------+------------+
| bac9-35df6ac533fc |  000004  |  2016-07-19T22:00:00.000Z | 220            | 123        |
+-------------------+----------+---------------------------+----------------+------------+
| a3db-9d6f56a5c611 |  000006  |  2016-06-30T22:00:00.000Z | 220            | 456        |
+-------------------+----------+---------------------------+----------------+------------+
| af1c-db5b089c1e32 |  000010  |  2016-07-02T22:00:00.000Z | 220            | 789        |
+-------------------+----------+---------------------------+----------------+------------+
| ...               | ...      | ...                       | ...            | ...        |
+-------------------+----------+---------------------------+----------------+------------+
</code>```

Global Secondary Index definition:

```<code>IndexCustomerId:
- CustomerId (integer),
- OrderIssueDate (DateTime on model, but string on Index definition)
</code>```

Code:

```<code>try
{
    DateTime dateFrom = new DateTime(2016, 08, 01);
    DateTime dateTo = new DateTime(2016, 08, 15);

    List<MyDynamoDBItem> items = new List<MyDynamoDBItem>();

    DynamoDBOperationConfig operationConfig = new DynamoDBOperationConfig();
    operationConfig.OverrideTableName = "Transactions";
    operationConfig.IndexName = "IndexCustomerId";

    DynamoDBContext context = new DynamoDBContext(DynamoDBClient);

    // 1) Works
    items = context.Query<MyDynamoDBItem>(customerId, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();

    // 2) Doesn't work
    items = context.Query<MyDynamoDBItem>(customerId, QueryOperator.Between, dateFrom, dateTo, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();

    // 3) Works, but I don't know if it is the right choice...
    List<ScanCondition> conditions = new List<ScanCondition>();
    conditions.Add(new ScanCondition(PeppolOrdineDynamoDBTableAttributes.OrderIssueDate, ScanOperator.Between, dateFrom, dateTo));
    operationConfig.QueryFilter = conditions;
    items = context.Query<MyDynamoDBItem>(customerId, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();
}
catch (Exception)
{
    throw;
}
</code>```

The first query without parameters works.

The second query with the Between operator and the 2 DateTime throws an Exception:

```<code>{"Cannot cast objects of type 'System.Int32' to type 'System.String'."}
</code>```

The third query that uses QueryFilter that is a List and  ScanOperator works too, but I don't know what's the difference with QueryOperator and also if it is the right choice, since I want to make a QUERY and not a SCAN.

答:
I had the same problem but I was using greaterThan, I found that adding the parameter values into an object array fixed it.

So maybe something like:

```<code>items = context.Query<MyDynamoDBItem>(customerId, QueryOperator.Between, new object[] {dateFrom, dateTo}, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();
</code>```

Body:
I'm trying to query a DynamoDB table using a Global Secondary Index with an HashKey and a RangeKey.

I want to QUERY the IndexCustomerId by CustomerId and DateTime range (from-to). There's no option to set the Index RangeKey as a DateTime. The only choices are: String, Number and Binary.

I'm using C# Object Persistence Model Amazon.DynamoDBv2.DataModel API on .NET Framework v3.5.

Table:

+-------------------+----------+---------------------------+----------------+------------+
| InputFlowCode     |  Counter |  OrderIssueDate           |  OrderTypeCode | CustomerId |
+-------------------+----------+---------------------------+----------------+------------+
| bac9-35df6ac533fc |  000004  |  2016-07-19T22:00:00.000Z | 220            | 123        |
+-------------------+----------+---------------------------+----------------+------------+
| a3db-9d6f56a5c611 |  000006  |  2016-06-30T22:00:00.000Z | 220            | 456        |
+-------------------+----------+---------------------------+----------------+------------+
| af1c-db5b089c1e32 |  000010  |  2016-07-02T22:00:00.000Z | 220            | 789        |
+-------------------+----------+---------------------------+----------------+------------+
| ...               | ...      | ...                       | ...            | ...        |
+-------------------+----------+---------------------------+----------------+------------+

Global Secondary Index definition:

IndexCustomerId:
- CustomerId (integer),
- OrderIssueDate (DateTime on model, but string on Index definition)

Code:

try
{
    DateTime dateFrom = new DateTime(2016, 08, 01);
    DateTime dateTo = new DateTime(2016, 08, 15);

    List<MyDynamoDBItem> items = new List<MyDynamoDBItem>();

    DynamoDBOperationConfig operationConfig = new DynamoDBOperationConfig();
    operationConfig.OverrideTableName = "Transactions";
    operationConfig.IndexName = "IndexCustomerId";

    DynamoDBContext context = new DynamoDBContext(DynamoDBClient);

    // 1) Works
    items = context.Query<MyDynamoDBItem>(customerId, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();

    // 2) Doesn't work
    items = context.Query<MyDynamoDBItem>(customerId, QueryOperator.Between, dateFrom, dateTo, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();

    // 3) Works, but I don't know if it is the right choice...
    List<ScanCondition> conditions = new List<ScanCondition>();
    conditions.Add(new ScanCondition(PeppolOrdineDynamoDBTableAttributes.OrderIssueDate, ScanOperator.Between, dateFrom, dateTo));
    operationConfig.QueryFilter = conditions;
    items = context.Query<MyDynamoDBItem>(customerId, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();
}
catch (Exception)
{
    throw;
}

The first query without parameters works.

The second query with the Between operator and the 2 DateTime throws an Exception:

{"Cannot cast objects of type 'System.Int32' to type 'System.String'."}

The third query that uses QueryFilter that is a List and  ScanOperator works too, but I don't know what's the difference with QueryOperator and also if it is the right choice, since I want to make a QUERY and not a SCAN.

Body:
I had the same problem but I was using greaterThan, I found that adding the parameter values into an object array fixed it.

So maybe something like:

items = context.Query<MyDynamoDBItem>(customerId, QueryOperator.Between, new object[] {dateFrom, dateTo}, operationConfig).OrderByDescending(o => o.OrderIssueDate).ToList();


问:
JSON not parsing from API call
After looking on here a lot I haven't found something similar to this problem.

I'm getting the JSON from my API call however it isn't parsing I went through the steps I'm using and getting a Parsing error that is SyntaxError: Unexpected token s in JSON at position 1 I will post examples of everything below and hopefully someone can tell me what I did wrong (I've been using the same thing to parse other objects and they worked not sure why this doesn't)

Expected JSON

```<code>{
"user":{
    "id":1054776,
    "email":"fghrklhjkltghskj@gmail.com",
    "username":"user1496654688",
    "first_name":null,
    "last_name":null,
    "last_login":null,
    "email_confirmed":false
    }
}
</code>```

RegisterRequest.java

```<code>public class RegisterRequest {

    private Context mContext;
    private Map<String, String> mCredentials;

    public interface RegisterFeedback{
        void onRegisterSuccess(RegisterResponse response);
        void onRegisterFailed(Exception exception);
    }

    public RegisterRequest(Context context) {
        mContext = context;
    }

    public void sendRegistration(String email, String password, RegisterFeedback feedback) {
        String url = Constants.BASE_URL + Constants.REGISTRATION_URL;
        Gson gson = new Gson();
        mCredentials = new HashMap<>();
        mCredentials.put("email", email);
        mCredentials.put("password", password);

        final RegisterFeedback registerFeedback = feedback;

        GsonRequest<RegisterResponse> request = new GsonRequest<>(url, RegisterResponse.class, null,
                Request.Method.POST, mCredentials, new Response.Listener<RegisterResponse>() {
            @Override
            public void onResponse(RegisterResponse response) {
                registerFeedback.onRegisterSuccess(response);
                PreferenceConnector.writeString(mContext, "authToken", response.getAccessToken());

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                registerFeedback.onRegisterFailed(error);

            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        ));

        RequestFactory.getInstance(mContext).addtoRequestQueue(request);

    }

}
</code>```

RegisterResponse.java

```<code>@Parcel
public class RegisterResponse {

    @SerializedName("id")
    private String id;
    @SerializedName("email")
    private String email;
    @SerializedName("username")
    private String username;
    @SerializedName("first_name")
    private String firstName;
    @SerializedName("last_name")
    private String lastName;
    @SerializedName("last_login")
    private String lastLogin;
    @SerializedName("email_confirmed")
    private String emailConfirmed;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastLogin() {
        return lastLogin;
    }

    public void setLastLogin(String lastLogin) {
        this.lastLogin = lastLogin;
    }

    public String isEmailConfirmed() {
        return emailConfirmed;
    }

    public void setEmailConfirmed(String emailConfirmed) {
        this.emailConfirmed = emailConfirmed;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
</code>```

GsonRequest.java

```<code>public class GsonRequest<T> extends JsonRequest<T> {

    private final Gson gson = new Gson();
    private Map<String, String> bodyJson;
    private final Class<T> clazz;
    private Map<String, String> headers;
    private Response.Listener<T> listener;
    private static final String CONTENT_TYPE = "Content-Type";

    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/x-www-form-urlencoded");

    public GsonRequest(String url, Class<T> clazz, Map<String, String> headers, int method, @Nullable Map<String, String> bodyJson,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {

        super(method, url, getFormDataString(bodyJson), listener, errorListener);
        this.clazz = clazz;
        this.listener = listener;
        this.bodyJson = bodyJson;

        if (headers == null) {
            this.headers = new HashMap<>();
        } else {
            this.headers = headers;
        }

        this.headers.put("client-id", Constants.API_CLIENT_ID);
        this.headers.put("client_secret", Constants.API_CLIENT_SECRET);
        this.headers.put("Accept-Encoding", "gzip, deflate, sdch");
    }

    private static String getFormDataString(Map<String, String> formData){

        StringBuilder params = new StringBuilder();
        if (formData != null) {
            for (String key : formData.keySet()) {
                params.append("&").append(key).append("=").append(formData.get(key));
            }

            return params.toString().substring(1);
        }else {
            return null;
        }
    }

    @Override
    public Map<String, String> getParams() throws AuthFailureError {
        return bodyJson != null ? bodyJson : super.getParams();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    protected void deliverResponse(T response){
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json;
            String encoding = response.headers.get("Content-Encoding");

            if (encoding != null && encoding.equals("gzip")) {
                json = unpackData(response.data);
            } else {
                json = new String (
                        response.data, HttpHeaderParser.parseCharset(response.headers));
            }

            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    private String unpackData(byte[] data) {
        String output = "";

        try {
            GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(data));
            InputStreamReader reader = new InputStreamReader(gStream);
            BufferedReader in = new BufferedReader(reader);
            String read;
            while ((read = in.readLine()) != null) {
                output += read;
            }
            reader.close();
            in.close();
            gStream.close();
        } catch (IOException e) {
            return null;
        }

        return output;
    }

}
</code>```

Any help would be appreciated, thank you in advance :D

答:
Your expected JSON has comma at the end after "email_confirmed":false,
Please rectify it and try again.</p>

Title: JSON not parsing from API call

Body:
After looking on here a lot I haven't found something similar to this problem.

I'm getting the JSON from my API call however it isn't parsing I went through the steps I'm using and getting a Parsing error that is SyntaxError: Unexpected token s in JSON at position 1 I will post examples of everything below and hopefully someone can tell me what I did wrong (I've been using the same thing to parse other objects and they worked not sure why this doesn't)

Expected JSON

{
"user":{
    "id":1054776,
    "email":"fghrklhjkltghskj@gmail.com",
    "username":"user1496654688",
    "first_name":null,
    "last_name":null,
    "last_login":null,
    "email_confirmed":false
    }
}

RegisterRequest.java

public class RegisterRequest {

    private Context mContext;
    private Map<String, String> mCredentials;

    public interface RegisterFeedback{
        void onRegisterSuccess(RegisterResponse response);
        void onRegisterFailed(Exception exception);
    }

    public RegisterRequest(Context context) {
        mContext = context;
    }

    public void sendRegistration(String email, String password, RegisterFeedback feedback) {
        String url = Constants.BASE_URL + Constants.REGISTRATION_URL;
        Gson gson = new Gson();
        mCredentials = new HashMap<>();
        mCredentials.put("email", email);
        mCredentials.put("password", password);

        final RegisterFeedback registerFeedback = feedback;

        GsonRequest<RegisterResponse> request = new GsonRequest<>(url, RegisterResponse.class, null,
                Request.Method.POST, mCredentials, new Response.Listener<RegisterResponse>() {
            @Override
            public void onResponse(RegisterResponse response) {
                registerFeedback.onRegisterSuccess(response);
                PreferenceConnector.writeString(mContext, "authToken", response.getAccessToken());

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                registerFeedback.onRegisterFailed(error);

            }
        });

        request.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        ));

        RequestFactory.getInstance(mContext).addtoRequestQueue(request);

    }

}

RegisterResponse.java

@Parcel
public class RegisterResponse {

    @SerializedName("id")
    private String id;
    @SerializedName("email")
    private String email;
    @SerializedName("username")
    private String username;
    @SerializedName("first_name")
    private String firstName;
    @SerializedName("last_name")
    private String lastName;
    @SerializedName("last_login")
    private String lastLogin;
    @SerializedName("email_confirmed")
    private String emailConfirmed;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastLogin() {
        return lastLogin;
    }

    public void setLastLogin(String lastLogin) {
        this.lastLogin = lastLogin;
    }

    public String isEmailConfirmed() {
        return emailConfirmed;
    }

    public void setEmailConfirmed(String emailConfirmed) {
        this.emailConfirmed = emailConfirmed;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

GsonRequest.java

public class GsonRequest<T> extends JsonRequest<T> {

    private final Gson gson = new Gson();
    private Map<String, String> bodyJson;
    private final Class<T> clazz;
    private Map<String, String> headers;
    private Response.Listener<T> listener;
    private static final String CONTENT_TYPE = "Content-Type";

    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/x-www-form-urlencoded");

    public GsonRequest(String url, Class<T> clazz, Map<String, String> headers, int method, @Nullable Map<String, String> bodyJson,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {

        super(method, url, getFormDataString(bodyJson), listener, errorListener);
        this.clazz = clazz;
        this.listener = listener;
        this.bodyJson = bodyJson;

        if (headers == null) {
            this.headers = new HashMap<>();
        } else {
            this.headers = headers;
        }

        this.headers.put("client-id", Constants.API_CLIENT_ID);
        this.headers.put("client_secret", Constants.API_CLIENT_SECRET);
        this.headers.put("Accept-Encoding", "gzip, deflate, sdch");
    }

    private static String getFormDataString(Map<String, String> formData){

        StringBuilder params = new StringBuilder();
        if (formData != null) {
            for (String key : formData.keySet()) {
                params.append("&").append(key).append("=").append(formData.get(key));
            }

            return params.toString().substring(1);
        }else {
            return null;
        }
    }

    @Override
    public Map<String, String> getParams() throws AuthFailureError {
        return bodyJson != null ? bodyJson : super.getParams();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    protected void deliverResponse(T response){
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json;
            String encoding = response.headers.get("Content-Encoding");

            if (encoding != null && encoding.equals("gzip")) {
                json = unpackData(response.data);
            } else {
                json = new String (
                        response.data, HttpHeaderParser.parseCharset(response.headers));
            }

            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    private String unpackData(byte[] data) {
        String output = "";

        try {
            GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(data));
            InputStreamReader reader = new InputStreamReader(gStream);
            BufferedReader in = new BufferedReader(reader);
            String read;
            while ((read = in.readLine()) != null) {
                output += read;
            }
            reader.close();
            in.close();
            gStream.close();
        } catch (IOException e) {
            return null;
        }

        return output;
    }

}

Any help would be appreciated, thank you in advance :D


问:
Unique 8 digit incremental number
I'm trying to generate a number which will ultimately be stored as string(varchar). e.g.

First - ABC00000001

Second- ABC00000002
.........................
I am able to generate character string as expected. Now the problem is,incremental number.

What i am trying to do is get the last number stored e.g. ABC00000009 and generate the next number that is ABC00000010. How to do the same?

If i extract integers from this than i will get 1 or 10,how to make it according to 8 digit format.

Any help would really be appreciated.

答:
I would suggest that you create an identity column.  This will increment (usually by 1, but not always).  Then create a computed column:</p>

```<code>alter table t add generated_number as
    ('ABC' + right(replicate('0', 8) + cast(idcol as varchar(255)), 8));
</code>```

Title: Unique 8 digit incremental number

Body:
I would suggest that you create an identity column.  This will increment (usually by 1, but not always).  Then create a computed column:

alter table t add generated_number as
    ('ABC' + right(replicate('0', 8) + cast(idcol as varchar(255)), 8));


问:
Text to Morse Code
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

```<code>import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want
</code>```

can you tell me how i can assign winsound.Beep() to a varible?

答:
My solution to your problem will involve passing functions as parameters to other functions. If this is unfamiliar to you, I suggest you look into functional programming with Python a little bit.

```<code>import winsound
import time

# first - create the `dot` and `line` functions
def dot():
    winsound.Beep(600, 100)
    time.sleep(0.1)               # this is in seconds

def line():
    ....

def space():
    ....

def full_stop():
    ....

# now you need some way of mapping letters to sounds
mapping = {
    "a": (dot, line),
    "b": (line, dot, dot, dot),
    ....
    " ": (space,),                 # A one-tuple is defined like this, not like `(var)`
    ".": (full_stop,)
}

# And as a final step you need a function to play the sounds
def play_morse(message):
    for character in message:
        character = character.lower()
        if character in mapping:
            for func in mapping[character]:
                func()
        else:
            print("Unknown character: '{}'".format(character))
</code>```

You would use the function like so:

```<code>>>> play_morse("Hello world!")
</code>```

Title: Text to Morse Code

Body:
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want

can you tell me how i can assign winsound.Beep() to a varible?

Body:
My solution to your problem will involve passing functions as parameters to other functions. If this is unfamiliar to you, I suggest you look into functional programming with Python a little bit.

import winsound
import time

# first - create the `dot` and `line` functions
def dot():
    winsound.Beep(600, 100)
    time.sleep(0.1)               # this is in seconds

def line():
    ....

def space():
    ....

def full_stop():
    ....

# now you need some way of mapping letters to sounds
mapping = {
    "a": (dot, line),
    "b": (line, dot, dot, dot),
    ....
    " ": (space,),                 # A one-tuple is defined like this, not like `(var)`
    ".": (full_stop,)
}

# And as a final step you need a function to play the sounds
def play_morse(message):
    for character in message:
        character = character.lower()
        if character in mapping:
            for func in mapping[character]:
                func()
        else:
            print("Unknown character: '{}'".format(character))

You would use the function like so:

>>> play_morse("Hello world!")


问:
How to create SQL query in Codiginator Model insensitive queries - SQL LIKE queries
I designed an app in Codeignitor, here I search enquiry based on contact person name, company name, email id, mobile no. I am using CI ORM Statements to perform database queries - does anyone have an idea how I can ignore case in these columns, so all the columns in capital or small letter there is no impact.

Here is my modal function for search the query:

```<code>public function search1($from1, $to1, $q)
{
    if(empty($q))
    {
        $this->db->where("enq_date >=",$from1);
        $this->db->where("enq_date <=",$to1);
        return $this->db->get('enq_capture')->result();
    }
    else
    {
        $where = array('enq_date>=' => $from1, 'enq_date <=' => $to1);
        $query=$this->db->select('*')
                    ->from('enq_capture')
                    ->where($where)
                    ->like('company_name',$q)
                    ->or_like('c_person',$q)
                    //->or_like('email',$q)
                    ->get();

        //print_r($query);
        return $query->result();
    }
}
</code>```

And here is my controller function:

```<code>public function search1()
{
    $data['user_data']=$this->is_logged_in();
    $q=$this->input->post('searchid');
    $from1=$this->input->post('from1');
    $to1=$this->input->post('to1');
    $data['search_data']=$this->Enquiry_model->search1($from1,$to1,$q);
    $this->load->view('admin1/enquiry/search_enquiry1',$data);
}
</code>```

答:
Use LOWER() function</p>

```<code>$query = $this->db->query("SELECT * FROM enq_capture WHERE enq_date >= '{$from1}' AND enq_date <= '{$to1}' AND (LOWER(company_name) LIKE '%{$qLower}%' OR LOWER(c_person) LIKE '%{$qLower}%')");
return $query->result();
</code>```

Body:
I designed an app in Codeignitor, here I search enquiry based on contact person name, company name, email id, mobile no. I am using CI ORM Statements to perform database queries - does anyone have an idea how I can ignore case in these columns, so all the columns in capital or small letter there is no impact.

Here is my modal function for search the query:

public function search1($from1, $to1, $q)
{
    if(empty($q))
    {
        $this->db->where("enq_date >=",$from1);
        $this->db->where("enq_date <=",$to1);
        return $this->db->get('enq_capture')->result();
    }
    else
    {
        $where = array('enq_date>=' => $from1, 'enq_date <=' => $to1);
        $query=$this->db->select('*')
                    ->from('enq_capture')
                    ->where($where)
                    ->like('company_name',$q)
                    ->or_like('c_person',$q)
                    //->or_like('email',$q)
                    ->get();

        //print_r($query);
        return $query->result();
    }
}

And here is my controller function:

public function search1()
{
    $data['user_data']=$this->is_logged_in();
    $q=$this->input->post('searchid');
    $from1=$this->input->post('from1');
    $to1=$this->input->post('to1');
    $data['search_data']=$this->Enquiry_model->search1($from1,$to1,$q);
    $this->load->view('admin1/enquiry/search_enquiry1',$data);
}

Body:
Use LOWER() function

$query = $this->db->query("SELECT * FROM enq_capture WHERE enq_date >= '{$from1}' AND enq_date <= '{$to1}' AND (LOWER(company_name) LIKE '%{$qLower}%' OR LOWER(c_person) LIKE '%{$qLower}%')");
return $query->result();


问:
Passing complex type as parameter of action method. MVC
I have a problem with passing data to action method. I created action link in my view in the way shown below:

```<code>@model ComplexModel

...

<a href=@Url.Action( "ComplexAction", "ComplexController", new { complex= @Model, str = "string" } )
class="ui-btn">!!!Change all</a>
</code>```

And action method with to get all passed parameters:

```<code>public ActionResult ComplexAction( ComplexModeloAufgabeViewModel complex, string str )
{
    return View();
}
</code>```

String is passed correctly, but complex model is allways null. What is happening here?

答:
You need to post complex types with a form:

```<code>using (Html.BeginForm("ComplexAction", "ComplexController")
{
    // form fields go here

    <input type="submit" value="save" />
}
</code>```

This will post your complex type as defined by your ViewModel @model ComplexViewModel at the top of your View.

Your action will then read the ViewModel as follows:

```<code>public ActionResult ComplexAction(ComplexViewModel model)
{
    // do stuff with the form values here
}
</code>```

Body:
I have a problem with passing data to action method. I created action link in my view in the way shown below:

@model ComplexModel

...

!!!Change all

And action method with to get all passed parameters:

public ActionResult ComplexAction( ComplexModeloAufgabeViewModel complex, string str )
{
    return View();
}

String is passed correctly, but complex model is allways null. What is happening here?

Body:
You need to post complex types with a form:

using (Html.BeginForm("ComplexAction", "ComplexController")
{
    // form fields go here

    <input type="submit" value="save" />
}

This will post your complex type as defined by your ViewModel @model ComplexViewModel at the top of your View.

Your action will then read the ViewModel as follows:

public ActionResult ComplexAction(ComplexViewModel model)
{
    // do stuff with the form values here
}


答:
This should do the trick :

```<code>sum( 1 for k in dic.keys() if k not in ['foo', 'bar', 'baz'])
</code>```

It avoid to use get just to check if the key exist

NB : You can also use the length of sets as follow :

```<code>L = set(dic.keys())
L2 = set(['foo', 'bar', 'baz'])
print(len(L2) - len(L & L2))
</code>```

Title: Count number of times the get method in a dict returns the second option

Body:
This should do the trick :

sum( 1 for k in dic.keys() if k not in ['foo', 'bar', 'baz'])

It avoid to use get just to check if the key exist

NB : You can also use the length of sets as follow :

L = set(dic.keys())
L2 = set(['foo', 'bar', 'baz'])
print(len(L2) - len(L & L2))


问:
how to send device farm test(espresso) report in mail from jenkins
I have configured jenkins to send mail to specific people for every build. I want to send test report along with text. How to do that? If you can help.</p>

答:
```<code>emailext subject: "FAILED: Job '\${env.JOB_NAME} [\${env.BUILD_NUMBER}]'",
                                                                   mimeType: "text/html",
                                                                   body: \"""Job '\${env.JOB_NAME} - Build # [\${env.BUILD_NUMBER}]' - FAILED:</p>
                                                                        <p>Check console output at "<a href='\${env.BUILD_URL}'>\${env.JOB_NAME} [\${env.BUILD_NUMBER}]</a>"</p>
                                                                        <p>Check test results at "<a href='\${env.BUILD_URL}cucumber-html-reports/overview-features.html'>Cucumber reports</a>"</p>\""",
                                                                   to:'user1@gmail.com,user2@gmail.com'
</code>```

if you use a pipeline job here is an example

Body:
emailext subject: "FAILED: Job '\${env.JOB_NAME} [\${env.BUILD_NUMBER}]'",
                                                                   mimeType: "text/html",
                                                                   body: \"""Job '\${env.JOB_NAME} - Build # [\${env.BUILD_NUMBER}]' - FAILED:</p>
                                                                        <p>Check console output at &QUOT;<a href='\${env.BUILD_URL}'>\${env.JOB_NAME} [\${env.BUILD_NUMBER}]</a>&QUOT;</p>
                                                                        <p>Check test results at &QUOT;<a href='\${env.BUILD_URL}cucumber-html-reports/overview-features.html'>Cucumber reports</a>&QUOT;</p>\""",
                                                                   to:'user1@gmail.com,user2@gmail.com'

if you use a pipeline job here is an example


问:
Regular expression for decimals
Hi Experts,
                   I have a requirement where I think regular expressions might help reducing a lot of if statements and conditions in my code.
My requirement is something like this
I have a quantity field that is displayed in the UI( JavaScript) which has a control factor (based on the quantity field's Unit of Measurement) send from the backend .

Example my Quantity = "126.768"
The control factor D = "2" (which means the number of display positions after the decimal point is 2) .

Now I need a regex to find the following

Regex1 should check whether the quantity is having any decimal points at all. If so then it should check whether the value after decimal points are not just zeros (ex sometimes quantity comes without getting formatted with the full length of decimal points 145.000, which in our case should be displayed as 145 in the UI and the control factor D doesn't need to be considered). Also RegEx should consider quantity values like ".590" ".001" etc.

Since I am new to RegEx I am struggling to come up with an expression

I managed to make a very basic RegEx that just check for the "." within the quantity and all the values after the "."
RegEx = /[.]\d*/g

If RegEx1 returns a positive result . Then Regex2 should now check for the value  D. It should adjust the decimal points based on D. For example if D = 3 and quantity = 345.26 then the output of regex2 should give 345.260 and similarly is D = 1 then quantity should be 345.3 ( donno whether rounding is possible using RegEx, a solution without rounding is also fine).

Regards,
Bince

答:
You shouldn't need for any check or regex,
there is a Number.prototype.toFixed method that will help you to adjust decimals.

It basically rounds a number to the nearest decimal point and returns a string. If you're working with strings, make sure you cast it before (using Number statically)

console.log(17.1234.toFixed(2)); // round it down
console.log(17.1264.toFixed(2)); // round it up
console.log(17..toFixed(2)); // Integer
console.log(Number("126.768").toFixed(2)); // from string casting```

Title: Regular expression for decimals


问:
What other data structures are available in the C++ STL?
I'm already aware of the following:

arrays

bitsets

hash maps and sets

regular maps and sets

iterators

lists

pairs

tuples

queues, deques, and priority queues

stacks

valarrays

vectors

Is there any other type of data structure available in the C++ library. What I'm specifically looking for is graphs, but I'd also like to know what else is there.

Also, I'd like to know if there are any external libraries I can link with my projects to implement a graph.

答:
The STL is divided into three parts:

Containers

Iterators

Algorithms

You have obviously found the containers part and you have probably used the iterators associated with the containers. But there is even more to the iterators than you have found.

The algorithms sections is linked to the containers via iterators. But also contains the parts handle functors and associated binders.

My favortie site for this is:  http://www.sgi.com/tech/stl/table_of_contents.html

In addition to the standard libraries you should have a look at the boost libraries:

see also: Boost Library


问:
How to use jsx-control-statements in reactjs?
Im using jsx-control-statements in react app to add basic control statements. I've installed the same using npm and updated the .babelrc file as below

```<code>{
  "presets": ["react"],
  "plugins": ["jsx-control-statements"]
}
</code>```

and I've the below jsx code

```<code><IF condition={ selectedID !== null }>
 {this.renderData()}
</IF>
</code>```

below is the function to initiate the selectID, I want to execute the renderData() only if the value not equal to null

```<code>getInitialState() {
    return {
        selectedID: null
    }
},
</code>```

As of now Im getting a console error saying "Uncaught ReferenceError: IF is not defined" and the app is not loading. Can anyone tell me anything wrong here. Need help.

答:
Bit late but I just came across this while googling - you want to be using If instead of IF.

I suppose not using it at all works too :|.

Body:
Im using jsx-control-statements in react app to add basic control statements. I've installed the same using npm and updated the .babelrc file as below

{
  "presets": ["react"],
  "plugins": ["jsx-control-statements"]
}

and I've the below jsx code

<IF condition={ selectedID !== null }>
 {this.renderData()}
</IF>

below is the function to initiate the selectID, I want to execute the renderData() only if the value not equal to null

getInitialState() {
    return {
        selectedID: null
    }
},

As of now Im getting a console error saying "Uncaught ReferenceError: IF is not defined" and the app is not loading. Can anyone tell me anything wrong here. Need help.


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
use .classname only
instead of div.classname</p>

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image


问:
IIS is trying to access the wrong web.config
So first a bit of background: I rechecked out my SVN repository to a new location and tried to run the application from there. And now Visual Studio is having problems launching my MVC application using Local IIS Web server.
I am currently getting this error:

The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       Unknown
Handler    Not yet determined
Error Code     0x80070003
Config Error       Cannot read configuration file
Config File    \?\C:\RND\app\web.config
Requested URL      https: //localhost:44304/app
Physical Path

Logon Method       Not yet determined
Logon User     Not yet determined
Request Tracing Dir

And the problem is that the config file does not exist at c:\RND\app\web.config it is now located at c:\RND\appTest\web.config.

Is there a way I can update this in Visual Studio?

It is as if it has saved the old path somewhere and not automatically updating it.

答:
I fix it by removing a file named "applicationhost.config" stored in the .vs folder at the same level of .sln file.
This file contains all the info about solution, by deleting it visual studio needs to recreate it with the default value.</p>


问:
Android dotted underline is staying in middle of textview
I want to show a dotted underline below the textview, following are my codes

```<code><TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />
</code>```

dashed_line.xml

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

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>
</code>```

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

```<code>android:drawableBottom="@drawable/dashed_line"
</code>```

答:
Use following code to add dotted line below textview:
dash.xml(drawable xml)

```<code><item
    android:left="-5dp"
    android:right="-5dp"
    android:top="-5dp">
    <shape
        android:shape="rectangle">

        <solid android:color="#ffffff" />

        <stroke
            android:width="1dp"
            android:dashGap="5dp"
            android:dashWidth="5dp"
            android:color="@android:color/black" />
    </shape>
</item>
</layer-list>
</code>```

and in your textview xml :

```<code> <TextView
    android:id="@+id/segment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dash"
    android:gravity="left"
    android:text="First segment"
    android:textSize="12sp"
    android:layout_centerInParent="true"/>
</code>```

Body:
I want to show a dotted underline below the textview, following are my codes

<TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />

dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

android:drawableBottom="@drawable/dashed_line"

Body:
Use following code to add dotted line below textview:
dash.xml(drawable xml)

<item
    android:left="-5dp"
    android:right="-5dp"
    android:top="-5dp">
    <shape
        android:shape="rectangle">

        <solid android:color="#ffffff" />

        <stroke
            android:width="1dp"
            android:dashGap="5dp"
            android:dashWidth="5dp"
            android:color="@android:color/black" />
    </shape>
</item>
</layer-list>

and in your textview xml :

 <TextView
    android:id="@+id/segment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dash"
    android:gravity="left"
    android:text="First segment"
    android:textSize="12sp"
    android:layout_centerInParent="true"/>


问:
Is it possible to change the amount from authorize to capture in ActiveMerchant?
I'm doing a function that authorize first the user's credit card information. From that I can get a response and able to save the transaction_id or authorization key w/c can be use to capture the money from Credit Card.

But I need to do it separate way, just to authorize the credit card info first.
Since, authorizing the card requires the initial amount like for ex:

```<code>credit_card = ActiveMerchant::Billing::CreditCard.new(
 :number     => '4111111111111111',
 :month      => '8',
 :year       => '2009',
 :first_name => 'Tobias',
 :last_name  => 'Luetke',
 :verification_value  => '123'
)

# initial amount - 1000
response = gateway.authorize(1000, credit_card)
</code>```

My BIG question now is that, is it possible to use the #capture:

with different amount, now 2000

gateway.capture(2000, response.authorization)

答:
Yeah I think it is possible since both capture and authorize are standalone server calls,

Authorization -
  You request an authorization when a customer makes a purchase. An authorization, provided by the customer’s card issuing bank, confirms the cardholder’s ability to pay, ensuring that the customer's credit card account is in good standing with sufficient funds to complete the purchase.

Capture -
  After providing a service/product to the customer, you ‘capture’ the relevant information from the authorization and submit it in a capture/settlement request that your processor uses to initiate a funds transfer between the customer's credit card account and your checking account.

Source

So by definition it should be possible, but you would not know if the user will be able to pay the amount you intend to capture(if the amount is higher than the one in authorize call).

Body:
I'm doing a function that authorize first the user's credit card information. From that I can get a response and able to save the transaction_id or authorization key w/c can be use to capture the money from Credit Card.

But I need to do it separate way, just to authorize the credit card info first.
Since, authorizing the card requires the initial amount like for ex:

credit_card = ActiveMerchant::Billing::CreditCard.new(
 :number     => '4111111111111111',
 :month      => '8',
 :year       => '2009',
 :first_name => 'Tobias',
 :last_name  => 'Luetke',
 :verification_value  => '123'
)

# initial amount - 1000
response = gateway.authorize(1000, credit_card)

My BIG question now is that, is it possible to use the #capture:

with different amount, now 2000

gateway.capture(2000, response.authorization)


问:
Android Instant-release build not includes base APK
We are preparing to publish instant app apks to play store via "Instant app development" channel for testing purpose.
When we sign instant app (using same keystore used for Installed App), only geting one feature module apk inside zip folder(instant-release.zip) which giving error while uploading to Play Store by complaining "Your Instant App APKs should contain at least one base APK"

Anyway we able to see the expected structure under instant-debug version

Structure deference between debug and release version as below

instant-debug.zip

hello-debug.apk

base-debug.apk

bye-debug.apk

instant-release.zip

hello-release.apk

And not sure whether we making any mistake on gradle configuration. It will very helpful if anyone can advise on this ?

答:
There are some known issues signing Instant Apps using the built-in menus in Android Studio 3.0 Preview. If you set up signingConfigs in your build.gradle files then run gradle assembleRelease from command line or from the gradle menu in Studio (one on the right side) it should work.

signingConfigs should be setup in each of your feature modules to ensure all feature APKs are signed.

Here's some info on setting up signingConfigs:

https://developer.android.com/studio/publish/