问:
PDO Exception SQLSTATE[HY000] [2002] Connection timed out with Elastic Beanstalk and RDS on Yii2
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

```<code>'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=myConnection_string:3306;myDB',
            'username' => 'myUsername',
            'password' => 'myPassword',
            'charset' => 'utf8',
        ],
</code>```

What is wrong? Thanks.

答:
I resolved the issue by changing to "all traffic" on EC2>Network&Security>Security Groups>Edit inbound rules.

Also I setup the variables on AWS and changed the script to:

```<code>'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=',
        'dsn' => 'mysql:host='.$_SERVER['RDS_HOSTNAME'].':'.$_SERVER['RDS_PORT'].';dbname='.$_SERVER['RDS_DB_NAME'],
        'username' => $_SERVER['RDS_USERNAME'],
        'password' => $_SERVER['RDS_PASSWORD'],
        'charset' => 'utf8',
    ],
</code>```

This answer help me a lot: How to connect to an RDS database from Yii2?

Body:
I have deployed a Yii2 based app onto AWS Elastic Beanstalk, also I have created the RDS instance with a database (it already has tables) on Elastic Beanstalk. All the files are uploaded correctly to the AWS instance.

The file /common/config/main-local.php has:

'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=myConnection_string:3306;myDB',
            'username' => 'myUsername',
            'password' => 'myPassword',
            'charset' => 'utf8',
        ],

What is wrong? Thanks.

Body:
I resolved the issue by changing to "all traffic" on EC2>Network&Security>Security Groups>Edit inbound rules.

Also I setup the variables on AWS and changed the script to:

'components' => [
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=',
        'dsn' => 'mysql:host='.$_SERVER['RDS_HOSTNAME'].':'.$_SERVER['RDS_PORT'].';dbname='.$_SERVER['RDS_DB_NAME'],
        'username' => $_SERVER['RDS_USERNAME'],
        'password' => $_SERVER['RDS_PASSWORD'],
        'charset' => 'utf8',
    ],

This answer help me a lot: How to connect to an RDS database from Yii2?


来源: stackexchange

问:
Flatten curved surface
I am trying to compute a panoramic projection for dental imaging purpose.

I have a rectangle surface "curved" in one direction by a piecewise function. If we look at it from the top, it looks like a regular piecewise function.

The "piecewise linear function" is just defined by a set of 3D points.
All the points are in the same plane. The plane where all the 3D points sit is orthogonal to the curved surface

(see the green line in the top-left window)

I am looking for the proper way to "flatten" it. (non linear transform)

The flat surface should have the same "length" as the curved one. (it is not a classic orthogonal projection)

Ultimately, I will use the "flat surface" as a canvas to display the information of interest.

(Bottom window)

Best,

答:
I see it like this:

I would:

take 3 consequent points P0,P1,P2 from your curve

compute U0,V0,U1,V1

```<code>U0 = P1-P0
U1 = P2-P1
V0 = cross(U0,(0,0,1)); V0=half_height/|V0|
V1 = cross(U1,(0,0,1)); V1=half_height/|V1|
</code>```

so A,B is just P0 +/- V0 and C,D is P1 +/- V1. In the cross product Use any vector non parallel with U0,U1 I chose (0,0,1) but in case it si parallel chose any other...

make the ABCD a recangle

So compute A'B'C'D' for example

```<code>A'.x = B'.x = index_of(P0) * sizex
C'.x = D'.x = index_of(P0) * sizex + sizex
A'.y = D'.y = sizey
B'.y = C'.y = 0
</code>```

Where sizex,sizey is the size of rectangle segment. You can also use |U0|,|V0| but in that case the start x will be integrated curve length.

compute transformation between ABCD and A'B'C'D'

so for each pixel P inside ABCD compute (x,y) inside A'B'C'D'. Thex` is easy:

```<code>x = A'.x + dot(P-P0,U0)/|P-P0|
</code>```

y is tricky and need some tweaking to suite your needs (so the result is smooth to your liking). For starters try simple approach (will lead to seams between segments)

```<code>y = (A'.y+B'.y)/2 + dot(P-P),V0)/|P-P0|
</code>```

Now just copy the pixel at position P into your target image at position (x,y)

To make this more smooth you can make V interpolated between V0,V1 dependent on the dot(P-P0,U0)/(|P-P0|*|U0|) so it will change seamlessly.

```<code>t = dot(P-P0,U0)/(|P-P0|*|U0|)
V = V0 + (V1-V0)*t
y = (A'.y+B'.y)/2 + dot(P-P),V)/|P-P0|
</code>```

If you need help with determining if point is inside then pixel P is inside if

```<code>dot(P-P0,U0)/(|P-P0|*U0) = <0.0,1.0>
</code>```

loop #1 for all segments of the curve

step by single sample point of curve (not by 3 ...)

ContentLicense: CC BY-SA 3.0

Title: Flatten curved surface

Body:
I see it like this:

I would:

take 3 consequent points P0,P1,P2 from your curve

compute U0,V0,U1,V1

U0 = P1-P0
U1 = P2-P1
V0 = cross(U0,(0,0,1)); V0=half_height/|V0|
V1 = cross(U1,(0,0,1)); V1=half_height/|V1|

so A,B is just P0 +/- V0 and C,D is P1 +/- V1. In the cross product Use any vector non parallel with U0,U1 I chose (0,0,1) but in case it si parallel chose any other...

make the ABCD a recangle

So compute A'B'C'D' for example

A'.x = B'.x = index_of(P0) * sizex
C'.x = D'.x = index_of(P0) * sizex + sizex
A'.y = D'.y = sizey
B'.y = C'.y = 0

Where sizex,sizey is the size of rectangle segment. You can also use |U0|,|V0| but in that case the start x will be integrated curve length.

compute transformation between ABCD and A'B'C'D'

so for each pixel P inside ABCD compute (x,y) inside A'B'C'D'. Thex` is easy:

x = A'.x + dot(P-P0,U0)/|P-P0|

y is tricky and need some tweaking to suite your needs (so the result is smooth to your liking). For starters try simple approach (will lead to seams between segments)

y = (A'.y+B'.y)/2 + dot(P-P),V0)/|P-P0|

Now just copy the pixel at position P into your target image at position (x,y)

To make this more smooth you can make V interpolated between V0,V1 dependent on the dot(P-P0,U0)/(|P-P0|*|U0|) so it will change seamlessly.

t = dot(P-P0,U0)/(|P-P0|*|U0|)
V = V0 + (V1-V0)*t
y = (A'.y+B'.y)/2 + dot(P-P),V)/|P-P0|

If you need help with determining if point is inside then pixel P is inside if

dot(P-P0,U0)/(|P-P0|*U0) = <0.0,1.0>

loop #1 for all segments of the curve

step by single sample point of curve (not by 3 ...)


问:
While loop inside while loop returns only first row
I'm trying to make array filled with different objects. I have set of pages and set of questions. Pages are groups and questions belongs to them.

I want to query first pages, then find out how many questions are within. After that create object for each question and append them into specific pages.

```<code>// first get pages so we get grouping and order
$getPages = $conn->prepare("SELECT * FROM pages WHERE event_id = :event_id ORDER BY page_order ASC");
$getPages->bindParam(":event_id", $_SESSION['event_id']);
$getPages->execute();
$pageCount = $getPages->rowCount();
$pages = array();

// get pages
while ($row = $getPages->fetch()) {
    $page = array();
    $page['id'] = $row['id'];
    $page['order'] = $row['page_order'];

    // query for that page
    $stmt = $conn->prepare("SELECT * FROM questions WHERE page_id = :page_id");
    $stmt->bindParam(":page_id", $page['id']);
    $stmt->execute();
    while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];
        // push question into questions
        $page['questions'] = $question;
    }

    // push page into pages
    $pages[] = $page;
}

//print pages
echo json_encode($pages);
</code>```

But sadly it only returns one row for each page...

答:
It's because your question overwrites each time. Change your code like below</p>

```<code><?php
$page['questions'] = array();
 while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];

        // push question into questions
        $page['questions'][] = $question;
    }
</code>```

Body:
I'm trying to make array filled with different objects. I have set of pages and set of questions. Pages are groups and questions belongs to them.

I want to query first pages, then find out how many questions are within. After that create object for each question and append them into specific pages.

// first get pages so we get grouping and order
$getPages = $conn->prepare("SELECT * FROM pages WHERE event_id = :event_id ORDER BY page_order ASC");
$getPages->bindParam(":event_id", $_SESSION['event_id']);
$getPages->execute();
$pageCount = $getPages->rowCount();
$pages = array();

// get pages
while ($row = $getPages->fetch()) {
    $page = array();
    $page['id'] = $row['id'];
    $page['order'] = $row['page_order'];

    // query for that page
    $stmt = $conn->prepare("SELECT * FROM questions WHERE page_id = :page_id");
    $stmt->bindParam(":page_id", $page['id']);
    $stmt->execute();
    while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];
        // push question into questions
        $page['questions'] = $question;
    }

    // push page into pages
    $pages[] = $page;
}

//print pages
echo json_encode($pages);

But sadly it only returns one row for each page...

Body:
It's because your question overwrites each time. Change your code like below

<?php
$page['questions'] = array();
 while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];

        // push question into questions
        $page['questions'][] = $question;
    }


问:
Average a certain column value in MySQL
I have this table structure:

```<code>id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45
</code>```

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

```<code>code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45
</code>```

答:
```<code>SELECT CODE,AVG(rating) FROM
(
SELECT CASE WHEN code >= 300 THEN '300+' ELSE CODE END AS CODE, rating FROM table
)Z
GROUP BY code;
</code>```

You can try the code above.

Title: Average a certain column value in MySQL

Body:
I have this table structure:

id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45

Body:
SELECT CODE,AVG(rating) FROM
(
SELECT CASE WHEN code >= 300 THEN '300+' ELSE CODE END AS CODE, rating FROM table
)Z
GROUP BY code;

You can try the code above.

ContentLicense: CC BY-SA 4.0


问:
How to use canvas in Angular
The common approaching to use canvas in javascript is like :

```<code>var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
</code>```

but in Angular2 I cannot get the HTMLCanvasElement object, the var "canvas" only get the HTMLElement in Angular2. So how to use canvas in Angular2?
And furthermore, how to use the third-party javascript in Angular2 with the language TypeScript?

