问:
Images wont stick in my database
I've been working on this issue for several days and I can't figure out what I'm doing wrong. I'm making an inventory/store app for a project where the user can input what items they have in stock into a list. As per the requirements I need to give it picture taking capability and I need to be able to save the picture in the SQLite database. That part I have achieved. But when I attempt to update an item and save it again to the list, the image returns null. I've attached pictures to visually explain...

Main activity

New item page

Save an item to the Main Activity listview

Click on an item to edit

Unless I take a new picture, when i save the updated item, the icon image returns null

I'm using a CursorLoader. I've treated the image the same way I treated all the other columns in the database... so I can't figure out why it won't stick.

Here's the code pertaining to images in EditorActivity:

```<code>Bitmap photos;

// Content URI for the existing item (null if it's a new item)
private Uri mCurrentItemUri;

// Picture taking capability with button
public void takePicture(View view) {
    PackageManager pm = this.getPackageManager();
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    } else {
        Toast.makeText(EditorActivity.this, "Sorry! You don't have a camera app.", Toast.LENGTH_SHORT).show();
    }
}

// Once image is taken, save to image view and then save to db as a ByteArray
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        photos = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(photos);
    }
}

// Get user input from editor and save item into database.
private void saveItem() {
    // Read from input fields
    // Use trim to eliminate leading or trailing white space
    String nameString = mNameEditText.getText().toString().trim();
    String priceString = mPriceEditText.getText().toString().trim();
    // Find quantity TV by id and extract int value as String
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_editor_text_view);
    String quantityString = quantityTextView.getText().toString();
    ImageView iconImage = (ImageView) findViewById(R.id.image_view_editor);

    // Check if this is supposed to be a new item and check if all the fields in the editor are blank
    if (mCurrentItemUri == null && TextUtils.isEmpty(nameString)
            && TextUtils.isEmpty(priceString) && TextUtils.isEmpty(quantityString) && iconImage == null) {
        // Since no fields were modified, we can return early without creating a new item.
        // No need to create ContentValues and no need to do any ContentProvider operations.
        return;
    }

    // Create a ContentValues object where column names are the keys and item attributes from the editor are the values.
    ContentValues values = new ContentValues();

    // Find image by the member variable "photos" and get the bytes
    byte[] bytes = Utils.getImageBytes(photos);
    values.put(ItemEntry.IMAGE_VIEW, bytes);

    values.put(ItemEntry.COLUMN_NAME, nameString);

    int price = 0;
    if (!TextUtils.isEmpty(priceString)) {
        price = Integer.parseInt(priceString);
    }
    values.put(ItemEntry.COLUMN_PRICE, price);

    values.put(ItemEntry.COLUMN_QUANTITY, quantityString);

    // Determine if this is a new or existing item by checking if mCurrentItemUri is null or not
    if (mCurrentItemUri == null) {
        // This is a NEW item, so insert a new item into the provider,
        // returning the content URI for the new item.
        Uri newUri = getContentResolver().insert(ItemEntry.CONTENT_URI, values);
        // Show a toast message depending on whether or not the insertion was successful.
        if (newUri == null) {
            // If the new content URI is null, then there was an error with insertion.
            Toast.makeText(this, getString(R.string.insert_item_failed), Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the insertion was successful and we can display a toast.
            Toast.makeText(this, getString(R.string.insert_item_successful), Toast.LENGTH_SHORT).show();
        }
    } else {
        // Otherwise this is an EXISTING item, so update the item with content URI: mCurrentItemUri
        // and pass in the new ContentValues. Pass in null for the selection and selection args
        // because mCurrentItemUri will already identify the correct row in the database that
        // we want to modify.
        int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
        // Show a toast message depending on whether or not the update was successful.
        if (rowsAffected == 0) {
            // If no rows were affected, then there was an error with the update.
            Toast.makeText(this, getString(R.string.edit_item_failed), Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the update was successful and we can display a toast.
            Toast.makeText(this, getString(R.string.edit_item_successful), Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

And the Utils file for the image methods:

```<code>public class Utils {

// Used in saveItem
// Adding the if/else statement here allows the picture to be null
// But now the picture disappears when you update an item without taking a new pic.
public static byte[] getImageBytes(Bitmap bitmap) {
    if (bitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    } else {
        return null;
    }
}

// Used in OnLoadFinished (Editor) and cursor adapter
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
</code>```

I'm fairly certain the issue lies in the saveItem method but let me know if you'd like to see the whole file.

答: The best approach for this work is that you should save image in phone directory which is accessible/not accessible from gallery as per your requirement and save the file path in the image column and you can access that image whenever it is required to load. I am also following the same approach in one of my offline applications which works smoothly without any problems but make sure whenever you perform delete option for any row then at that time you should also remove that file for better storage management.</p>

Title: Images wont stick in my database

Body:
I've been working on this issue for several days and I can't figure out what I'm doing wrong. I'm making an inventory/store app for a project where the user can input what items they have in stock into a list. As per the requirements I need to give it picture taking capability and I need to be able to save the picture in the SQLite database. That part I have achieved. But when I attempt to update an item and save it again to the list, the image returns null. I've attached pictures to visually explain...

Main activity

New item page

Save an item to the Main Activity listview

Click on an item to edit

Unless I take a new picture, when i save the updated item, the icon image returns null

I'm using a CursorLoader. I've treated the image the same way I treated all the other columns in the database... so I can't figure out why it won't stick.

Here's the code pertaining to images in EditorActivity:

Bitmap photos;

// Content URI for the existing item (null if it's a new item)
private Uri mCurrentItemUri;

// Picture taking capability with button
public void takePicture(View view) {
    PackageManager pm = this.getPackageManager();
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    } else {
        Toast.makeText(EditorActivity.this, "Sorry! You don't have a camera app.", Toast.LENGTH_SHORT).show();
    }
}

// Once image is taken, save to image view and then save to db as a ByteArray
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        photos = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(photos);
    }
}

// Get user input from editor and save item into database.
private void saveItem() {
    // Read from input fields
    // Use trim to eliminate leading or trailing white space
    String nameString = mNameEditText.getText().toString().trim();
    String priceString = mPriceEditText.getText().toString().trim();
    // Find quantity TV by id and extract int value as String
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_editor_text_view);
    String quantityString = quantityTextView.getText().toString();
    ImageView iconImage = (ImageView) findViewById(R.id.image_view_editor);

    // Check if this is supposed to be a new item and check if all the fields in the editor are blank
    if (mCurrentItemUri == null && TextUtils.isEmpty(nameString)
            && TextUtils.isEmpty(priceString) && TextUtils.isEmpty(quantityString) && iconImage == null) {
        // Since no fields were modified, we can return early without creating a new item.
        // No need to create ContentValues and no need to do any ContentProvider operations.
        return;
    }

    // Create a ContentValues object where column names are the keys and item attributes from the editor are the values.
    ContentValues values = new ContentValues();

    // Find image by the member variable "photos" and get the bytes
    byte[] bytes = Utils.getImageBytes(photos);
    values.put(ItemEntry.IMAGE_VIEW, bytes);

    values.put(ItemEntry.COLUMN_NAME, nameString);

    int price = 0;
    if (!TextUtils.isEmpty(priceString)) {
        price = Integer.parseInt(priceString);
    }
    values.put(ItemEntry.COLUMN_PRICE, price);

    values.put(ItemEntry.COLUMN_QUANTITY, quantityString);

    // Determine if this is a new or existing item by checking if mCurrentItemUri is null or not
    if (mCurrentItemUri == null) {
        // This is a NEW item, so insert a new item into the provider,
        // returning the content URI for the new item.
        Uri newUri = getContentResolver().insert(ItemEntry.CONTENT_URI, values);
        // Show a toast message depending on whether or not the insertion was successful.
        if (newUri == null) {
            // If the new content URI is null, then there was an error with insertion.
            Toast.makeText(this, getString(R.string.insert_item_failed), Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the insertion was successful and we can display a toast.
            Toast.makeText(this, getString(R.string.insert_item_successful), Toast.LENGTH_SHORT).show();
        }
    } else {
        // Otherwise this is an EXISTING item, so update the item with content URI: mCurrentItemUri
        // and pass in the new ContentValues. Pass in null for the selection and selection args
        // because mCurrentItemUri will already identify the correct row in the database that
        // we want to modify.
        int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
        // Show a toast message depending on whether or not the update was successful.
        if (rowsAffected == 0) {
            // If no rows were affected, then there was an error with the update.
            Toast.makeText(this, getString(R.string.edit_item_failed), Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the update was successful and we can display a toast.
            Toast.makeText(this, getString(R.string.edit_item_successful), Toast.LENGTH_SHORT).show();
        }
    }
}

And the Utils file for the image methods:

public class Utils {

// Used in saveItem
// Adding the if/else statement here allows the picture to be null
// But now the picture disappears when you update an item without taking a new pic.
public static byte[] getImageBytes(Bitmap bitmap) {
    if (bitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    } else {
        return null;
    }
}

// Used in OnLoadFinished (Editor) and cursor adapter
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}

I'm fairly certain the issue lies in the saveItem method but let me know if you'd like to see the whole file.


来源: stackexchange

问:
How to pick top value from tie-break group using Unix sort
I have the following text file:

```<code>$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20
</code>```

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

```<code>foo,a,20
foo,b,50
bar,c,33
</code>```

I'm stuck with this:

```<code>$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33
</code>```

Whats the right way to do it?

答:
awk smauk

PURE BASH!!

```<code>regex=',(.+),'
var="xx"
for line in $(sort -t, -k2,2 -k3,3nr myfile.txt); do
  if [[ $line =~ $regex ]]; then
    bashrematch=${BASH_REMATCH[1]}
    if [[ "$var" != "$bashrematch" ]]; then
      var=$bashrematch
      echo $line
    fi
  fi
done
foo,a,20
foo,b,50
bar,c,33
</code>```

just to compress and shrink the code a bit

```<code>r=',(.+),'; v=""; for l in $(sort -t, -k2,2 -k3,3nr myfile.txt); do [[ $l =~ $r ]] && b=${BASH_REMATCH[1]} && [ "$v" != "$b" ] && v=$b && echo $l; done
foo,a,20
foo,b,50
bar,c,33
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following text file:

$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

foo,a,20
foo,b,50
bar,c,33

I'm stuck with this:

$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33

Whats the right way to do it?

Body:
awk smauk

PURE BASH!!

regex=',(.+),'
var="xx"
for line in $(sort -t, -k2,2 -k3,3nr myfile.txt); do
  if [[ $line =~ $regex ]]; then
    bashrematch=${BASH_REMATCH[1]}
    if [[ "$var" != "$bashrematch" ]]; then
      var=$bashrematch
      echo $line
    fi
  fi
done
foo,a,20
foo,b,50
bar,c,33

just to compress and shrink the code a bit

r=',(.+),'; v=""; for l in $(sort -t, -k2,2 -k3,3nr myfile.txt); do [[ $l =~ $r ]] && b=${BASH_REMATCH[1]} && [ "$v" != "$b" ] && v=$b && echo $l; done
foo,a,20
foo,b,50
bar,c,33


问:
how to include google analytics in php web service
I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.

webservice in php:

```<code><?php
   require_once('lib/nusoap.php'); // basic include.. must go at the top

   $SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.

   $server = new soap_server(); // the soap object from the include above.

   // this has many input parameters but we only need two: the service name and the namespace
   $server->configureWSDL('Service', $SERVICE_NAMESPACE);

    $server->register('test',// method name
        array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
        array('return' => 'xsd:string'),// output - one string is returned called "return"
        $SERVICE_NAMESPACE,// namespace
        $SERVICE_NAMESPACE . '#hello1',// soapaction
        'rpc',// style.. remote procedure call
        'encoded',// use of the call
        'Nada interesante'// documentation for people who hook into your service.
    );

    function test($sName,$sName99)
    {
        return 'TEST ';
    }

    //This processes the request and returns a result.
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
    $server->service($HTTP_RAW_POST_DATA);
?>
</code>```

I want to have google analytics info and for that i want to integrate the following script:

```<code><script async src="https://www.googletagmanager.com/gtag/js?id=UA-89356985-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('config', 'UA-89356985-1');
</script>
</code>```

I don't know how to integrate in the test function. I want to know when the users calls the test function.

Thanks in advance very much.

答:
You cannot use the Javascript tracker unless your PHP script produces HTML and Javascript that is executed in a browser.

You can however use the Measurement Protocol to make server side calls to Google Analytics. That's basically an endpoint where you send predefined parameters with your custom values (via any method that can make http calls) and  they will register in Google Analytics.

Body:
I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.

webservice in php:

<?php
   require_once('lib/nusoap.php'); // basic include.. must go at the top

   $SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.

   $server = new soap_server(); // the soap object from the include above.

   // this has many input parameters but we only need two: the service name and the namespace
   $server->configureWSDL('Service', $SERVICE_NAMESPACE);

    $server->register('test',// method name
        array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
        array('return' => 'xsd:string'),// output - one string is returned called "return"
        $SERVICE_NAMESPACE,// namespace
        $SERVICE_NAMESPACE . '#hello1',// soapaction
        'rpc',// style.. remote procedure call
        'encoded',// use of the call
        'Nada interesante'// documentation for people who hook into your service.
    );

    function test($sName,$sName99)
    {
        return 'TEST ';
    }

    //This processes the request and returns a result.
    $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
    $server->service($HTTP_RAW_POST_DATA);
?>

I want to have google analytics info and for that i want to integrate the following script:

I don't know how to integrate in the test function. I want to know when the users calls the test function.

Thanks in advance very much.


问:
"search for" in top left of intellij
Really quick question. I sometimes hit some random hotkey in IntelliJ and it screws up my typing and starts typing in some "search for: " box in the top left near where the top-left of the project view usually is. What hotkey does this? No matter how much I backspace, the box will disappear but once I start typing again I will only type in this weird box.

The only way I've ever fixed this is by closing and restarting IntelliJ. As you can see, even if I press escape and close it, it still pops up when I start typing again.

答:
This is an incremental search. The key mapping for this will vary according to each user's preferences.

Here's a screenshot, showing that my kep mapping is CTRL j

You'll find your key mapping under Preferences > Keymap > Other > Incremental Search.

You can remove / stop the incremental search by hitting ESC.

Title: "search for" in top left of intellij


问:
Excel cell default measure unit
What is the default measurement unit of Excel cell size? Is it Point or Pixel or Millimeter ?

By default, excel cell Row height is 15, what is the meaning of this value? Is it 15 Pixels or 15 Points

By default, excel cell Column Width is 8.43, what is the meaning of this value? Is it 8.43 Pixels or 8.43 Points

If both row and column units are same, then Row height should be smaller than to column width. But the measurement is reverse, row height shows bigger number than column width. In Cell appearance also, row is small than column width.

I need to create box with Height 90 mm (millimeter) and  Width 195 mm (millimeter). Please let me know what are values to be put in Row and Column textboxes.

Thanks in advance.

答:
As per the Microsoft documentation....

You can specify a row height of 0 (zero) to 409. This value represents the height measurement in points (1 point equals approximately 1/72 inch or 0.035 cm). The default row height is 12.75 points (approximately 1/6 inch or 0.4 cm). If a row has a height of 0 (zero), the row is hidden.

Read it more here.

Title: Excel cell default measure unit


问:
Delegate returning nil
I'm trying to use a protocol / delegate in swift, and while I'm not getting any errors it seems that my delegate is not being created.

Here is my code

Class 1

```<code>import UIKit

protocol GameViewSliding{
    func slideGameView()
}

class GameDetailsViewController: UIViewController {

    var delegate:GameViewSliding?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func showOptions(sender: AnyObject) {

        println("button pressed")
        println(delegate)
        delegate?.slideGameView()
    }

}
</code>```

Class 2 that conforms to the protocol

```<code>import UIKit

var currentHoleNumber:Int = 0
var parThree = false;
var parFive = false;

class GameViewController: UIViewController,  GameViewSliding{

var gameDetailsVC:GameDetailsViewController = GameDetailsViewController()
    override func viewDidLoad() {
        super.viewDidLoad()

        println("inside the game class")
        gameDetailsVC.delegate = self
    }

    func slideGameView(){
        println("this is from the root controller")
    }

}
</code>```

The delegate comes back nil, which is why I never get the println from Class2, just not sure why it's nil.

答:
I noticed that there are some issues when setting the delegate up when using SplitViewController. The detailVC from the splitViewController can be acquired like so:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let detailNavigationController = splitViewController?.viewControllers[1] as! UINavigationController
    let detailVC = detailNavigationController.topViewController as! DetailViewController

    detailVC.delegate = self
}
</code>```

Another way is to set the delegate in the AppDelegate, the lines following after the SplitViewController is configured:

```<code>let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let masterVC = masterNavigationController.topViewController as! MasterViewController
let detailNavigationController = splitViewController.viewControllers[1] as! UINavigationController
let detailVC = detailNavigationController.topViewController as! DetailViewController

detailVC.delegate = masterVC
</code>```

Title: Delegate returning nil

Body:
I'm trying to use a protocol / delegate in swift, and while I'm not getting any errors it seems that my delegate is not being created.

Here is my code

Class 1

import UIKit

protocol GameViewSliding{
    func slideGameView()
}

class GameDetailsViewController: UIViewController {

    var delegate:GameViewSliding?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func showOptions(sender: AnyObject) {

        println("button pressed")
        println(delegate)
        delegate?.slideGameView()
    }

}

Class 2 that conforms to the protocol

import UIKit

var currentHoleNumber:Int = 0
var parThree = false;
var parFive = false;

class GameViewController: UIViewController,  GameViewSliding{

var gameDetailsVC:GameDetailsViewController = GameDetailsViewController()
    override func viewDidLoad() {
        super.viewDidLoad()

        println("inside the game class")
        gameDetailsVC.delegate = self
    }

    func slideGameView(){
        println("this is from the root controller")
    }

}

The delegate comes back nil, which is why I never get the println from Class2, just not sure why it's nil.

Body:
I noticed that there are some issues when setting the delegate up when using SplitViewController. The detailVC from the splitViewController can be acquired like so:

override func viewDidLoad() {
    super.viewDidLoad()
    let detailNavigationController = splitViewController?.viewControllers[1] as! UINavigationController
    let detailVC = detailNavigationController.topViewController as! DetailViewController

    detailVC.delegate = self
}

Another way is to set the delegate in the AppDelegate, the lines following after the SplitViewController is configured:

let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let masterVC = masterNavigationController.topViewController as! MasterViewController
let detailNavigationController = splitViewController.viewControllers[1] as! UINavigationController
let detailVC = detailNavigationController.topViewController as! DetailViewController

detailVC.delegate = masterVC


问:
Move function outside class definition
I am trying to enhance the readability of my library which features a matrix class. In particular I want users to get a direct overview when looking at the class definition. Therefore I am moving the actual functions outside of the definition. However, I appear to be unsuccessful for the copy constructor. In particular I don't succeed to define the templates correctly.

A minimal example (featuring the functions outside the class definition) is the following:

```<code>#include <vector>