答:
You can accomplish this by using @ViewChild

In your class do the following.

```<code>import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
   name: 'my-component',
   // notice the variable name myCanvas
   template: `<canvas #myCanvas></canvas>`
})
export class myComponent implements AfterViewInit {
  // its important myCanvas matches the variable name in the template
  @ViewChild('myCanvas')
  canvas: ElementRef<HTMLCanvasElement>;

  context: CanvasRenderingContext2D;

  ngAfterViewInit(): void {
    this.context = this.canvas.nativeElement.getContext('2d');
  }
}
</code>```

Try to stay away from using document as much as you can, as it could bite you on the long run. Also using @ViewChild has an advantage over querying the DOM, once the application is compiled. Angular already knows ahead of time which element it needs to do the modifications on, rather than having to find it in the DOM.

For a full example check out this demo

Update

For angular 8 you need to use ViewChild like this.

```<code>@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;
</code>```

See How should I use the new static option for @ViewChild in Angular 8? for more information

Title: How to use canvas in Angular

Body:
The common approaching to use canvas in javascript is like :

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

but in Angular2 I cannot get the HTMLCanvasElement object, the var "canvas" only get the HTMLElement in Angular2. So how to use canvas in Angular2?
And furthermore, how to use the third-party javascript in Angular2 with the language TypeScript?

Body:
You can accomplish this by using @ViewChild

In your class do the following.

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
   name: 'my-component',
   // notice the variable name myCanvas
   template: `<canvas #myCanvas></canvas>`
})
export class myComponent implements AfterViewInit {
  // its important myCanvas matches the variable name in the template
  @ViewChild('myCanvas')
  canvas: ElementRef<HTMLCanvasElement>;

  context: CanvasRenderingContext2D;

  ngAfterViewInit(): void {
    this.context = this.canvas.nativeElement.getContext('2d');
  }
}

Try to stay away from using document as much as you can, as it could bite you on the long run. Also using @ViewChild has an advantage over querying the DOM, once the application is compiled. Angular already knows ahead of time which element it needs to do the modifications on, rather than having to find it in the DOM.

For a full example check out this demo

Update

For angular 8 you need to use ViewChild like this.

@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;

See How should I use the new static option for @ViewChild in Angular 8? for more information


问:
I have a Singleton class, but returns two. Do I need two lok obj?
```<code>public class Manager {
    private static Manager _one;
    private static Manager _two;
    private static object Obj_Lock_one = new object();
    private static object Obj_Lock_two = new object();//Do I need Obj_Lock_two here ?

    public static Manager GetOne ()
    {
            if (_one == null)
            {
                lock (Obj_Lock_one)
                {
                    if (_one == null)
                    {
                        _one = new Manager();
                    }
                }
            }

            return _one;
    }
    public static Manager GetTwo ()
    {
            if (_two == null)
            {
                lock (Obj_Lock_two) //Do I need Obj_Lock_two here ?
                {
                    if (_two == null)
                    {
                        _two = new Manager();
                    }
                }
            }

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

Do I need a second obj to lock? In GetTwo method should I use "lock(Obj_Lock_one)" or "lock(Obj_Lock_two)"

If I only use one obj to lock, may just block one thred, I think...

SO what is the correct way?

答:
Do I need a second obj to lock?

Using a second lock object here will slightly improve performance, if two thread simultaneously call GetOne() and GetTwo() for the first time at the same time. In other words: You probably won't be able to measure a difference.

SO what is the correct way?

Don't reinvent the wheel. Scrap your code and use Lazy initialization with Lazy<T> instead, which is thread-safe and automatically takes care of all those thread-sync issues:

```<code>public sealed class Manager
{
    private static readonly Lazy<Manager> lazyOne = new Lazy<Manager>(() => new Manager());
    private static readonly Lazy<Manager> lazyTwo = new Lazy<Manager>(() => new Manager());

    public static Manager GetOne() { return lazyOne.Value; }
    public static Manager GetTwo() { return lazyTwo.Value; }
}
</code>```

Body:
public class Manager {
    private static Manager _one;
    private static Manager _two;
    private static object Obj_Lock_one = new object();
    private static object Obj_Lock_two = new object();//Do I need Obj_Lock_two here ?

    public static Manager GetOne ()
    {
            if (_one == null)
            {
                lock (Obj_Lock_one)
                {
                    if (_one == null)
                    {
                        _one = new Manager();
                    }
                }
            }

            return _one;
    }
    public static Manager GetTwo ()
    {
            if (_two == null)
            {
                lock (Obj_Lock_two) //Do I need Obj_Lock_two here ?
                {
                    if (_two == null)
                    {
                        _two = new Manager();
                    }
                }
            }

            return _two;
    }
}

Do I need a second obj to lock? In GetTwo method should I use "lock(Obj_Lock_one)" or "lock(Obj_Lock_two)"

If I only use one obj to lock, may just block one thred, I think...

SO what is the correct way?

Body:
Do I need a second obj to lock?

Using a second lock object here will slightly improve performance, if two thread simultaneously call GetOne() and GetTwo() for the first time at the same time. In other words: You probably won't be able to measure a difference.

SO what is the correct way?

Don't reinvent the wheel. Scrap your code and use Lazy initialization with Lazy<T> instead, which is thread-safe and automatically takes care of all those thread-sync issues:

public sealed class Manager
{
    private static readonly Lazy<Manager> lazyOne = new Lazy<Manager>(() => new Manager());
    private static readonly Lazy<Manager> lazyTwo = new Lazy<Manager>(() => new Manager());

    public static Manager GetOne() { return lazyOne.Value; }
    public static Manager GetTwo() { return lazyTwo.Value; }
}


答:
You could use a case expression to group together all the codes greater than 300:

```<code>SELECT   CASE WHEN code >= 300 THEN '300+'
            ELSE CAST(code AS CHAR)
         END,
         AVG(rating)
FROM     table
GROUP BY CASE WHEN code >= 300 THEN '300+'
            ELSE CAST(code AS CHAR)
         END
</code>```

Title: Average a certain column value in MySQL

Body:
You could use a case expression to group together all the codes greater than 300:

SELECT   CASE WHEN code >= 300 THEN '300+'
            ELSE CAST(code AS CHAR)
         END,
         AVG(rating)
FROM     table
GROUP BY CASE WHEN code >= 300 THEN '300+'
            ELSE CAST(code AS CHAR)
         END


问:
Trust My device
How do I go about the following scenario: The first time user logs in from a device MFA is prompted. During MFA if user checks "trust this device" box further logins on the device will need only password.

I am using custom policies.

答: We do something similar with the IP address, although that may not help if you have a shared IP, you might be able to store a cookie as part of login and then retrieve it using javascript and then enter it into a claim on the login page . </p>

Title: Trust My device


问:
Create Excel with string values
I would like to create an excel with string rows in it.Now by default the excel creates numeric rows and the value i want to set is 00000111.the code i am using is the following :

```<code>Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet1")

oSheet.Range("A1").Value = "0000111"
oSheet.Range("B1").Value ="Name"
oSheet.Range("C1").Value = "Name2"
oSheet.Range("D1").Value = "Phone"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()
</code>```

Kind Regards ,
Ifigenia

答:
Another way

Change

```<code>oSheet.Range("A1").Value = "0000111"
</code>```

to

```<code>oSheet.Range("A1").Value = "'0000111" '<~~ Notice the ' before the number
</code>```

Title: Create Excel with string values

Body:
I would like to create an excel with string rows in it.Now by default the excel creates numeric rows and the value i want to set is 00000111.the code i am using is the following :

Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object

oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add

oSheet = oBook.Worksheets("Sheet1")

oSheet.Range("A1").Value = "0000111"
oSheet.Range("B1").Value ="Name"
oSheet.Range("C1").Value = "Name2"
oSheet.Range("D1").Value = "Phone"

oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()

Kind Regards ,
Ifigenia

Body:
Another way

Change

oSheet.Range("A1").Value = "0000111"

to

oSheet.Range("A1").Value = "'0000111" '<~~ Notice the ' before the number


问:
Find which element of the stream does not match the given predicate in allmatch
I want to find out which element is failing the predicate in case of allmatch.

```<code>List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);
</code>```

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

```<code>numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });
</code>```

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

答:
Something need to clarify: a boolean is not a Predicate. boolean is a noun, but Predicate is a predicate. so your Predicate is more like this:

```<code>IntPredicate isEven = n -> n % 2 == 0;

boolean numbersAreEven = numbers.stream().allMatch(isEven);
</code>```

IF you need to inverse a Predicate you can using Predicate#negate, for example:

```<code>IntPredicate isOdd = isEven.negate();

boolean numbersAreOdd = numbers.stream().allMatch(isOdd);
</code>```

IF you want to list all odd numbers, you should use Stream#filter, for example:

```<code>numbers.stream().filter(isOdd).forEach(System.out::println);
</code>```

IF you want to find the first odd number, you can use Stream#findFirst, for example:

```<code>Number odd = numbers.stream().filter(isOdd).findFirst().orElse(null);
</code>```

IF you want to find the first odd number regardless of the elements order, you can use Stream#findAny, for example:

```<code>Number odd = numbers.stream().filter(isOdd).findAny().orElse(null);
</code>```

Note: both Stream#findAny and Stream#findFirst are short-circuiting terminal operation, which means it will exit once any intermediate operation is satisfied.

Body:
I want to find out which element is failing the predicate in case of allmatch.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

Body:
Something need to clarify: a boolean is not a Predicate. boolean is a noun, but Predicate is a predicate. so your Predicate is more like this:

IntPredicate isEven = n -> n % 2 == 0;

boolean numbersAreEven = numbers.stream().allMatch(isEven);

IF you need to inverse a Predicate you can using Predicate#negate, for example:

IntPredicate isOdd = isEven.negate();

boolean numbersAreOdd = numbers.stream().allMatch(isOdd);

IF you want to list all odd numbers, you should use Stream#filter, for example:

numbers.stream().filter(isOdd).forEach(System.out::println);

IF you want to find the first odd number, you can use Stream#findFirst, for example:

Number odd = numbers.stream().filter(isOdd).findFirst().orElse(null);

IF you want to find the first odd number regardless of the elements order, you can use Stream#findAny, for example:

Number odd = numbers.stream().filter(isOdd).findAny().orElse(null);

Note: both Stream#findAny and Stream#findFirst are short-circuiting terminal operation, which means it will exit once any intermediate operation is satisfied.


问:
Xib to ViewController
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

Edit:

CallHistoryTableViewCell.h

```<code>@interface CallHistoryTableViewCell : UITableViewCell
    @property(nonatomic, strong) IBOutlet UILabel *contactName;
    @property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end