template<class X>
class matrix
{
private:
  std::vector<X> m_data;

public:
  matrix(){};
  matrix(size_t n);
  X& operator[](size_t i);
  size_t size();

  template<\
    typename U,typename V=X,\
    typename=typename std::enable_if<std::is_convertible<X,U>::value>::type\
  >
  operator matrix<U> ()
  {
    matrix<U> out(size());

    for ( size_t i = 0 ; i < size() ; ++i )
      out[i] = static_cast<U>( m_data[i] );

    return out;
  }

};

template<class X>
matrix<X>::matrix(size_t n)
{
  m_data.resize(n);
}

template<class X>
X& matrix<X>::operator[](size_t i)
{
  return m_data[i];
}

template<class X>
size_t matrix<X>::size()
{
  return m_data.size();
}

int main()
{
  matrix<double> A(3);

  matrix<int> B = A;
}
</code>```

答:
Assuming your question refers to the conversion operator template ( you only have the implicit copy costructor there ), the syntax to move out a member template requires the specification of both template-parameters ( class first, without defaults ), hence:

```<code>template<class X>
template<typename U,typename V,typename E>
matrix<X>::operator matrix<U> ()
{
  //...
</code>```

Title: Move function outside class definition

Body:
I am trying to enhance the readability of my library which features a matrix class. In particular I want users to get a direct overview when looking at the class definition. Therefore I am moving the actual functions outside of the definition. However, I appear to be unsuccessful for the copy constructor. In particular I don't succeed to define the templates correctly.

A minimal example (featuring the functions outside the class definition) is the following:

#include <vector>

template<class X>
class matrix
{
private:
  std::vector<X> m_data;

public:
  matrix(){};
  matrix(size_t n);
  X& operator[](size_t i);
  size_t size();

  template<\
    typename U,typename V=X,\
    typename=typename std::enable_if<std::is_convertible<X,U>::value>::type\
  >
  operator matrix ()
  {
    matrix out(size());

    for ( size_t i = 0 ; i < size() ; ++i )
      out[i] = static_cast( m_data[i] );

    return out;
  }

};

template<class X>
matrix<X>::matrix(size_t n)
{
  m_data.resize(n);
}

template<class X>
X& matrix<X>::operator[](size_t i)
{
  return m_data[i];
}

template<class X>
size_t matrix<X>::size()
{
  return m_data.size();
}

int main()
{
  matrix<double> A(3);

  matrix<int> B = A;
}

Body:
Assuming your question refers to the conversion operator template ( you only have the implicit copy costructor there ), the syntax to move out a member template requires the specification of both template-parameters ( class first, without defaults ), hence:

template<class X>
template<typename U,typename V,typename E>
matrix<X>::operator matrix<U> ()
{
  //...


问:
Angular material dialog box is not showing properly
I want to popup a dialogue box on form submission, I added dialogue box components into my component class and invoked dialog box method in form submit method. but the dialogue box is not showing up properly instead only a white small box is appearing in its place. I have added its dependencies in app.module file and added the entry component as well. it is the code:</p>

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';

@Component({
  selector: 'dialog-overview-example',
  template: ''
})
export class DialogOverviewExample {

    animal: string;
    name: string;

    constructor(public dialog: MdDialog) { this.animal = 'tiger'; this.name = 'ali';}

    openDialog(): void {
      let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
        width: '250px',
        data: { name: this.name, animal: this.animal }
      });

      dialogRef.afterClosed().subscribe(result => {
        console.log('The dialog was closed');
        this.animal = result;
      });
    }

  }
@Component({
  selector: 'dialog-overview-example-dialog',
  template: '',
})
export class DialogOverviewExampleDialog {

    constructor(
      public dialogRef: MdDialogRef<DialogOverviewExampleDialog>,
      @Inject(MD_DIALOG_DATA) public data: any) { }

    onNoClick(): void {
      this.dialogRef.close();
    }

  }

@Component({
  selector: 'my-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  constructor(public dialog: MdDialog){}

  confirmForm(){
    let dialogueBox: DialogOverviewExample = new DialogOverviewExample(this.dialog);
    dialogueBox.openDialog();
  }

  onSubmit(){
    this.confirmForm();
    let formControls = JSON.stringify(this.reviewForm.value.controlArray);
    this.formService.createForm(formControls)
      .subscribe(
        data => console.log(data),
        error => console.error(error)
    );
    this.reviewForm.reset();
  }
}
</code>```

答: It's because your template: '', is empty, if you want to fill the dialog box with something, you should specify any HTML for it, otherwise, it will be empty, as in your case.

Body:
I want to popup a dialogue box on form submission, I added dialogue box components into my component class and invoked dialog box method in form submit method. but the dialogue box is not showing up properly instead only a white small box is appearing in its place. I have added its dependencies in app.module file and added the entry component as well. it is the code:

import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';

@Component({
  selector: 'dialog-overview-example',
  template: ''
})
export class DialogOverviewExample {

    animal: string;
    name: string;

    constructor(public dialog: MdDialog) { this.animal = 'tiger'; this.name = 'ali';}

    openDialog(): void {
      let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
        width: '250px',
        data: { name: this.name, animal: this.animal }
      });

      dialogRef.afterClosed().subscribe(result => {
        console.log('The dialog was closed');
        this.animal = result;
      });
    }

  }
@Component({
  selector: 'dialog-overview-example-dialog',
  template: '',
})
export class DialogOverviewExampleDialog {

    constructor(
      public dialogRef: MdDialogRef<DialogOverviewExampleDialog>,
      @Inject(MD_DIALOG_DATA) public data: any) { }

    onNoClick(): void {
      this.dialogRef.close();
    }

  }

@Component({
  selector: 'my-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  constructor(public dialog: MdDialog){}

  confirmForm(){
    let dialogueBox: DialogOverviewExample = new DialogOverviewExample(this.dialog);
    dialogueBox.openDialog();
  }

  onSubmit(){
    this.confirmForm();
    let formControls = JSON.stringify(this.reviewForm.value.controlArray);
    this.formService.createForm(formControls)
      .subscribe(
        data => console.log(data),
        error => console.error(error)
    );
    this.reviewForm.reset();
  }
}


问:
Sizeof unsigned int array
```<code>int main() {

    unsigned __int8 counts[5] = { 0, 0, 0, 0, 0};
    sizeof(counts) //Prints 5
    Func(counts);

}

void Func(unsigned __int8 counts[]){
   sizeof(counts) //Prints 4
}
</code>```

<p>Could someone explain why sizeof prints two different values for the same array? </p>

答:
You're passing the array by value and not by reference, this means the pointer is being copied and returning the size of that, rather than the array itself.

Change your function to pass by reference or pointer.

See this answer for more help: What is array decaying?

Title: Sizeof unsigned int array

Body:
int main() {

    unsigned __int8 counts[5] = { 0, 0, 0, 0, 0};
    sizeof(counts) //Prints 5
    Func(counts);

}

void Func(unsigned __int8 counts[]){
   sizeof(counts) //Prints 4
}

Could someone explain why sizeof prints two different values for the same array?


问:
using DbPerTenantConnectionStringResolver
using core boilerplate framework 3.3.2 (latest doco i could see was for 3.2.1).

So i'm attempting to implement as db/tenant configuration.

To my delight I saw there was actually a class called DbPerTenantConnectionStringResolver - fantastic!

In my EntityFrameworkModule I add to the override PreInitialize() method by adding the following line:

```<code>Configuration.ReplaceService<IConnectionStringResolver, DbPerTenantConnectionStringResolver>(DependencyLifeStyle.Transient);
</code>```

However this does not compile:

```<code>The non-generic method 'IAbpStartupConfiguration.ReplaceService(Type, Action)'

cannot be used with type arguments  CCRE.EntityFrameworkCore
</code>```

Hopefully somebody can set me on the right track...

答:
Add the following namespace:

using Abp.Configuration.Startup;
```

<p>That accesses this extension method:</p>

<pre class="lang-cs prettyprint-override"><code>public static void ReplaceService<TType, TImpl>(this IAbpStartupConfiguration configuration, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
    where TType : class
    where TImpl : class, TType
{
    configuration.ReplaceService(typeof(TType), () =>
    {
        configuration.IocManager.Register<TType, TImpl>(lifeStyle);
    });
}
</code>```

Body:
using core boilerplate framework 3.3.2 (latest doco i could see was for 3.2.1).

So i'm attempting to implement as db/tenant configuration.

To my delight I saw there was actually a class called DbPerTenantConnectionStringResolver - fantastic!

In my EntityFrameworkModule I add to the override PreInitialize() method by adding the following line:

Configuration.ReplaceService<IConnectionStringResolver, DbPerTenantConnectionStringResolver>(DependencyLifeStyle.Transient);

However this does not compile:

The non-generic method 'IAbpStartupConfiguration.ReplaceService(Type, Action)'

cannot be used with type arguments  CCRE.EntityFrameworkCore

Hopefully somebody can set me on the right track...

Body:
Add the following namespace:

using Abp.Configuration.Startup;

That accesses this extension method:

public static void ReplaceService<TType, TImpl>(this IAbpStartupConfiguration configuration, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton)
    where TType : class
    where TImpl : class, TType
{
    configuration.ReplaceService(typeof(TType), () =>
    {
        configuration.IocManager.Register<TType, TImpl>(lifeStyle);
    });
}


问:
sbt set java options in Dynamic Task
I am trying to write task which takes input argument, pass it to testOnly task and execute. It works perfectly, but I cannot set system propertis in this task, which will be visible in test. This properties should not affect other tasks and should be visible only in this custom task.

Here is my code sample

```<code>lazy val myTestOnly = InputKey[Unit]("myTestOnly", "test only with special sys prop")

val myTestOnlyTask = myTestOnly := {
  Def.inputTaskDyn {
    val args: Seq[String] = spaceDelimited("").parsed

    javaOptions in Test ++= Seq("-Dfoo=bar") // does not work
    testOptions += Tests.Setup(() => System.setProperty("foo", "bar")) //does not work
    System.setProperty("foo", "bar") // does not work

    (testOnly in Test).toTask(" " + args.head)
  }.evaluated
}
</code>```

When I run in sbt console

```<code> myTestOnly com.sampleTest
</code>```

testOnly executes but "foo" property is not visible

So the qustion is how to set property in task definition which will be visible in test runtime only for current task?

答:
in build.sbt:

```<code>val currentTimestamp: String =
  new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
val targetDir
  : String = baseDirectory + "/project/target/mtd/" + currentTimestamp

javaOptions in Test ++= Seq("-Ddynamic_dir_to_set=" + targetDir)
</code>```

and sbt test will have guaranteed value for the dynamic_dir_to_set env var.

Couple of theory links to go trough:

http://www.scala-sbt.org/0.13.2/docs/Detailed-Topics/Forking.html#change-working-directory
http://www.scala-sbt.org/0.13/docs/Plugins-and-Best-Practices.html

Title: sbt set java options in Dynamic Task

Body:
I am trying to write task which takes input argument, pass it to testOnly task and execute. It works perfectly, but I cannot set system propertis in this task, which will be visible in test. This properties should not affect other tasks and should be visible only in this custom task.

Here is my code sample

lazy val myTestOnly = InputKey[Unit]("myTestOnly", "test only with special sys prop")

val myTestOnlyTask = myTestOnly := {
  Def.inputTaskDyn {
    val args: Seq[String] = spaceDelimited("").parsed

    javaOptions in Test ++= Seq("-Dfoo=bar") // does not work
    testOptions += Tests.Setup(() => System.setProperty("foo", "bar")) //does not work
    System.setProperty("foo", "bar") // does not work

    (testOnly in Test).toTask(" " + args.head)
  }.evaluated
}

When I run in sbt console

 myTestOnly com.sampleTest

testOnly executes but "foo" property is not visible

So the qustion is how to set property in task definition which will be visible in test runtime only for current task?

Body:
in build.sbt:

val currentTimestamp: String =
  new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())