</code>```

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

```<code>@interface CallHistoryVC : UIViewController
@end
</code>```

CallHistoryVC.m

```<code>#import "CallHistoryVC.h"
#import "CallHistoryTableViewCell.h"

@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}
@property (nonatomic, strong) NSMutableArray<RecentCall> *sortedEventArray;
@property (weak, nonatomic) IBOutlet UITableView *tView;

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//---add one contact---//
[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}
</code>```

Everything works fine but in didSelectRowAtIndexPath indexPath is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

答:
implement the didSelectRowAtIndexPath as below

```<code>      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
            {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    StoryViewController *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"StoryViewController"];
    [self presentViewController:storyViewController animated:YES completion:nil]; //  present it
     //[self.navigationController pushViewController:storyViewController animated:YES];// or push it
            }
</code>```

Set the cell id name as CallHistoryTableViewCell in your table view cell from your xib file.
Now in your viewDidLoad register your custom tableView cell

```<code>[self.tableView registerNib:@"CallHistoryTableViewCell" forCellReuseIdentifier:@"CallHistoryTableViewCell"];
</code>```

and place the following code in your cellForRowAtIndexPath

```<code>CallHistoryTableViewCell *cell = (CallHistoryTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CallHistoryTableViewCell"];
return cell;
</code>```

Title: Xib to ViewController

Body:
I have TableViewCell.xib file where in each cell there can be summary of data like name, contact etc. Now if I touch the cell it will go to another ViewController where there will be details of that cell's data.(it does not matter what this ViewController shows). I want to go to another ViewController from this xib file's cell touch. how can I do that.

Edit:

CallHistoryTableViewCell.h

@interface CallHistoryTableViewCell : UITableViewCell
    @property(nonatomic, strong) IBOutlet UILabel *contactName;
    @property(nonatomic, strong) IBOutlet UILabel *contactNumber;
@end

this class has CallHistoryTableViewCell.xib file.

CallHistoryVC.h

@interface CallHistoryVC : UIViewController
@end

CallHistoryVC.m

#import "CallHistoryVC.h"
#import "CallHistoryTableViewCell.h"

@interface CallHistoryVC ()<UITableViewDelegate, UITableViewDataSource,CallingViewControllerDelegate> {
AppDelegate *appDelegate;

}
@property (nonatomic, strong) NSMutableArray<RecentCall> *sortedEventArray;
@property (weak, nonatomic) IBOutlet UITableView *tView;

- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//---add one contact---//
[self defaultViewSetting];
_tView.delegate = self;
_tView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 75;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _sortedEventArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CallHistoryTableViewCell";

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailsOfHistory *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"DetailsOfHistory"];
//[self presentViewController:storyViewController animated:YES completion:nil]; //  present it
[self.navigationController pushViewController:storyViewController animated:YES];// or push it

NSLog(@"%ld",(long)indexPath.row);
}

Everything works fine but in didSelectRowAtIndexPath indexPath is not showing that means touch not working. By click on the cell I want to go to another viewcontroller in stroyboard.

Body:
implement the didSelectRowAtIndexPath as below

      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
            {
UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    StoryViewController *storyViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"StoryViewController"];
    [self presentViewController:storyViewController animated:YES completion:nil]; //  present it
     //[self.navigationController pushViewController:storyViewController animated:YES];// or push it
            }

Set the cell id name as CallHistoryTableViewCell in your table view cell from your xib file.
Now in your viewDidLoad register your custom tableView cell

[self.tableView registerNib:@"CallHistoryTableViewCell" forCellReuseIdentifier:@"CallHistoryTableViewCell"];

and place the following code in your cellForRowAtIndexPath

CallHistoryTableViewCell *cell = (CallHistoryTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CallHistoryTableViewCell"];
return cell;


问:
It is possible to render a DOM in a div?
I am working with email services and the services gives me the body of the message in the following form

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.= w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=3D "http://www.w3.= org/1999/xhtml">

<head>
    <meta http-equiv=3D "Content-Type" content=3D "text/html; charset=3Dutf-8">
    <title>How's it going? </title>
    <style>
        @import url(https://fonts.googleapis.com/css?family=3DRoboto:300);
        /*Calling our web font*/
        /* Some resets and issue fixes */

        #outlook a {
            padding: 0;
        }
        body {
            width: 100% !important;
            -webkit-text;
            size-adjust: 100%;
            -ms-te xt-size-adjust: 100%;
            margin: 0;
            padding: 0;
        }
        =20 .ReadMsgBody {
            width: 100%;
        }
        .ExternalClass {
            width: 100%;
        }
        =20 .backgroundTable {
            margin: 0 auto;
            padding: 0;
            width: 100%;
            !important;
        }
         =20 table td {
            border-collapse: collapse;
        }
        .ExternalClass * {
            line-height: 115%;
        }
        =20=20
        /* End reset */

        =20
        /* These are our tablet/medium screen media queries */

        @media screen and (max-width: 630px) {
            =20
            /* Display block allows us to stack elements */

             =20 *[class=3D"mobile-column"] {
                display: block;
            }
            =20=20
            /* Some more stacking elements */

            *[class=3D"mob-column"] {
                float: none !important;
                width: 100% !im portant;
            }
            =20=20
            /* Hide stuff */

            *[class=3D"hide"] {
                display: none !important;
            }
            =20=20
            /* This sets elements to 100% width and fixes the height issues= too, a god send */

            *[class=3D"100p"] {
                width: 100% !important;
                height: auto !importan t;
            }
            =20=20
            /* For the 2x2 stack */

            =20 *[class=3D"condensed"] {
                padding-bottom: 40px !important;
                display : block;
            }
            =20
            /* Centers content on mobile */

            *[class=3D"center"] {
                text-align: center !important;
                width: 100% ! important;
                height: auto !important;
            }
            =20=20
            /* 100percent width section with 20px padding */

            *[class=3D"100pad"] {
                width: 100% !important;
                padding: 20px;
            }
            =20=20
            /* 100percent width section with 20px padding left & right */

            *[class=3D"100padleftright"] {
                width: 100% !important;
                padding: 0 20px 0 20px;
            }
            =20=20
            /* 100percent width section with 20px padding top & bottom */

            *[class=3D"100padtopbottom"] {
                width: 100% !important;
                padding: 20 px 0px 20px 0px;
            }
            =20=20=20
        }
    </style>
    <style type=3D "text/css">
    </style>
</head>

<body> =20
    <table>
        <tr>
            <td style=3D "padding: 0 10px;"> =20
                <div class=3D "mktEditable" id=3D "content" style=3D "font-family: Arial, = sans-serif; font-size:14px; line-height:20px; color:#2e2e2e; font-weight:no= rmal; ">
                    <p style=3D "font-size: 12px;"> </p>
                    <p> =20 Hey,
                        <br> Thanks for taking the time to evaluate amoCRM. Our mission is helping sales= teams accomplish more by giving them the proper place to manage their work= . I hope we can do that for you too. </p>
                    <p> I was told that you aren=E2=80=99t really enjoying the first days of your t= rial - just hit reply, and let me know about your main goal. I=E2=80=99ll c= onnect you with the right person to fine-tune amoCRM to fit your needs. </p=> Thank you and best regards,
                        <br> Egor Kovalchuk
                        <br> CEO, amoCRM </div>
            </td>
        </tr>
    </table> =20 <img src=3D "https://mandrillapp.com/track/open.php?u=3D30051581&id=3Dd8= bfb7221bf8403c8d63e2375a2dd6a4" height=3D "1" width=3D "1">
    <center>
        <br>
        <br>
        <br>
        <br>
        <br>
        <br>
        <table border=3D "0" cellpadding=3D "0" cellspacing=3D "0" width=3D "100%"=i d=3D "canspamBarWrapper" style=3D "background-color:#FFFFFF; border-top:1px = solid #E5E5E5;">
            <tr>
                <td align=3D "center" valign=3D "top" style=3D "padding-top:20px; = padding-bottom:20px;">
                    <table border=3D "0" cellpadding=3D "0" cellspacing=3D "0" id==3D "canspamBar">
                        <tr>
                            <td align=3D "center" valign=3D "top" style=3D "color:= #606060; font-family:Helvetica, Arial, sans-serif; font-size:11px; line-hei= ght:150%; padding-right:20px; padding-bottom:5px; padding-left:20px; text-a= lign:center;"> This email was sent to <a href=3D "mailto:vasily= ev.alexander@hotmail.com" target=3D "_blank" style=3D "color:#404040 !importa= nt;">vasilyev.alexander@hotmail.com</a>    <a href=3D "https://mandrillapp.com/track/click/= 30051581/mandrillapp.com?p=3DeyJzIjoiRVA5WWVBVkt3eVl4UEI2TmJfWkdNUU9UcVg0Ii= widiI6MSwicCI6IntcInVcIjozMDA1MTU4MSxcInZcIjoxLFwidXJsXCI6XCJodHRwOlxcXC9cX= FwvbWFuZHJpbGxhcHAuY29tXFxcL3RyYWNrXFxcL3Vuc3ViLnBocD91PTMwMDUxNTgxJmlkPWQ4= YmZiNzIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0Lmp6WlBnZVVWRWg1Y01nRTNLJTJCbFlqaDh= QbVE0JTNEJnI9aHR0cHMlM0ElMkYlMkZtYW5kcmlsbGFwcC5jb20lMkZ1bnN1YiUzRm1kX2VtYW= lsJTNEdmFzaWx5ZXYuYWxleGFuZGVyJTI1NDBob3RtYWlsLmNvbVwiLFwiaWRcIjpcImQ4YmZiN= zIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0XCIsXCJ1cmxfaWRzXCI6W1wiODdmOTIzZjE4Mjg2= ZmM5NzgwMGE1NzA3ZWEyMDJjM2EwNDUwMGZhNFwiXX0ifQ" style=3D "color:#404040 !imp= ortant;">unsubscribe from this list</a> </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <style type=3D "text/css">
            @media only screen and (max-width: 480px) {
                table[id=3D"canspamBar"] td {
                    font-size: 14px !important;
                }
                table[id=3D"canspamBar"] td a {
                    display: block !important;
                    margin- top: 10px !important;
                }
            }
        </style>
    </center>
</body>=20

</html>
</code>```

I need to render it as html under a div on my client page. Is there any possibility to do so

--edited for clarification, cant read this in a single line

答:
In javascript use document.getElementById("divid").innerHTML(response)

If you are using jquery you can load html on div using $("#div_id").html(response);
In this example i have not taken you html code since it is very big string i'm not able to use it in code here.

var response = '
This is Your Response
';

$("#email").html(response);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="email"></body></code>```

Body:
I am working with email services and the services gives me the body of the message in the following form

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.= w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv=3D "Content-Type" content=3D "text/html; charset=3Dutf-8">
    <title>How's it going? </title>

 =20

             =20

 =20 Hey,

 Thanks for taking the time to evaluate amoCRM. Our mission is helping sales= teams accomplish more by giving them the proper place to manage their work= . I hope we can do that for you too.

 I was told that you aren=E2=80=99t really enjoying the first days of your t= rial - just hit reply, and let me know about your main goal. I=E2=80=99ll c= onnect you with the right person to fine-tune amoCRM to fit your needs.
 Thank you and best regards,

 Egor Kovalchuk

 CEO, amoCRM

 =20

                             This email was sent to vasilyev.alexander@hotmail.com    <a href=3D "https://mandrillapp.com/track/click/= 30051581/mandrillapp.com?p=3DeyJzIjoiRVA5WWVBVkt3eVl4UEI2TmJfWkdNUU9UcVg0Ii= widiI6MSwicCI6IntcInVcIjozMDA1MTU4MSxcInZcIjoxLFwidXJsXCI6XCJodHRwOlxcXC9cX= FwvbWFuZHJpbGxhcHAuY29tXFxcL3RyYWNrXFxcL3Vuc3ViLnBocD91PTMwMDUxNTgxJmlkPWQ4= YmZiNzIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0Lmp6WlBnZVVWRWg1Y01nRTNLJTJCbFlqaDh= QbVE0JTNEJnI9aHR0cHMlM0ElMkYlMkZtYW5kcmlsbGFwcC5jb20lMkZ1bnN1YiUzRm1kX2VtYW= lsJTNEdmFzaWx5ZXYuYWxleGFuZGVyJTI1NDBob3RtYWlsLmNvbVwiLFwiaWRcIjpcImQ4YmZiN= zIyMWJmODQwM2M4ZDYzZTIzNzVhMmRkNmE0XCIsXCJ1cmxfaWRzXCI6W1wiODdmOTIzZjE4Mjg2= ZmM5NzgwMGE1NzA3ZWEyMDJjM2EwNDUwMGZhNFwiXX0ifQ" style=3D "color:#404040 !imp= ortant;">unsubscribe from this list

=20

I need to render it as html under a div on my client page. Is there any possibility to do so

--edited for clarification, cant read this in a single line

Body:
In javascript use document.getElementById("divid").innerHTML(response)

If you are using jquery you can load html on div using $("#div_id").html(response);
In this example i have not taken you html code since it is very big string i'm not able to use it in code here.

var response = '<html><body><h3>This is Your Response</h3></body></html>';

$("#email").html(response);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="email"></body>


问:
How do I clear all options in a dropdown box?
My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

```<code>document.getElementById("DropList").options.length=0;
</code>```

After searching, I've learned that it's the length=0 that it doesn't like.

I've tried ...options=null and var clear=0; ...length=clear with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

答:
This is a short way:

```<code>document.getElementById('mySelect').innerText = null;
</code>```

One line, no for, no JQuery, simple.

Body:
My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)

document.getElementById("DropList").options.length=0;

After searching, I've learned that it's the length=0 that it doesn't like.

I've tried ...options=null and var clear=0; ...length=clear with the same result.

I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.

Body:
This is a short way:

document.getElementById('mySelect').innerText = null;

One line, no for, no JQuery, simple.


答:
You can create an iframe, store your HTML in a JS variable and put it inside your iframe :</p>

```<code>var myHtml = '<html>...</html>';

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write(myHtml);
doc.close();
</code>```

Title: It is possible to render a DOM in a div?

Body:
You can create an iframe, store your HTML in a JS variable and put it inside your iframe :

var myHtml = '<html>...</html>';

var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write(myHtml);
doc.close();


问:
Converting site from .html to .php
my site has now become sufficiently large for me to think it's necessary to convert the pages to php pages to help me update it in the future. The problem is: my site has a number of links to it on various websites across the web. Eg these links point to www.example.com/page1.html but the page is now going to be renamed www.example.com/page1.php

How would people get around this problem? Simply redirect the html page to the php page? Are there any alternatives? Does this have any implications for SEO?

Thanks

答:
As answered by Marc B,

there is no such thing as a "PHP script". There are only files that contain  code blocks, which will get interpreted/executed when the containing file is passed through PHP.

i would say that it's true and if you want to absolutely turn your html files into php files simply put <?php before your <DOCTYPE html!> line and then ?> after your  line save it and rename it as example.php if it is example.html

if you are windows8 or higher user then click on 'View' in file explorer and then check 'File name Extension'. Now you'll be able to see the extension example.html and many other files extensions like .jpg, .mp3 e.t.c...., This helps you to easily rename exactly like example.php but not example.php.html as .html will not be visible if you are not checked File name Extension.

Title: Converting site from .html to .php

Body:
As answered by Marc B,

there is no such thing as a "PHP script". There are only files that contain  code blocks, which will get interpreted/executed when the containing file is passed through PHP.

i would say that it's true and if you want to absolutely turn your html files into php files simply put <?php before your <DOCTYPE html!> line and then ?> after your </html> line save it and rename it as example.php if it is example.html

if you are windows8 or higher user then click on 'View' in file explorer and then check 'File name Extension'. Now you'll be able to see the extension example.html and many other files extensions like .jpg, .mp3 e.t.c...., This helps you to easily rename exactly like example.php but not example.php.html as .html will not be visible if you are not checked File name Extension.


问:
what is the different between using sp_xml_preparedocument and selecting from xml parameter direcly
I have a Stored procedure in MSSQL 2012.

The sp get an xml datatype and insert the data into table

I found that i can use two options.

option 1

```<code>DECLARE @strXML AS xml
SET @strXML = '<DocumentElement><LocationData><SL_ID>2</SL_ID>
<IsDefault>1</IsDefault></LocationData><LocationData><SL_ID>3</SL_ID>
<IsDefault>0</IsDefault></LocationData></DocumentElement>'

SELECT
    'SL_ID' = x.v.value('SL_ID[1]','int'),
    'IsDefault' = x.v.value('IsDefault[1]','int')
 FROM @strXML.nodes('DocumentElement/LocationData') x(v)
</code>```

option 2

```<code>DECLARE @strXML AS xml
SET @strXML = '<DocumentElement><LocationData><SL_ID>2</SL_ID>
<IsDefault>1</IsDefault></LocationData><LocationData><SL_ID>3</SL_ID>
<IsDefault>0</IsDefault></LocationData></DocumentElement>'

DECLARE @hDoc int

EXEC sp_xml_preparedocument @hDoc OUTPUT, @strXML

SELECT SL_ID,IsDefault
FROM OPENXML(@hDoc, 'DocumentElement/LocationData')
WITH
(
   SL_ID int 'SL_ID',
   IsDefault int 'IsDefault'
)

EXEC sp_xml_removedocument @hDoc
</code>```

what is the different between them

答:
What is the difference?

Very easy: The one is good, the other is bad

FROM OPENXML with the corresponding SPs to prepare and to remove a document is outdated and should not be used any more (rare exceptions exist). Rather use the appropriate methods the XML data type provides.

SQL-Server does not store the XML as the string you see, but as a hierarchy tree structure. The XML you see is constructed for you when you read it. All modifications, all searching / filtering with XPath and XQuery is done against a table-like tree. This is astonishingly fast, because there's no string parsing necessary (this is done only once, when the XML is pushed into the native XML type).

The old fashioned approach with FROM OPENXML will do this expensive process over and over...

And very important: The modern approach is fully ad-hoc (inlined), while the old approach needs to work procedural (cannot be used within a VIEW or within an inline TVF)

Some background:

Read this link about sp_xml_preparedocument:

[ xmltext ] Is the original XML document. The MSXML parser parses this
  XML document. xmltext is a text parameter: char, nchar, varchar,
  nvarchar, text, ntext or xml.

The parameter you pass in is handled as a string. If you pass in a real XML it needs to reconstruct a string representation of your internal XML-tree just to do the expensive parsing process again. Might be, that the process is smart enough to recognise, that the paramter is an XML already and can handle this more performant, but I doubt this...

Body:
I have a Stored procedure in MSSQL 2012.

The sp get an xml datatype and insert the data into table

I found that i can use two options.

option 1

DECLARE @strXML AS xml
SET @strXML = '<DocumentElement><LocationData><SL_ID>2</SL_ID>
<IsDefault>1</IsDefault></LocationData><LocationData><SL_ID>3</SL_ID>
<IsDefault>0</IsDefault></LocationData></DocumentElement>'

SELECT
    'SL_ID' = x.v.value('SL_ID[1]','int'),
    'IsDefault' = x.v.value('IsDefault[1]','int')
 FROM @strXML.nodes('DocumentElement/LocationData') x(v)

option 2

DECLARE @strXML AS xml
SET @strXML = '<DocumentElement><LocationData><SL_ID>2</SL_ID>
<IsDefault>1</IsDefault></LocationData><LocationData><SL_ID>3</SL_ID>
<IsDefault>0</IsDefault></LocationData></DocumentElement>'

DECLARE @hDoc int

EXEC sp_xml_preparedocument @hDoc OUTPUT, @strXML

SELECT SL_ID,IsDefault
FROM OPENXML(@hDoc, 'DocumentElement/LocationData')
WITH
(
   SL_ID int 'SL_ID',
   IsDefault int 'IsDefault'
)

EXEC sp_xml_removedocument @hDoc

what is the different between them


问:
Zebra RW420 Android SDK print multiple copies avoiding a loop
I'm using the code below to print a bitmap with the Android SDK which can be found at this link:
https://www.zebra.com/us/en/products/software/barcode-printers/link-os/link-os-sdk.html#mainpartabscontainer_794f=downloads

//variables
int printQty= 3;
String printerAddress= ...;

Connection connection = new BluetoothConnection(printerAddress);
connection.open();

//for removing the useless margin printed
connection.write("! U1 JOURNAL\r\n! U1 SETFF 100 2\r\n".getBytes());

ZebraPrinter printer = ZebraPrinterFactory.getInstance(connection);
Bitmap bitmapToPrint = large bitmap here;
ZebraImageAndroid zebraImageToPrint = new ZebraImageAndroid(bitmapToPrint);

for (int i = 0; i < printQty; i++){
     printer.printImage(zebraImageToPrint, 0, 0, -1, -1, false);
}

bitmapToPrint.recycle();
connection.close();
```

The problem is:
the printing process is taking a lot of time because the bitmap is large.

Is there a way to avoid a loop and tell to the printer how many quantity to print without calling printImage multiple times?

i've searched a lot in the documentation but i've not found something usefull, is there a way to achieve this? With CPCL can i achieve the same effect?

Thanks
Mat

答:
This how i solved it at the end    </p>

```<code>int printQty = 5; //or whatever number you want
Coonection connection = new BluetoothConnection(deviceAddress);
connection.open();
//with SETFF command we add 50 millimiters of margin at the end of the the print (without this the print is wasting a lot of paper)
//ref https://km.zebra.com/kb/index?page=forums&topic=021407fb4efb3012e55595f77007e8a
connection.write("! U1 setvar \"device.languages\" \"CPCL\"\r\n".getBytes());
connection.write("! U1 JOURNAL\r\n! U1 SETFF 50 2\r\n".getBytes());
ZebraPrinter printer = ZebraPrinterFactory.getInstance(PrinterLanguage.CPCL, connection);
//get the bitmap to print
bitmapToPrint = PdfUtils.pdfToBitmap(getApplicationContext(), pdfStamped, 0);

int width = bitmapToPrint.getWidth();
int height = bitmapToPrint.getHeight();
float aspectRatio = width / ZEBRA_RW420_WIDTH; //ZEBRA_RW420_WIDTH = 800f
float multiplier = 1 / aspectRatio;
//scale the bitmap to fit the ZEBRA_RW_420_WIDTH print
bitmapToPrint = Bitmap.createScaledBitmap(bitmapToPrint, (int)(width * multiplier), (int)(height * multiplier), false);

//get the new bitmap and add 20 pixel more of margin
int newBitmapHeight = bitmapToPrint.getHeight() + 20;
//create the Zebra object with the new Bitmap
ZebraImageAndroid zebraImageToPrint = new ZebraImageAndroid(bitmapToPrint);
//the image is sent to the printer and stored in R: folder
printer.storeImage("R:TEMP.PCX", zebraImageToPrint, -1, -1);

//create the print commands string
String printString =
        "! 0 200 200 " + newBitmapHeight + " " + printQty   + "\r\n"//set the height of the bitmap and the quantity to print
        + "PW 831"                                          + "\r\n"//MAX_PRINT_WIDTH
        + "TONE 50"                                         + "\r\n"//print intensity tone 0-200
        + "SPEED 2"                                         + "\r\n"//print speed (less = more accurate) 1 2.5cm/s | 2 - 5cm/s | 3 - 7.6cm/s
        + "ON-FEED REPRINT"                                 + "\r\n"//enable reprint on FEED button press
        + "NO-PACE"                                         + "\r\n"
        + "BAR-SENSE"                                       + "\r\n"
        + "PCX 20 20 !<TEMP.PCX"                            + "\r\n"//get the image we stored before in the printer
        + "FORM"                                            + "\r\n"
        + "PRINT"                                           + "\r\n";//print
//send the commands to the printer, the image will be printed now
connection.write(printString.getBytes());

//delete the image at the end to prevent printer memory sutaration
connection.write("! U1 do \"file.delete\" \"R:TEMP.PCX\"\r\n".getBytes());
//close the connection with the printer
connection.close();
//recycle the bitmap
bitmapToPrint.recycle();
</code>```

Body:
I'm using the code below to print a bitmap with the Android SDK which can be found at this link:
https://www.zebra.com/us/en/products/software/barcode-printers/link-os/link-os-sdk.html#mainpartabscontainer_794f=downloads

//variables
int printQty= 3;
String printerAddress= ...;

Connection connection = new BluetoothConnection(printerAddress);
connection.open();

//for removing the useless margin printed
connection.write("! U1 JOURNAL\r\n! U1 SETFF 100 2\r\n".getBytes());

ZebraPrinter printer = ZebraPrinterFactory.getInstance(connection);
Bitmap bitmapToPrint = large bitmap here;
ZebraImageAndroid zebraImageToPrint = new ZebraImageAndroid(bitmapToPrint);

for (int i = 0; i < printQty; i++){
     printer.printImage(zebraImageToPrint, 0, 0, -1, -1, false);
}

bitmapToPrint.recycle();
connection.close();

The problem is:
the printing process is taking a lot of time because the bitmap is large.

Is there a way to avoid a loop and tell to the printer how many quantity to print without calling printImage multiple times?

i've searched a lot in the documentation but i've not found something usefull, is there a way to achieve this? With CPCL can i achieve the same effect?

Thanks
Mat

Body:
This how i solved it at the end

int printQty = 5; //or whatever number you want
Coonection connection = new BluetoothConnection(deviceAddress);
connection.open();
//with SETFF command we add 50 millimiters of margin at the end of the the print (without this the print is wasting a lot of paper)
//ref https://km.zebra.com/kb/index?page=forums&topic=021407fb4efb3012e55595f77007e8a
connection.write("! U1 setvar \"device.languages\" \"CPCL\"\r\n".getBytes());
connection.write("! U1 JOURNAL\r\n! U1 SETFF 50 2\r\n".getBytes());
ZebraPrinter printer = ZebraPrinterFactory.getInstance(PrinterLanguage.CPCL, connection);
//get the bitmap to print
bitmapToPrint = PdfUtils.pdfToBitmap(getApplicationContext(), pdfStamped, 0);

int width = bitmapToPrint.getWidth();
int height = bitmapToPrint.getHeight();
float aspectRatio = width / ZEBRA_RW420_WIDTH; //ZEBRA_RW420_WIDTH = 800f
float multiplier = 1 / aspectRatio;
//scale the bitmap to fit the ZEBRA_RW_420_WIDTH print
bitmapToPrint = Bitmap.createScaledBitmap(bitmapToPrint, (int)(width * multiplier), (int)(height * multiplier), false);

//get the new bitmap and add 20 pixel more of margin
int newBitmapHeight = bitmapToPrint.getHeight() + 20;
//create the Zebra object with the new Bitmap
ZebraImageAndroid zebraImageToPrint = new ZebraImageAndroid(bitmapToPrint);
//the image is sent to the printer and stored in R: folder
printer.storeImage("R:TEMP.PCX", zebraImageToPrint, -1, -1);

//create the print commands string
String printString =
        "! 0 200 200 " + newBitmapHeight + " " + printQty   + "\r\n"//set the height of the bitmap and the quantity to print
        + "PW 831"                                          + "\r\n"//MAX_PRINT_WIDTH
        + "TONE 50"                                         + "\r\n"//print intensity tone 0-200
        + "SPEED 2"                                         + "\r\n"//print speed (less = more accurate) 1 2.5cm/s | 2 - 5cm/s | 3 - 7.6cm/s
        + "ON-FEED REPRINT"                                 + "\r\n"//enable reprint on FEED button press
        + "NO-PACE"                                         + "\r\n"
        + "BAR-SENSE"                                       + "\r\n"
        + "PCX 20 20 !<TEMP.PCX"                            + "\r\n"//get the image we stored before in the printer
        + "FORM"                                            + "\r\n"
        + "PRINT"                                           + "\r\n";//print
//send the commands to the printer, the image will be printed now
connection.write(printString.getBytes());

//delete the image at the end to prevent printer memory sutaration
connection.write("! U1 do \"file.delete\" \"R:TEMP.PCX\"\r\n".getBytes());
//close the connection with the printer
connection.close();
//recycle the bitmap
bitmapToPrint.recycle();


问:
Can't reference an assembly in a T4 template
I have the following code in a tester class in my main assembly, PocoGenerator.  This assembly is supposed to use a T4 template to generate POCO's based on L2S entities in a referenced assembly (a project reference), DataObjects.

```<code>var assemblyName = "DataObjects";
var dataObjects = AppDomain.CurrentDomain.Load(new AssemblyName(assemblyName));
</code>```

Try as I may, I cannot get T4 to find the DataObjects assembly.  I have tried various forms of assembly directives, like:

```<code><#@ assembly name="DataObjects" #>
<#@ assembly name="DataObjects, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" #>
</code>```

to no avail.  The code above works in the tester class, but not in the template.  What am I doing wrong?

ADDED:
I have resolved this issue by using the absolute path to the assembly in bot places I reference it, the directive as well as the class feature block, i.e.

```<code><#@ assembly name="C:\Development\PocoGenerator\DataObjects\bin\Debug\DataObjects.dll" #>
</code>```

and

```<code>var sourceAssembly = Assembly.LoadFile(@"C:\Development\PocoGenerator\DataObjects\bin\Debug\DataObjects.dll");
</code>```

But I really don't like this, as I would like to use this template in various projects, and I just plain hate duplication, especially of magic strings.

答:
```<code><#@ assembly name="$(ProjectDir)bin\Debug\ProofOfConcept.dll" #>
</code>```

Happy Coding!

ContentLicense: CC BY-SA 2.5

Body:
I have the following code in a tester class in my main assembly, PocoGenerator.  This assembly is supposed to use a T4 template to generate POCO's based on L2S entities in a referenced assembly (a project reference), DataObjects.

var assemblyName = "DataObjects";
var dataObjects = AppDomain.CurrentDomain.Load(new AssemblyName(assemblyName));

Try as I may, I cannot get T4 to find the DataObjects assembly.  I have tried various forms of assembly directives, like:

<#@ assembly name="DataObjects" #>
<#@ assembly name="DataObjects, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" #>

to no avail.  The code above works in the tester class, but not in the template.  What am I doing wrong?

ADDED:
I have resolved this issue by using the absolute path to the assembly in bot places I reference it, the directive as well as the class feature block, i.e.

<#@ assembly name="C:\Development\PocoGenerator\DataObjects\bin\Debug\DataObjects.dll" #>

and

var sourceAssembly = Assembly.LoadFile(@"C:\Development\PocoGenerator\DataObjects\bin\Debug\DataObjects.dll");

But I really don't like this, as I would like to use this template in various projects, and I just plain hate duplication, especially of magic strings.

Body:
<#@ assembly name="$(ProjectDir)bin\Debug\ProofOfConcept.dll" #>

Happy Coding!


问:
What is use of `""+` in setText
I have an example:

```<code> int num1 = Integer.parseInt(firstno.getText());
 int num2 = Integer.parseInt(secondno.getText());
 int num3 = num1+num2;
 result.setText(""+num3);
</code>```

what is use of "" in result.setText(""+num3);

答:
It's a (very) lazy way to convert int to String.

```<code>result.setText(num3);
</code>```

Does not work because setText() requires a String and not an int. Better would be to use this:

```<code>result.setText(String.valueOf(num3));
</code>```

Title: What is use of `""+` in setText

Body:
I have an example:

 int num1 = Integer.parseInt(firstno.getText());
 int num2 = Integer.parseInt(secondno.getText());
 int num3 = num1+num2;
 result.setText(""+num3);

what is use of "" in result.setText(""+num3);

Body:
It's a (very) lazy way to convert int to String.

result.setText(num3);

Does not work because setText() requires a String and not an int. Better would be to use this:

result.setText(String.valueOf(num3));


问:
Data gets garbled when writing to csv with fputcsv() / fgetcsv()
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

```<code>$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);
</code>```

Gives me this output:

```<code>BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)
</code>```

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

答:
This is not PHP bug. It seems that json_encode() use the same delimiter (,), enclosure (") and escape (\) which is the same as default delimiter, enclosure and escape for both fputcsv() and fgetcsv(). You may differentiate enclosure or escape, and delimiter if necessary.

As already answered, in this case it will work by specify enclosure with (') instead:

```<code>$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before, ',', "'");

rewind($fh);

$row_after = fgetcsv($fh, 0, ',', "'");

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);
</code>```

Body:
There seems to be an encoding issue or bug in PHP with fputcsv() and fgetcsv().

The following PHP code:

$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before);

rewind($fh);

$row_after = fgetcsv($fh);

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);

Gives me this output:

BEFORE:
array (
  0 => 'A',
  1 => '["a","\\\\","b"]',
  2 => 'B',
)

AFTER:
array (
  0 => 'A',
  1 => '["a","\\\\',
  2 => 'b""]"',
  3 => 'B',
)

So clearly, the data is damaged on the way. Originally there were just 3 cells in the row, afterwards there are 4 cells in the row. The middle cell is split thanks to the backslash that is also used as an escape character.

See also
https://3v4l.org/nc1oE
Or here, with explicit values for delimiter, enclosure, escape_char: https://3v4l.org/Svt7m

Is there any way I can sanitize / escape my data before writing to CSV, to guarantee that the data read from the file will be exactly the same?

Is CSV a fully reversible format?

EDIT: The goal would be a mechanism to properly write and read ANY data as csv, so that after one round trip the data is still the same.

EDIT: I realize that I do not really understand the $escape_char parameter. See also fgetcsv/fputcsv $escape parameter fundamentally broken Maybe an answer to this would also bring us closer to a solution.

Body:
This is not PHP bug. It seems that json_encode() use the same delimiter (,), enclosure (") and escape (\) which is the same as default delimiter, enclosure and escape for both fputcsv() and fgetcsv(). You may differentiate enclosure or escape, and delimiter if necessary.

As already answered, in this case it will work by specify enclosure with (') instead:

$row_before = ['A', json_encode(['a', '\\', 'b']), 'B'];

print "\nBEFORE:\n";
var_export($row_before);
print "\n";

$fh = fopen($file = 'php://temp', 'rb+');

fputcsv($fh, $row_before, ',', "'");

rewind($fh);

$row_after = fgetcsv($fh, 0, ',', "'");

print "\nAFTER:\n";
var_export($row_after);
print "\n\n";

fclose($fh);


问:
Selenium/Watir: 'InvalidCookieDomain' error when trying to add cookie
I am new into WATIR, or Selenium, but I was trying to add a cookie into my WATIR browser, as below:

```<code>browser = Watir::Browser.new :firefox
browser.goto(url)
browser.cookies.add name,value, domain: ".www.example.com"
</code>```

I am prompted with the following error:

Selenium::WebDriver::Error::UnknownError: ReferenceError: InvalidCookieDomainError is not defined

But, when I delete the domain option, it works.

I was wondering why I can't add a different domain into my cookies?

答:
Like WATIR, all Selenium-based frameworks create language-specific wrappers to Selenium pre-defined commands. These commands are defined here in the Selenium Webdriver W3C standard.

If you go to Cookies section, specifically, the addCookie sub-section, you will see the following:

If the current browsing context’s document element is a cookie-averse Document object, return error with error code invalid cookie domain.

Your domain attribute is bound to the same domain as your given url. So, basically, your domain HAS to be the same as your current url, or a sub-domain of the url.

Example: For url=global.nba.com, you can set cookies for both the sub-domain ({domain: "global.nba.com"}), as well as for the root-domain ({domain: "nba.com"}).

```<code>browser = Watir::Browser.new :firefox
browser.goto(url)
browser.cookies.add("<yourCookieName>","<yourCookieValue>", {domain: "<sameUrlOriginDomain>"})
</code>```

Hope this helps!

Body:
I am new into WATIR, or Selenium, but I was trying to add a cookie into my WATIR browser, as below:

browser = Watir::Browser.new :firefox
browser.goto(url)
browser.cookies.add name,value, domain: ".www.example.com"

I am prompted with the following error:

Selenium::WebDriver::Error::UnknownError: ReferenceError: InvalidCookieDomainError is not defined

But, when I delete the domain option, it works.

I was wondering why I can't add a different domain into my cookies?

Body:
Like WATIR, all Selenium-based frameworks create language-specific wrappers to Selenium pre-defined commands. These commands are defined here in the Selenium Webdriver W3C standard.

If you go to Cookies section, specifically, the addCookie sub-section, you will see the following:

If the current browsing context’s document element is a cookie-averse Document object, return error with error code invalid cookie domain.

Your domain attribute is bound to the same domain as your given url. So, basically, your domain HAS to be the same as your current url, or a sub-domain of the url.

Example: For url=global.nba.com, you can set cookies for both the sub-domain ({domain: "global.nba.com"}), as well as for the root-domain ({domain: "nba.com"}).

browser = Watir::Browser.new :firefox
browser.goto(url)
browser.cookies.add("<yourCookieName>","<yourCookieValue>", {domain: "<sameUrlOriginDomain>"})

Hope this helps!


问:
Silverlight 4, MEF, Export/Import errors, Mefx doesn't want to work
Out of frustration and more than 3 days googling up this issue... i have no choice but to bother you guys with my question.

i am creating a Silverlight application. I am using MEF. When i try to run my application i get the following error.

The invocation of the constructor on
  type
  'IFG.Silverlight.Client.Views.MenuView'
  that matches the specified binding
  constraints threw an exception. [Line:
  25 Position: 47]

and its Inner exception is as follow...

The composition remains unchanged. The
  changes were rejected because of the
  following error(s): The composition
  produced a single composition error.
  The root cause is provided below.
  Review the CompositionException.Errors
  property for more detailed
  information.

1) No valid exports were found that
  match the constraint
  '((exportDefinition.ContractName ==
  "MenuViewModel") AndAlso
  (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity")
  AndAlso
  "IFG.Silverlight.Client.ViewModel.MenuViewModel".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))',
  invalid exports may have been
  rejected.