val targetDir
  : String = baseDirectory + "/project/target/mtd/" + currentTimestamp

javaOptions in Test ++= Seq("-Ddynamic_dir_to_set=" + targetDir)

and sbt test will have guaranteed value for the dynamic_dir_to_set env var.

Couple of theory links to go trough:

http://www.scala-sbt.org/0.13.2/docs/Detailed-Topics/Forking.html#change-working-directory
http://www.scala-sbt.org/0.13/docs/Plugins-and-Best-Practices.html


问:
Lodash reject get return object
```<code>var obj = {a: [], b: [1,2], c: [], d: [1]};
</code>```

How do I get a non-empty array of objects like the following:

```<code>{b: [1,2], d: [1]}
</code>```

答:
Right now, Lodash has a method called _.omit that does exactly what you need:

```<code>> const object = {a: 1, b: 2, c: 3, d: 4}
undefined
> _.omit(object, ['a', 'c'])
{ b: 2, d: 4 }
</code>```

Title: Lodash reject get return object

Body:
var obj = {a: [], b: [1,2], c: [], d: [1]};

How do I get a non-empty array of objects like the following:

{b: [1,2], d: [1]}

Body:
Right now, Lodash has a method called _.omit that does exactly what you need:

> const object = {a: 1, b: 2, c: 3, d: 4}
undefined
> _.omit(object, ['a', 'c'])
{ b: 2, d: 4 }


问:
ProgressDialog won't dismiss, on redirected url
i already created  simple webview with progress dialog, what's in my question is when url got redirected progress dialog wont dismiss. for example : i'm open url like : www.myweb.com/account. then it redirect to : www.myweb.com/login. any solution to handle this?</p>

```<code>//progress dialog
    ProgressDialog loading;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        loading= new ProgressDialog(MainActivity.this, R.style.MyAlertDialogStyle);
        loading.setMessage("Sedang Memuat...");
        loading.setCancelable(false);
        loading.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
            if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);
    }
</code>```

答:
I don't think that onPageFinished is getting called on each redirect, it maybe due to the use of Iframe or something else. I think you should override onProgressChanged in WebChromeClient like this:

```<code>myWebView.setWebChromeClient(new WebChromeClient(){

        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

           if(newProgress <100){
            prDialog.setMessage("Please wait ...");
            prDialog.show();
        }

          else if (newProgress ==100){
               if(prDialog!=null && prDialog.isShowing()){
                  prDialog.dismiss();
        }
       }
    }
</code>```

Body:
i already created  simple webview with progress dialog, what's in my question is when url got redirected progress dialog wont dismiss. for example : i'm open url like : www.myweb.com/account. then it redirect to : www.myweb.com/login. any solution to handle this?

//progress dialog
    ProgressDialog loading;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        loading= new ProgressDialog(MainActivity.this, R.style.MyAlertDialogStyle);
        loading.setMessage("Sedang Memuat...");
        loading.setCancelable(false);
        loading.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
            if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);
    }

Body:
I don't think that onPageFinished is getting called on each redirect, it maybe due to the use of Iframe or something else. I think you should override onProgressChanged in WebChromeClient like this:

myWebView.setWebChromeClient(new WebChromeClient(){

        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

           if(newProgress <100){
            prDialog.setMessage("Please wait ...");
            prDialog.show();
        }

          else if (newProgress ==100){
               if(prDialog!=null && prDialog.isShowing()){
                  prDialog.dismiss();
        }
       }
    }


问:
html parser for php?

Possible Duplicate:

  Best methods to parse HTML

  How to get href from anchor tag with particular class

hi guys,

I need an html parser. Baiscally given an html in a string i need to extract every href of

Which html parser for php do u suggest me? Someone that handles wrong html too.

Thanks

答:
I would recommend using DOMDocument, it's often (always?) compiled with PHP 5.

You can use DOMXpath for extracting all href attributes.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5

Title: html parser for php?


问:
Uncaught ReferenceError: models is not defined in the html file in a backbone.js application
demo.js

```<code>var CommentsCollection = Backbone.Collection.extend({

    url : "http://0.0.0.0:8080/"

});

var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var that = this;
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            success: () => {
                    var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });

                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(models));
            }
        })
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home'
    }
});

Backbone.history.start();
</code>```

index.html

```<code><html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>Top posts</h1>
        <hr />
        <div class="page"></div>
    </div>

    <script type="text/template" id="reddit-comments-template">
        <table class = "comments table">
            <thead>
                <tr>
                    <th>Row</th>
                    <th>Commments</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(models){ %>
                    <tr>
                        <td><%= models.get('firstname') %></td>
                        <td><%= models.get('lastname') %></td>
                        <td><%= models.get('id') %></td>
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="demo.js"></script>

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

Actually if you see, I tried some getting some data from the api and updating the view according to the changes in the data, the collection gets the data from the api and then I get the models of the collection to loop over the data from the model, the variables in the models get printed in the log I added in the js script in the comments as you can see but I guess the value is not passed to the html file, giving rise to that error. Can you please tell me how to correct it.

答:
You can convert the collection to json and pass it to template and access the models. In this way you can iterate through models using _.each and render their attributes in template.

```<code>var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var context = {};
        this.commentsCollection = new CommentsCollection();
        this.commentsCollection.fetch({
            success: () => {
                    //var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });
                  context['models'] = this.commentsCollection.toJSON()
                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(context));
            }
        })
    }
});
</code>```

Template:

```<code><html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>Top posts</h1>
        <hr />
        <div class="page"></div>
    </div>

    <script type="text/template" id="reddit-comments-template">
        <table class = "comments table">
            <thead>
                <tr>
                    <th>Row</th>
                    <th>Commments</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(model){ %>
                    <tr>
                        <td><%= model.firstname %>
                        <td><%= model.lastname %></td>
                        <td><%= model.id %></td>
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="demo.js"></script>

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

Body:
demo.js

var CommentsCollection = Backbone.Collection.extend({

    url : "http://0.0.0.0:8080/"

});

var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var that = this;
        var commentsCollection = new CommentsCollection();
        commentsCollection.fetch({
            success: () => {
                    var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });

                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(models));
            }
        })
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home'
    }
});

Backbone.history.start();

index.html

    <title> </title>

Top posts

Actually if you see, I tried some getting some data from the api and updating the view according to the changes in the data, the collection gets the data from the api and then I get the models of the collection to loop over the data from the model, the variables in the models get printed in the log I added in the js script in the comments as you can see but I guess the value is not passed to the html file, giving rise to that error. Can you please tell me how to correct it.

Body:
You can convert the collection to json and pass it to template and access the models. In this way you can iterate through models using _.each and render their attributes in template.

var CommentsListView = Backbone.View.extend({

    el: '.page',

    render : function(){
        var context = {};
        this.commentsCollection = new CommentsCollection();
        this.commentsCollection.fetch({
            success: () => {
                    //var models = commentsCollection.models;
                    // _.each(models, function(models){
                    //  console.log(models.get('firstname'));
                    // });
                  context['models'] = this.commentsCollection.toJSON()
                  var template = _.template($('#reddit-comments-template').html());
                  that.$el.html(template(context));
            }
        })
    }
});

Template:

<html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>Top posts</h1>
        <hr />
        <div class="page"></div>
    </div>

    <script type="text/template" id="reddit-comments-template">
        <table class = "comments table">
            <thead>
                <tr>
                    <th>Row</th>
                    <th>Commments</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(model){ %>
                    <tr>
                        <td><%= model.firstname %>
                        <td><%= model.lastname %></td>
                        <td><%= model.id %></td>
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="demo.js"></script>

</body>
</html>


问:
InputSplits in mapreduce
I have just started learning Mapreduce and have some queries I want answers to. Here goes:

1) Case 1: FileInputFormat as  Input format. A directory having multiple files to be processed is the Input Path. If I have n files, all of the files lesser than the block size in the hadoop cluster, How many splits are calculated for the map reduce Job?