Resulting in: Cannot set import
  'IFG.Silverlight.Client.Views.MenuView.ViewModel
  (ContractName="MenuViewModel")' on
  part
  'IFG.Silverlight.Client.Views.MenuView'.
  Element:
  IFG.Silverlight.Client.Views.MenuView.ViewModel
  (ContractName="MenuViewModel") -->
  IFG.Silverlight.Client.Views.MenuView

Ok. my code is very simple since it's a test application.

i have an Interface IRetailModel

```<code>namespace IFG.Silverlight.Client.Common
{
    public interface IRetailModel
    { ............
</code>```

then i have a class that implements this interface

```<code>namespace IFG.Silverlight.Client.Model
{
    [Export(typeof(IRetailModel))]
    public class RetailModel : IRetailModel
    { .................
</code>```

Then I have my ViewModel for the View

```<code>namespace IFG.Silverlight.Client.ViewModel
{
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Export(ViewModelTypes.MenuViewModel)]
    public class MenuViewModel : IFGViewModelBase
    {
 IRetailModel _model;

        [ImportingConstructor]
        public MenuViewModel(IRetailModel model)
        {
</code>```

Well, i found that there is a magical tool called MefX that it's supposed to debug deep to the bone your code and tells you what's going on... I havent been able to get this to work.

I followed directions from this article http://blogs.msdn.com/b/nblumhardt/archive/2009/09/24/debug-composition-from-within-visual-studio.aspx

When i try to run it says

Error: Unable to load one or more of
  the requested types. Retrieve the
  LoaderExceptions property for more
  information.

Then went back to Google and i found this Visual MefX (which is the same but with a GUI) and i can load the .xap but basically it gives me the same info that i get from Visual Studio. I can't find the darn [BECAUSE]...

I am really, HONESTLY AND DEEPLY, frustrated with this situation. Can anyone explain to me where am i failing to get MefX to do its job? I know the risk of dealing with these Overnight Frameworks (lack of documentation, buggy, etc etc) that MEF seems to be, but Prism is not a option to me (i feel like buying a M16 to kill a fly when i can use my finger).

Thank you

答: For future reference, an updated version of Visual Mefx is attached to this blog post: How to Debug and Diagnose MEF Failures.  It is also part of MEFContrib, although I'm not sure if the MEFContrib version has all the changes from the version in the blog post.</p>

Body:
Out of frustration and more than 3 days googling up this issue... i have no choice but to bother you guys with my question.

i am creating a Silverlight application. I am using MEF. When i try to run my application i get the following error.

The invocation of the constructor on
  type
  'IFG.Silverlight.Client.Views.MenuView'
  that matches the specified binding
  constraints threw an exception. [Line:
  25 Position: 47]