2) I extend FileInputFormat in a class called MyFileInputFormat, and I override isSplitable to always return false. The input configuration is same as above. Will I get n splits in this case?

3) If say 1 of the files among the n files is slightly larger than the cluster's block size will I get n+1 splits in the second case?

Thanks in advance for the help!

答:
Lets start with Basics of FileInputFormat

FileInputFormat is Abstract hence you cannot use it directly.
"public abstract class FileInputFormat"

Lets assume you use a InputFormat like TextInputFormat (class TextInputFormat extends FileInputFormat) and answer your question.

The splitMethod logic in FileInputFormat  is applicable per file in the input path hence you will have "N" splits in MapReduce jobs (Case1).

For Case2 you will still have N splits , as you have just informed the inputformat to not split individual files. But for each file consider that as one split.

For Case 3 you will still have N splits as the files are not being split. Do remember the split logic is applied to individual file and not considering them together.

CombineInputFormat is what is used if you want to combine inputfiles during the split logic.

Title: InputSplits in mapreduce


问:
Python Riemann Sum does not yield zero for equal positive and negative areas
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

```<code>import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()
</code>```

答: Your code seems to be valid to me. It sums the y returned by f_x, and accounts for the approximation error of having only 1000 subintervals by adding delta_x to the second argument of arange. Unfortunately, I think that roundoff error is at play here.

Body:
I wrote a program to approximate an integral using a Riemann sum and graph it using matplotlib in Python. For functions with equal areas above and below the x-axis, the resulting area should be zero, but my program outputs a very small number instead.

The following code graphs the odd function f(x) = x^3 from -1 to 1, so the area should be zero. My code instead approximates it to be 1.68065561477562 e^-15.

What is causing this? Is it a rounding error in delta_x, x, or y? I know I could just round the value to zero, but I'm wondering if there is another problem or way to solve this.

I have tried using the Decimal.decimal class for delta_x, but I just got an even smaller number.

The Python code:

import matplotlib.pyplot as plt
import numpy as np

# Approximates and graphs integral using Riemann Sum

# example function: f(x) = x^3
def f_x(x):
    return x**3

# integration range from a to b with n rectangles
a, b, n = -1, 1, 1000

# calculate delta x, list of x-values, list of y-values, and approximate area under curve
delta_x = (b - a) / n

x = np.arange(a, b+delta_x, delta_x)

y = [f_x(i) for i in x]

area = sum(y) * delta_x

# graph using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.bar(x, y, delta_x, alpha=.5)
plt.title('a={}, b={}, n={}'.format(a, b, n))
plt.xlabel('A = {}'.format(area))
plt.show()


问:
Symfony 3 modal
why my modal don't appears when I clik in my link?
I do like this and I don't know where is wrong?

In my table, my Edit button is a dropdown button because I have two Entity joined in this table, so when I click in the link who edited one of my entity the modal don't appears, the page becomes fade only.

edit.html.twig

```<code><a data-toggle="modal" href="#edit{{ fruit.id }}">
    Edit
</a>
<div class="modal" id="edit{{ fruit.id }}">
    {{ form_start(edit_form, { 'method' : 'post', 'action': path('fruit_edit', { 'id' : fruit.id }) }) }}
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
            <h4 class="modal-title">Edit</h4>
        </div>
        <div class="modal-body">
            {{ form_widget(edit_form) }}
            <input type="submit" value="Edit" />
        </div>
    </div>
    {{ form_end(edit_form) }}
</div>
</code>```

index.html.twig

```<code><td>
<div class="dropdown">
    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">
        <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
    </button>
    <ul class="dropdown-menu">
        <li>{{ render(controller('AppBundle:Fruit:edit', { 'id' : fruit.id } )) }}</li>
        <li>href="#">Categories</a></li>
    </ul>
</div>
</code>```

Controller

```<code>public function editAction(Request $request, Fruit $fruit)
{
    $deleteForm = $this->createDeleteForm($fruit);
    $editForm = $this->createForm('AppBundle\Form\FruitType', $fruit);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('fruit_edit', array('id' => $fruit->getId()));
    }

    return $this->render('fruit/edit.html.twig', array(
        'fruit' => $fruit,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}
</code>```

Help me please to show what the problem, thanks!

答:
You can try just move your

 container outside the

 tag:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">

    </button>

                Edit

Categories

        <form>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

Edit

                    <input>
                    <input type="submit" value="Edit" />

        </form>

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

<p>So...</p>

<p>edit.html.twig</p>

```

    {{ form_start(edit_form, { 'method' : 'post', 'action': path('fruit_edit', { 'id' : fruit.id }) }) }}

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

Edit

            {{ form_widget(edit_form) }}
            <input type="submit" value="Edit" />

    {{ form_end(edit_form) }}

```

<p>index.html.twig</p>

```

    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">

    </button>

                Edit

href="#">Categories

    {{ render(controller('AppBundle:Fruit:edit', { 'id' : fruit.id } )) }}

```

Title: Symfony 3 modal

Body:
why my modal don't appears when I clik in my link?
I do like this and I don't know where is wrong?

In my table, my Edit button is a dropdown button because I have two Entity joined in this table, so when I click in the link who edited one of my entity the modal don't appears, the page becomes fade only.

edit.html.twig

    Edit

    {{ form_start(edit_form, { 'method' : 'post', 'action': path('fruit_edit', { 'id' : fruit.id }) }) }}

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

Edit

            {{ form_widget(edit_form) }}
            <input type="submit" value="Edit" />

    {{ form_end(edit_form) }}

index.html.twig

    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">

    </button>

{{ render(controller('AppBundle:Fruit:edit', { 'id' : fruit.id } )) }}

href="#">Categories

Controller