and its Inner exception is as follow...

The composition remains unchanged. The
  changes were rejected because of the
  following error(s): The composition
  produced a single composition error.
  The root cause is provided below.
  Review the CompositionException.Errors
  property for more detailed
  information.

1) No valid exports were found that
  match the constraint
  '((exportDefinition.ContractName ==
  "MenuViewModel") AndAlso
  (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity")
  AndAlso
  "IFG.Silverlight.Client.ViewModel.MenuViewModel".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))',
  invalid exports may have been
  rejected.

Resulting in: Cannot set import
  'IFG.Silverlight.Client.Views.MenuView.ViewModel
  (ContractName="MenuViewModel")' on
  part
  'IFG.Silverlight.Client.Views.MenuView'.
  Element:
  IFG.Silverlight.Client.Views.MenuView.ViewModel
  (ContractName="MenuViewModel") -->
  IFG.Silverlight.Client.Views.MenuView

Ok. my code is very simple since it's a test application.

i have an Interface IRetailModel

namespace IFG.Silverlight.Client.Common
{
    public interface IRetailModel
    { ............

then i have a class that implements this interface

namespace IFG.Silverlight.Client.Model
{
    [Export(typeof(IRetailModel))]
    public class RetailModel : IRetailModel
    { .................

Then I have my ViewModel for the View

namespace IFG.Silverlight.Client.ViewModel
{
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Export(ViewModelTypes.MenuViewModel)]
    public class MenuViewModel : IFGViewModelBase
    {
 IRetailModel _model;

        [ImportingConstructor]
        public MenuViewModel(IRetailModel model)
        {

Well, i found that there is a magical tool called MefX that it's supposed to debug deep to the bone your code and tells you what's going on... I havent been able to get this to work.

I followed directions from this article http://blogs.msdn.com/b/nblumhardt/archive/2009/09/24/debug-composition-from-within-visual-studio.aspx

When i try to run it says

Error: Unable to load one or more of
  the requested types. Retrieve the
  LoaderExceptions property for more
  information.

Then went back to Google and i found this Visual MefX (which is the same but with a GUI) and i can load the .xap but basically it gives me the same info that i get from Visual Studio. I can't find the darn [BECAUSE]...

I am really, HONESTLY AND DEEPLY, frustrated with this situation. Can anyone explain to me where am i failing to get MefX to do its job? I know the risk of dealing with these Overnight Frameworks (lack of documentation, buggy, etc etc) that MEF seems to be, but Prism is not a option to me (i feel like buying a M16 to kill a fly when i can use my finger).

Thank you


问:
Failed to get bootstrap index from server
I am trying to do code analysis for sonarqube. However, I got the error when running

mvm sonar:sonar

This is the error message:

```<code>[ERROR] SonarQube server [http://localhost:9000] can not be reached
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 42.972 s
[INFO] Finished at: 2017-06-06T08:51:52+08:00
[INFO] Final Memory: 8M/19M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:
3.3.0.603:sonar (default-cli) on project example-java-maven: Unable to execute SonarQube:
Fail to get bootstrap index from server: Status returned by url
[http://localhost:9000/batch/index] is not valid: [504] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions,
please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

But when I access http://localhost:9000 via the browser, I can see the sonarqube homepage.

So why could this be happening?

Thank you.

答:
Try to use sonar-maven-plugin version 3.2 on your pom.xml

```<code> <plugin>
      <groupId>org.sonarsource.scanner.maven</groupId>
      <artifactId>sonar-maven-plugin</artifactId>
      <version>3.2</version>
  </plugin>
</code>```

This works for me

Body:
I am trying to do code analysis for sonarqube. However, I got the error when running

mvm sonar:sonar

This is the error message:

[ERROR] SonarQube server [http://localhost:9000] can not be reached
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 42.972 s
[INFO] Finished at: 2017-06-06T08:51:52+08:00
[INFO] Final Memory: 8M/19M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:
3.3.0.603:sonar (default-cli) on project example-java-maven: Unable to execute SonarQube:
Fail to get bootstrap index from server: Status returned by url
[http://localhost:9000/batch/index] is not valid: [504] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions,
please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

But when I access http://localhost:9000 via the browser, I can see the sonarqube homepage.

So why could this be happening?

Thank you.

Body:
Try to use sonar-maven-plugin version 3.2 on your pom.xml

 <plugin>
      <groupId>org.sonarsource.scanner.maven</groupId>
      <artifactId>sonar-maven-plugin</artifactId>
      <version>3.2</version>
  </plugin>

This works for me


问:
Qt c++ Does my program use static or dynamic linking?
Sorry about this probably stupid question - I don`t know much about linking :

I use Qt QtCreator to program a GUI in C++ in a program that existed before where  I had to adapt it.  Now my Question is : How do I know whether the program uses static or dynamic linking?

When I install the program I wrote on another device I find a list of the executable(s) plus 5 dlls ( libgcc_s_dw2-1.dll, libxml2.dll, mingwm10.dll, QtCore4.dll, QtGui4.dll)

In my pro-File I have an entry  CONFIG += qaxcontainer and another entry where I do link libxml dynamically .

Does this mean all is linked dynamically?

Thank you very much

答:
If your program requires the .dll file in order to run, it means that it is dynamically linked.
Static libraries are .lib (on Windows) and are embedded directly in the executable file.


问:
Scrollbar to bottom QTableWidget
I have a QTableWidget that is filled in realtime.
I use the function scrollToBottom() to always see the last information displayed by my table.

It worked well when the size of my différents rows are unchanged.
But sometimes I receive informations that increase the size of my row and the problem is that my table display them like if they were regular rows and with that problem the user can't see the entire row.

If someone already had this problem how did you solve it ?

If it is not clear let me know.

答:
I had a similar problem with ListView in qml but also with QListWidget. I had to implement a messanger list which added messages dynamically. I still couldn't find a proper solution but I figured out the problem. Your QTableWidget doesn't know how to resize "invisible" row. It approximates the rows size in respect to the visible rows size. I tried to implement custom QListWidget and overwrite the drawing function but couldn't make it work. At that moment I used Qt5.4, I don't know if the issue is solved in the latest versions.

However, one solution is to create html content and display it on a WebView. It's not the most elegant solution but theoretically it should work like a charm.

Title: Scrollbar to bottom QTableWidget


问:
cURL error 7: Failed to connect to localhost port 4444: Connection refused
I have been trying to send a request post to my localhost using guzzlehttp/guzzle v6.2.3  but i keep getting the error shown in the title. I have tried to make the call using Postman and it works fine. I have been doing some searching and found that most people solve the issue by changing localhost to 127.0.0.1 or to the IPv4.. I have tried all of them but still getting the same error every time. Here is my code:

```<code>$client = new Client();
$res = $client>post('http://localhost:4444/api/abc/xyz',request(['x', 'y']));
echo $res->getStatusCode();
</code>```

Please assist me resolving the problem.

答:
I have found the solution. actually the issue is caused because i'm using homestead, so I can't use localhost as it will browse the VM localhost. I had to change the path to

http://10.0.2.2/api/abc/xyz

Body:
I have been trying to send a request post to my localhost using guzzlehttp/guzzle v6.2.3  but i keep getting the error shown in the title. I have tried to make the call using Postman and it works fine. I have been doing some searching and found that most people solve the issue by changing localhost to 127.0.0.1 or to the IPv4.. I have tried all of them but still getting the same error every time. Here is my code:

$client = new Client();
$res = $client>post('http://localhost:4444/api/abc/xyz',request(['x', 'y']));
echo $res->getStatusCode();

Please assist me resolving the problem.


问:
angularjs ng-repeat dependable selectBox
i want to make my selectbox dependable, so, if i choose region "America", the second selectBox should only show New York, but i don't have any idea how to make it, i try to use ng-click inside my option, but it doesn't work. And i can't change my database type, i need to work with it, so anyone know how to make it without change any database structure?

var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
$scope.countryList=[];
 $scope.data =[
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Busan", city_code:"PUS"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Seoul", city_code:"SEL"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Ulsan", city_code:"USN"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"GwangJu", city_code:"KWJ"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Gunsan", city_code:"KUV"},
 {id:1, country_code:"USA", country_name:"America", city_name:"New York", city_code:"NY"}
 ];

    for (var i = 0; i < $scope.data.length; i++) {
     var isExist = false;
     for (var j = 0; j < $scope.countryList.length; j++) {
      if (JSON.stringify($scope.data[i].country_code) == JSON.stringify($scope.countryList[j].country_code)) {
       isExist = true;
       break;
      }
     }
     if (isExist == false) {
      $scope.countryList.push($scope.data[i]);
     }
    }
});
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="port_small_select_div">
            <select class="small_select">
              <option disabled selected hidden>Region</option>
              <option ng-repeat="country in countryList" value="{{ country.country_code }}">{{ country.country_name}}</option>
            </select>
          </div>