public function editAction(Request $request, Fruit $fruit)
{
    $deleteForm = $this->createDeleteForm($fruit);
    $editForm = $this->createForm('AppBundle\Form\FruitType', $fruit);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('fruit_edit', array('id' => $fruit->getId()));
    }

    return $this->render('fruit/edit.html.twig', array(
        'fruit' => $fruit,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

Help me please to show what the problem, thanks!

Body:
You can try just move your <div class="modal" ... ></div> container outside the <ul></ul> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<div class="dropdown">
    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">
        <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
    </button>
    <ul class="dropdown-menu">
        <li>
            <a data-toggle="modal" href="#edit5">
                Edit
            </a>
        </li>
        <li><a href="#">Categories</a></li>
    </ul>
    <div class="modal" id="edit5">
        <form>
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">Edit</h4>
                </div>
                <div class="modal-body">
                    <input>
                    <input type="submit" value="Edit" />
                </div>
            </div>
        </form>
    </div>
</div>

So...

edit.html.twig

<div class="modal" id="edit{{ fruit.id }}">
    {{ form_start(edit_form, { 'method' : 'post', 'action': path('fruit_edit', { 'id' : fruit.id }) }) }}
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">Edit</h4>
        </div>
        <div class="modal-body">
            {{ form_widget(edit_form) }}
            <input type="submit" value="Edit" />
        </div>
    </div>
    {{ form_end(edit_form) }}
</div>

index.html.twig

<td>
<div class="dropdown">
    <button class="btn btn-info dropdown-toggle btn-xs" type="button" data-toggle="dropdown">
        <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
    </button>
    <ul class="dropdown-menu">
        <li>
            <a data-toggle="modal" href="#edit{{ fruit.id }}">
                Edit
            </a>
        </li>
        <li>href="#">Categories</a></li>
    </ul>
    {{ render(controller('AppBundle:Fruit:edit', { 'id' : fruit.id } )) }}
</div>


答: This is the best tool I have tested to parse HTML and extract data.</p>

Title: html parser for php?

Body:
Possible Duplicate:

  Best methods to parse HTML

  How to get href from anchor tag with particular class

hi guys,

I need an html parser. Baiscally given an html in a string i need to extract every href of

Which html parser for php do u suggest me? Someone that handles wrong html too.

Thanks


问:
how to insert multiple lines in json array in database using php
I want to enter some details that included in JSON arrays to database.

Given below is my source code.

here is my data json array from the txt file

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

{

   "reader_name":"Biboy Pogi",
   "mac_address":"00:16:25:10:7E:85",
   "tag_reads":[

      {

         "antennaPort":1,
         "epc":"2015031687850100010105B5",
         "tid":"E280110520005A8B952F0886",
         "isHeartBeat":false
      }
   ]
}

答:
Assuming that you source data come in one json per row. You can do the iteration insert with the below sample code:</p>

```<code>$fn = 'debug.txt';
$raw = file_get_contents($fn);

$raw = explode("\r\n", $raw);
foreach($raw as $row){
    //force it to array for single item
    if (substr($row, 0, 1) != '[')
        $row = '[' . $row . ']';

    $data_arr= json_decode($row, true);

    foreach ($data_arr as $data){
        $reader_name = $data['reader_name'];
        $mac_address = $data['mac_address'];
        $antennaPort = $data['tag_reads'][0]['antennaPort'];
        $epc = $data['tag_reads'][0]['epc'];
        $tid = $data['tag_reads'][0]['tid'];

        $sql = "INSERT INTO tags(reader_name, mac_address, antennaPort, epc, tid)
        VALUES('$reader_name', '$mac_address', '$antennaPort', '$epc', '$tid')";

        if(!mysqli_query($con, $sql))
        {
            die('Error : ' . mysqli_error($con));
        }
    }
}
</code>```

Body:
Assuming that you source data come in one json per row. You can do the iteration insert with the below sample code:

$fn = 'debug.txt';
$raw = file_get_contents($fn);

$raw = explode("\r\n", $raw);
foreach($raw as $row){
    //force it to array for single item
    if (substr($row, 0, 1) != '[')
        $row = '[' . $row . ']';

    $data_arr= json_decode($row, true);

    foreach ($data_arr as $data){
        $reader_name = $data['reader_name'];
        $mac_address = $data['mac_address'];
        $antennaPort = $data['tag_reads'][0]['antennaPort'];
        $epc = $data['tag_reads'][0]['epc'];
        $tid = $data['tag_reads'][0]['tid'];

        $sql = "INSERT INTO tags(reader_name, mac_address, antennaPort, epc, tid)
        VALUES('$reader_name', '$mac_address', '$antennaPort', '$epc', '$tid')";

        if(!mysqli_query($con, $sql))
        {
            die('Error : ' . mysqli_error($con));
        }
    }
}


答:
Please throw this link: Microsoft reference

You can change and define this unit manually where pointed in above link:

On the File tab, click Options, click the Advanced category, and under Display, select an option from the Ruler Units list.

So please visit Here Microsoft reference that exactly explain
what you asked.

Above you asked are the pixel width retranslated into character units (based on the Normal font) for display.

Title: Excel cell default measure unit

Body:
What is the default measurement unit of Excel cell size? Is it Point or Pixel or Millimeter ?

By default, excel cell Row height is 15, what is the meaning of this value? Is it 15 Pixels or 15 Points

By default, excel cell Column Width is 8.43, what is the meaning of this value? Is it 8.43 Pixels or 8.43 Points

If both row and column units are same, then Row height should be smaller than to column width. But the measurement is reverse, row height shows bigger number than column width. In Cell appearance also, row is small than column width.

I need to create box with Height 90 mm (millimeter) and  Width 195 mm (millimeter). Please let me know what are values to be put in Row and Column textboxes.

Thanks in advance.


问:
How way i can do Two array use in a Loop
I have two array and i want to use it in a Loop How way i can do that

Controller Codes are:

```<code>public function showJobCategoryContent($id)
{
    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return [
            'created_at' => Carbon::parse($job->created_at)->addDays(30)->toDateTimeString()
        ];
    });

    $dates = [];
    $dates[] = $jobsInfoById->pluck('created_at');
    $jobsInfosById = [];
    $jobsInfosById[] = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return view('front.category-content.job-category-content',[
        'jobsInfosById'=> $jobsInfosById,
        'dates'=>$dates
    ]);
}
</code>```

How can I use this two array in a loop

My view page:

```<code>@php
    $arrayData = array_merge($jobsInfosById, $dates);
@endphp

@foreach($arrayData as $jobInfoById)
    <li>
        <h4>{{$jobInfoById->company_name}}</h4>
        <h5 class="deadline">Deadline:<b>{{ date('d F, Y', strtotime($jobInfoById->date)) }}</b></h5>
    </li>
@endforeach
</code>```

It shows an error Undefined property:

Illuminate\Pagination\LengthAwarePaginator::$company_name

{
$arrayData Value As Follows:

Array
(
    [0] => Illuminate\Pagination\LengthAwarePaginator Object
        (
            [total:protected] => 3
            [lastPage:protected] => 1
            [items:protected] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => 3

```<code>                                [company_name] => Khulan Computer house

                                [published] => 1
                                [created_at] => 2017-10-22 15:25:54
                                [updated_at] => 2017-10-24 11:00:52
                            )

                        [1] => stdClass Object
                            (
                                [id] => 4

                                [company_name] => Khulan Computer house

                                [published] => 1
                                [created_at] => 2017-10-22 15:46:44
                                [updated_at] => 2017-10-24 11:00:41
                            )

                        [2] => stdClass Object
                            (
                                [id] => 11

                                [company_name] => Computer Lab

                                [published] => 1
                                [created_at] => 2017-10-24 08:01:00
                                [updated_at] => 2017-10-24 10:53:57
                            )

                    )

            )

        [perPage:protected] => 3
        [currentPage:protected] => 1
        [path:protected] => http://localhost/jobs-zone/public/category-content/job-category-content/4
        [query:protected] => Array
            (
            )

        [fragment:protected] =>
        [pageName:protected] => page
    )

[1] => Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => 2017-11-21 15:25:54
                [1] => 2017-11-21 15:46:44
                [2] => 2017-11-23 08:01:00
            )

    )
</code>```

)[![enter image description here][1]][1]

[1]:

答:
You should try this:

Change your view code may be it returns array.

```<code>@foreach($arrayData as $jobInfoById)

    print('<pre style="color:red;">');
    print_r($jobInfoById);
    print('```');
    exit;

{{$jobInfoById['company_name']}}

Deadline:{{ date('d F, Y', strtotime($jobInfoById->date)) }}

@endforeach
```

Body:
I have two array and i want to use it in a Loop How way i can do that

Controller Codes are:

public function showJobCategoryContent($id)
{
    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return [
            'created_at' => Carbon::parse($job->created_at)->addDays(30)->toDateTimeString()
        ];
    });

    $dates = [];
    $dates[] = $jobsInfoById->pluck('created_at');
    $jobsInfosById = [];
    $jobsInfosById[] = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return view('front.category-content.job-category-content',[
        'jobsInfosById'=> $jobsInfosById,
        'dates'=>$dates
    ]);
}

How can I use this two array in a loop

My view page:

@php
    $arrayData = array_merge($jobsInfosById, $dates);
@endphp

@foreach($arrayData as $jobInfoById)

{{$jobInfoById->company_name}}

Deadline:{{ date('d F, Y', strtotime($jobInfoById->date)) }}

@endforeach

It shows an error Undefined property:

Illuminate\Pagination\LengthAwarePaginator::$company_name

{
$arrayData Value As Follows:

Array
(
    [0] => Illuminate\Pagination\LengthAwarePaginator Object
        (
            [total:protected] => 3
            [lastPage:protected] => 1
            [items:protected] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => 3

                                [company_name] => Khulan Computer house

                                [published] => 1
                                [created_at] => 2017-10-22 15:25:54
                                [updated_at] => 2017-10-24 11:00:52
                            )

                        [1] => stdClass Object
                            (
                                [id] => 4

                                [company_name] => Khulan Computer house

                                [published] => 1
                                [created_at] => 2017-10-22 15:46:44
                                [updated_at] => 2017-10-24 11:00:41
                            )

                        [2] => stdClass Object
                            (
                                [id] => 11

                                [company_name] => Computer Lab

                                [published] => 1
                                [created_at] => 2017-10-24 08:01:00
                                [updated_at] => 2017-10-24 10:53:57
                            )

                    )

            )

        [perPage:protected] => 3
        [currentPage:protected] => 1
        [path:protected] => http://localhost/jobs-zone/public/category-content/job-category-content/4
        [query:protected] => Array
            (
            )

        [fragment:protected] =>
        [pageName:protected] => page
    )

[1] => Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => 2017-11-21 15:25:54
                [1] => 2017-11-21 15:46:44
                [2] => 2017-11-23 08:01:00
            )

    )

)[![enter image description here][1]][1]

[1]:

Body:
You should try this:

Change your view code may be it returns array.

@foreach($arrayData as $jobInfoById)

    print('<pre style="color:red;">');
    print_r($jobInfoById);
    print('</pre>');
    exit;

    <li>
        <h4>{{$jobInfoById['company_name']}}</h4>
        <h5 class="deadline">Deadline:<b>{{ date('d F, Y', strtotime($jobInfoById->date)) }}</b></h5>
    </li>
@endforeach


问:
How to manipulate the database after a fatal error in CodeIgniter?
I'm trying to store in to the database diferent kind of errors and stranges behaviours in my Codeigniter. For these to not be an exception I would like to store php Fatal errors also. To archive this I proceded this way:

Created an override of the CI_Log class named MY_Log and stored it in application/core.
The code in that class looks like this:

```<code>class MY_Log extends CI_Log {

    public function __construct(){

        parent::__construct();

    }

    function write_log($level = 'error', $msg, $php_error = FALSE){

        $result = parent::write_log($level, $msg, $php_error);

        if((require_once APPPATH.'libraries/Utils.php')== TRUE){
            if ($result == TRUE && strtoupper($level) == 'ERROR') {

                $utils = new Utils();
                $message = "An error occurred: \n\n";
                $message .= $level.' - '.date($this->_date_fmt). ' --> '.$msg."\n";
                $utils->log_petition_if_required(date("Y-m-d H:i:s", time() + 86400), 0, "", 500, $message);
            }
        }

        return $result;

    }
}
</code>```

This class actually caches the error correctly and redirects the functionality towards the 'Utils' library just right.
The code in the library looks like this:

```<code>class Utils
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
    }
    public function log_petition_if_required($date_log, $user_id, $post_data, $http_code, $output){

        $date_now = date("Y-m-d H:i:s");
        if(!empty($date_log) && $date_log>$date_now)
        {
            $url = $_SERVER['HTTP_HOST'].str_replace('/index.php','',$_SERVER['PHP_SELF']).'?'.$_SERVER['QUERY_STRING'];

            $insert_data = [
                'user_id' => $user_id,
                'date' => $date_now,
                'url' => $url,
                'post_data' => $post_data,
                'status' => $http_code,
                'response' => $output
            ];

            $sql = 'INSERT INTO activity_log (user_id, activity_date, url, post_data, http_code, response) VALUES (?,?,?,?,?,?)';

            //This condition is my futile intent of loading the database functionality and everything seems to work as expected till this point
            if(empty($this->CI)){
                $this->CI = & get_instance();
                $this->CI->load->database();
            }

            $query = $this->CI->db->query($sql, $insert_data);
        }
    }
}
</code>```

So I've been having problems in this last lines in the log_petition_if_required function, loading the database functionality and executing the query.

Currently getting this error:

Fatal error: Call to a member function database() on a non-object in
  C:\wamp\www\appname\application\libraries\Utils.php on line
  $this->CI->load->database();

Which is the correct way to call the Loader class and get the database under this circumstances? Should I proceed in another way?

答:
As the user @DFriend stated in this question:

Extending CI_Log is not going to work if you need to access other
libraries. The reason is CI_Log is created long before $CI is created
so no "instance" is available for &get_instance() to return.

$this->load doesn't work because $this is not a controller ($this and
$CI point to the same object) and the class load ('CI_Loader') hasn't
been created yet either.

The way I was proceeding doesn't look like the way to go. Since extending the CI_Log class has clear limitations as the modification of the core class itself.

For the moment and since it is a temporal modification I will proceed overriding the CI_Log class and using plain PHP to complete the task.

Body:
I'm trying to store in to the database diferent kind of errors and stranges behaviours in my Codeigniter. For these to not be an exception I would like to store php Fatal errors also. To archive this I proceded this way:

Created an override of the CI_Log class named MY_Log and stored it in application/core.
The code in that class looks like this:

class MY_Log extends CI_Log {

    public function __construct(){

        parent::__construct();

    }

    function write_log($level = 'error', $msg, $php_error = FALSE){

        $result = parent::write_log($level, $msg, $php_error);

        if((require_once APPPATH.'libraries/Utils.php')== TRUE){
            if ($result == TRUE && strtoupper($level) == 'ERROR') {

                $utils = new Utils();
                $message = "An error occurred: \n\n";
                $message .= $level.' - '.date($this->_date_fmt). ' --> '.$msg."\n";
                $utils->log_petition_if_required(date("Y-m-d H:i:s", time() + 86400), 0, "", 500, $message);
            }
        }

        return $result;

    }
}

This class actually caches the error correctly and redirects the functionality towards the 'Utils' library just right.
The code in the library looks like this:

class Utils
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
    }
    public function log_petition_if_required($date_log, $user_id, $post_data, $http_code, $output){

        $date_now = date("Y-m-d H:i:s");
        if(!empty($date_log) && $date_log>$date_now)
        {
            $url = $_SERVER['HTTP_HOST'].str_replace('/index.php','',$_SERVER['PHP_SELF']).'?'.$_SERVER['QUERY_STRING'];

            $insert_data = [
                'user_id' => $user_id,
                'date' => $date_now,
                'url' => $url,
                'post_data' => $post_data,
                'status' => $http_code,
                'response' => $output
            ];

            $sql = 'INSERT INTO activity_log (user_id, activity_date, url, post_data, http_code, response) VALUES (?,?,?,?,?,?)';

            //This condition is my futile intent of loading the database functionality and everything seems to work as expected till this point
            if(empty($this->CI)){
                $this->CI = & get_instance();
                $this->CI->load->database();
            }

            $query = $this->CI->db->query($sql, $insert_data);
        }
    }
}

So I've been having problems in this last lines in the log_petition_if_required function, loading the database functionality and executing the query.

Currently getting this error:

Fatal error: Call to a member function database() on a non-object in
  C:\wamp\www\appname\application\libraries\Utils.php on line
  $this->CI->load->database();

Which is the correct way to call the Loader class and get the database under this circumstances? Should I proceed in another way?


问:
Jquery: What's faster? .text() or .attr('id')?
just wondering, which of these would be faster?

```<code>if ( $(this).text() == 'Test' )
{
    ...
}
</code>```

or

```<code>if ( $(this).attr('id') == 'Test' )
{
    ...
}
</code>```

or is there a faster way?

or are they both the same?

thanks

答: To add to lonesomeday's answer, I'd point out that the correct answer is most likely "it doesn't matter". If it does, then you probably shouldn't be running such performance-critical code in the visitor's browser, and they might have misgivings about their processor time being used in such ways; remember, (client-side) JavaScript does not run on your computer!

Body:
just wondering, which of these would be faster?

if ( $(this).text() == 'Test' )
{
    ...
}

or

if ( $(this).attr('id') == 'Test' )
{
    ...
}

or is there a faster way?

or are they both the same?

thanks