          <div class="port_select_div">
            <select class="big_select">
              <option disabled selected hidden>Detailed information</option>
              <option ng-repeat="city in data" value="{{ city.city_code }}">{{ city.city_name}}</option>
            </select>
          </div>
          </div></code>```

答:
You could apply filter over the second dropdown based on country_code of selection of 1st dropdown. I also replaces dropdown to use ng-options. Also you should consider adding ng-model to each select box.

```<code><select class="small_select" ng-model="selectedRegion"
  ng-options="country.country_name as country_code for in countryList">
  <option disabled selected hidden>Region</option>
</select>

<select class="big_select" ng-model="selectedCity"
 ng-options="city.city_code as city.city_name for city in data | filter: {country_code: selectedRegion }">
  <option disabled selected hidden>Detailed information</option>
</select>
</code>```

Body:
i want to make my selectbox dependable, so, if i choose region "America", the second selectBox should only show New York, but i don't have any idea how to make it, i try to use ng-click inside my option, but it doesn't work. And i can't change my database type, i need to work with it, so anyone know how to make it without change any database structure?

var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
$scope.countryList=[];
 $scope.data =[
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Busan", city_code:"PUS"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Seoul", city_code:"SEL"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Ulsan", city_code:"USN"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"GwangJu", city_code:"KWJ"},
 {id:1, country_code:"KR", country_name:"Korea", city_name:"Gunsan", city_code:"KUV"},
 {id:1, country_code:"USA", country_name:"America", city_name:"New York", city_code:"NY"}
 ];

    for (var i = 0; i < $scope.data.length; i++) {
     var isExist = false;
     for (var j = 0; j < $scope.countryList.length; j++) {
      if (JSON.stringify($scope.data[i].country_code) == JSON.stringify($scope.countryList[j].country_code)) {
       isExist = true;
       break;
      }
     }
     if (isExist == false) {
      $scope.countryList.push($scope.data[i]);
     }
    }
});

            <select class="small_select">
              <option disabled selected hidden>Region</option>
              <option ng-repeat="country in countryList" value="{{ country.country_code }}">{{ country.country_name}}</option>
            </select>

            <select class="big_select">
              <option disabled selected hidden>Detailed information</option>
              <option ng-repeat="city in data" value="{{ city.city_code }}">{{ city.city_name}}</option>
            </select>

Body:
You could apply filter over the second dropdown based on country_code of selection of 1st dropdown. I also replaces dropdown to use ng-options. Also you should consider adding ng-model to each select box.

<select class="small_select" ng-model="selectedRegion"
  ng-options="country.country_name as country_code for in countryList">
  <option disabled selected hidden>Region</option>
</select>

<select class="big_select" ng-model="selectedCity"
 ng-options="city.city_code as city.city_name for city in data | filter: {country_code: selectedRegion }">
  <option disabled selected hidden>Detailed information</option>
</select>


问:
Create a custom exception and handle it with .NET Core
I have 2 projects both in .NET Core a "Business" project and a WebApi.

I'd like create a custom exception to throw from my "Business" project and try/catch in the controller and then do different action depending the exception type.

I try the classic way to create a custom exception (part of the code)

```<code>protected NegativeNumberException(SerializationInfo info, StreamingContext context)
  : base(info, context)
{
}
</code>```

but SerializationInfo does not exist in .NET Core.

How can I do this ?

答:
Use System.Runtime.Serialization.Formatters nuget package.

In general, you may use package search site when you are looking for the specific type.

Body:
I have 2 projects both in .NET Core a "Business" project and a WebApi.

I'd like create a custom exception to throw from my "Business" project and try/catch in the controller and then do different action depending the exception type.

I try the classic way to create a custom exception (part of the code)

protected NegativeNumberException(SerializationInfo info, StreamingContext context)
  : base(info, context)
{
}

but SerializationInfo does not exist in .NET Core.

How can I do this ?


问:
FORTRAN wipes arg values between function calls?
So strange. Does FORTRAN require variables to be reinitialized after they've been sent as parameters? I kept getting a segmentation fault whenever I'd send the same arguments to another subroutine. I discovered that the argument values were being wiped between the first call and the second, with no reassignment statements on the arguments between function calls or even in either function. The scope of these arguments is limited to the main program (I'm not using any COMMON blocks).

I can't post code right now as I'm writing from my phone, but any ideas? The temporary workaround is to reassign the values right before calling the second function.

Thanks for the help.

答: Fortran passes arguments by reference, so if you are modifying them in the first subroutine, they will be changed in the caller.</p>


问:
Ngrok Bad Gateway Intermittent 502
I am running ngrok to forward webhooks at my local vagrant running ubuntu and apache (it is a php laravel application).  I am getting intermittent bad gateway errors.

What is strange is that the inspector on http://127.0.0.1:4040/ is showing 200's

The third party system that is firing the webhooks is returning the raw html as

```<code><html>
    <body>
        <h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.

    </body>
</html>
</code>```

Because it works sometimes I don't think there is a problem with the setup. Any suggests would be helpful.  Right now I just hit it again and again until it is successful.

One thing is that the local dev is slow,

For example from the ngrok inspector.

GET /inbound/webhook  200 OK  3.44s

I noticed that the slower response are more likely to throw a 502.

Anyone know how to fix this problem?

答:
So actually what is happening in your case is, the request is reaching your server and it responds after the request has been timed out. Hence Twilio responds with 502 after a timeout. But your server is sending a correct response (Request is not capable of taking your response due to delay).

Kindly make sure your server's responding time is faster! That will fix this.

Title: Ngrok Bad Gateway Intermittent 502

Body:
I am running ngrok to forward webhooks at my local vagrant running ubuntu and apache (it is a php laravel application).  I am getting intermittent bad gateway errors.

What is strange is that the inspector on http://127.0.0.1:4040/ is showing 200's

The third party system that is firing the webhooks is returning the raw html as

502 Bad Gateway

The server returned an invalid or incomplete response.

Because it works sometimes I don't think there is a problem with the setup. Any suggests would be helpful.  Right now I just hit it again and again until it is successful.

One thing is that the local dev is slow,

For example from the ngrok inspector.

GET /inbound/webhook  200 OK  3.44s

I noticed that the slower response are more likely to throw a 502.

Anyone know how to fix this problem?


问:
Login form doesn't verify the password
I am working on a login form and the password doesn't get verified from some reason. The user supposed to log in into system with email and password. I am matching user based on the email with the data in database. Could you please look at it?

Customer table

HTML form in file index.php

Login to Your Account

   <form method="post" action="login.php" class="form">

         <input type="text" name="email" id="email" class="input-md form-control" placeholder="Email" required />

         <input type="password" name="password" id="password" class="input-md form-control" placeholder="Password" required />

         <input type="submit" name="login" class="login btn btn-mod btn-medium" id="btnLogIn" value="Login" />

   </form>

```
</div>
</div>
</p>

<p>File login.php</p>

``` <?php
require_once 'connection_db.php';
$response = new stdClass;
if (empty($_POST['email']) || empty($_POST['password'])) {
    $response->success = false;
    $response->message = 'Email and password cannot be empty.';
} else {
    $sql = 'SELECT * FROM `customer` WHERE `email` = ? ';

    $email = $_POST['email'];
    $password = $_POST['password'];
    $password = password_hash($password, PASSWORD_DEFAULT);
    // print_r($password, true);

    try {
        $stmt = $db->prepare($sql);
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $array = $result->fetch_array(MYSQLI_ASSOC);
        // print_r($array, true);
        if (count($array)) {
            $response->success = true;
            $response->message = 'Login successful.';
            session_start();
            $_SESSION['email'] = $email;
            $_SESSION['id'] = $id;
            $_SESSION['current_page'] = $_SERVER['HTTP_REFERER'];
            header("Location: ". $_SESSION['current_page']);

        } else {
            $response->success = false;
            $response->message = 'Wrong username or password.';
            header("Location: index.php#test-popup");
        }
    }
    catch (Exception $e) {
        $response->success = false;
        $response->message = "Error.";
    }
}
// unset($db);
?>
```

答:
Here's a generic setup of how your login script should look:

```<code>if (isset($_POST['submit']))
{
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (!empty($email) && !empty($password))
    {
        $res = $dbh->prepare("SELECT * FROM `customer` WHERE `email` = ?");
        $res->execute([$email]);

        $row = $res->fetch(MYSQLI_ASSOC);

        if ($res->rowCount() > 0)
        {
            if (password_verify($password, $row['password']))
            {
                $_SESSION['user_session'] = $row['uid'];

                header('Location: loggedIn.php');
            } else {
                // echo incorrect pass
            }
        } else {
            // echo no such user...
        }
    } else {
        // echo something...
    }
}
</code>```

You should be using password_verify for your login script. You only use password_hash for registering to hash the password that has been submitted.

Title: Login form doesn't verify the password

Body:
I am working on a login form and the password doesn't get verified from some reason. The user supposed to log in into system with email and password. I am matching user based on the email with the data in database. Could you please look at it?

Customer table

HTML form in file index.php

Login to Your Account

   <form method="post" action="login.php" class="form">

         <input type="text" name="email" id="email" class="input-md form-control" placeholder="Email" required />

         <input type="password" name="password" id="password" class="input-md form-control" placeholder="Password" required />

         <input type="submit" name="login" class="login btn btn-mod btn-medium" id="btnLogIn" value="Login" />

   </form>

File login.php

 <?php
require_once 'connection_db.php';
$response = new stdClass;
if (empty($_POST['email']) || empty($_POST['password'])) {
    $response->success = false;
    $response->message = 'Email and password cannot be empty.';
} else {
    $sql = 'SELECT * FROM `customer` WHERE `email` = ? ';

    $email = $_POST['email'];
    $password = $_POST['password'];
    $password = password_hash($password, PASSWORD_DEFAULT);
    // print_r($password, true);

    try {
        $stmt = $db->prepare($sql);
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $array = $result->fetch_array(MYSQLI_ASSOC);
        // print_r($array, true);
        if (count($array)) {
            $response->success = true;
            $response->message = 'Login successful.';
            session_start();
            $_SESSION['email'] = $email;
            $_SESSION['id'] = $id;
            $_SESSION['current_page'] = $_SERVER['HTTP_REFERER'];
            header("Location: ". $_SESSION['current_page']);

        } else {
            $response->success = false;
            $response->message = 'Wrong username or password.';
            header("Location: index.php#test-popup");
        }
    }
    catch (Exception $e) {
        $response->success = false;
        $response->message = "Error.";
    }
}
// unset($db);
?>

Body:
Here's a generic setup of how your login script should look:

if (isset($_POST['submit']))
{
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (!empty($email) && !empty($password))
    {
        $res = $dbh->prepare("SELECT * FROM `customer` WHERE `email` = ?");
        $res->execute([$email]);

        $row = $res->fetch(MYSQLI_ASSOC);

        if ($res->rowCount() > 0)
        {
            if (password_verify($password, $row['password']))
            {
                $_SESSION['user_session'] = $row['uid'];

                header('Location: loggedIn.php');
            } else {
                // echo incorrect pass
            }
        } else {
            // echo no such user...
        }
    } else {
        // echo something...
    }
}

You should be using password_verify for your login script. You only use password_hash for registering to hash the password that has been submitted.