Programs & Examples On #Wce

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:

test rax, 1
jpe even

... has a 50% chance of mispredicting the branch, and that will come expensive.

The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.

How to set UICollectionViewCell Width and Height programmatically

Finally got the answer. You should extend UICollectionViewDelegateFlowLayout
This should be working with answers above.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

How to detect tableView cell touched or clicked in swift

I screw up on the every time! Just make sure the tableView delegate and dataSource are declared in viewDidLoad. Then I normally populate a few arrays to simulate returned data and then take it from there!

//******** Populate Table with data ***********
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SetupCellView
    cell?.ControllerLbl.text = ViewContHeading[indexPath.row]
    cell?.DetailLbl.text = ViewContDetail[indexPath.row]
    cell?.StartupImageImg.image = UIImage(named: ViewContImages[indexPath.row])
    return cell!
}

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

condition binding must have optinal type which mean that you can only bind optional values in if let statement

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        // Delete the row from the data source

        if let tv = tableView as UITableView? {


        }
    }
}

This will work fine but make sure when you use if let it must have optinal type "?"

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

This worked for me, May help you too :

Swift 4+ :

self.tableView.register(UITableViewCell.self, forCellWithReuseIdentifier: "cell")

Swift 3 :

self.tableView.register(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")

Swift 2.2 :

self.tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")

We have to Set Identifier property to Table View Cell as per below image,

enter image description here

UIButton action in table view cell

Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Add these 2 lines

layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

So you have:

   // Do any additional setup after loading the view, typically from a nib.
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
        layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout

That will remove all the spaces and give you a grid layout:

enter image description here

If you want the first column to have a width equal to the screen width then add the following function:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0
    {
        return CGSize(width: screenWidth, height: screenWidth/3)
    }
    return CGSize(width: screenWidth/3, height: screenWidth/3);

}

Grid layout will now look like (I've also added a blue background to first cell): enter image description here

UICollectionView - dynamic cell height?

Swift 4.*

I have created a Xib for UICollectionViewCell which seems to be the good approach.

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return size(indexPath: indexPath)
    }

    private func size(for indexPath: IndexPath) -> CGSize {
        // load cell from Xib
        let cell = Bundle.main.loadNibNamed("ACollectionViewCell", owner: self, options: nil)?.first as! ACollectionViewCell

        // configure cell with data in it
        let data = self.data[indexPath.item]
        cell.configure(withData: data)

        cell.setNeedsLayout()
        cell.layoutIfNeeded()

        // width that you want
        let width = collectionView.frame.width
        let height: CGFloat = 0

        let targetSize = CGSize(width: width, height: height)

        // get size with width that you want and automatic height
        let size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)
        // if you want height and width both to be dynamic use below
        // let size = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)

        return size
    }
}

#note: I don't recommend setting image when configuring data in this size determining case. It gave me the distorted/unwanted result. Configuring texts only gave me below result.

enter image description here

Class has no initializers Swift

simply provide the init block for HomeCell class

it's work in my case

UITableViewCell Selected Background Color on Multiple Selection

Swift 5 - This works for me:

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
        selectedCell.contentView.backgroundColor = .red
    }



    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
        cellToDeSelect.contentView.backgroundColor = .clear
    }

Outlets cannot be connected to repeating content iOS

If you're using a table view to display Settings and other options (like the built-in Settings app does), then you can set your Table View Content to Static Cells under the Attributes Inspector. Also, to do this, you must embedded your Table View in a UITableViewController instance.

UICollectionView Self Sizing Cells with Auto Layout

To whomever it may help,

I had that nasty crash if estimatedItemSize was set. Even if I returned 0 in numberOfItemsInSection. Therefore, the cells themselves and their auto-layout were not the cause of the crash... The collectionView just crashed, even when empty, just because estimatedItemSize was set for self-sizing.

In my case I reorganized my project, from a controller containing a collectionView to a collectionViewController, and it worked.

Go figure.

iOS 8 UITableView separator inset 0 not working

Most answers are showing separator insets and layout margins being set over a variety of methods (i.e., viewDidLayoutSubviews, willDisplayCell, etc) for cells and tableviews, but I've found that just putting these in cellForRowAtIndexPath works great. Seems like the cleanest way.

// kill insets for iOS 8
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
    cell.preservesSuperviewLayoutMargins = NO;
    [cell setLayoutMargins:UIEdgeInsetsZero];
}
// iOS 7 and later
if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    [cell setSeparatorInset:UIEdgeInsetsZero];

Custom UITableViewCell from nib in Swift

Another method that may work for you (it's how I do it) is registering a class.

Assume you create a custom tableView like the following:

class UICustomTableViewCell: UITableViewCell {...}

You can then register this cell in whatever UITableViewController you will be displaying it in with "registerClass":

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.registerClass(UICustomTableViewCell.self, forCellReuseIdentifier: "UICustomTableViewCellIdentifier")
}

And you can call it as you would expect in the cell for row method:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("UICustomTableViewCellIdentifier", forIndexPath: indexPath) as! UICustomTableViewCell
    return cell
}

Datatables: Cannot read property 'mData' of undefined

FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.

The following will throw error (no <thead> and <tbody> tags)

<table id="sample-table">
    <tr>
        <th>title-1</th>
        <th>title-2</th>
    </tr>
    <tr>
        <td>data-1</td>
        <td>data-2</td>
    </tr>
</table>

The following will also throw an error (unequal number of columns)

<table id="sample-table">
    <thead>
        <tr>
            <th>title-1</th>
            <th>title-2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>data-1</td>
            <td>data-2</td>
            <td>data-3</td>
        </tr>
    </tbody>
</table>

For more info read more here

Fatal error: unexpectedly found nil while unwrapping an Optional values

Replace this line cell.labelTitle.text = "This is a title"
with cell.labelTitle?.text = "This is a title"

How to Correctly handle Weak Self in Swift Blocks with Arguments

Swift 4.2

let closure = { [weak self] (_ parameter:Int) in
    guard let self = self else { return }

    self.method(parameter)
}

https://github.com/apple/swift-evolution/blob/master/proposals/0079-upgrade-self-from-weak-to-strong.md

creating custom tableview cells in swift

Set tag for imageview and label in cell

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

    let cell = tableView.dequeueReusableCellWithIdentifier("imagedataCell", forIndexPath: indexPath) as! UITableViewCell

    let rowData = self.tableData[indexPath.row] as! NSDictionary

    let urlString = rowData["artworkUrl60"] as? String
    // Create an NSURL instance from the String URL we get from the API
    let imgURL = NSURL(string: urlString!)
    // Get the formatted price string for display in the subtitle
    let formattedPrice = rowData["formattedPrice"] as? String
    // Download an NSData representation of the image at the URL
    let imgData = NSData(contentsOfURL: imgURL!)


    (cell.contentView.viewWithTag(1) as! UIImageView).image = UIImage(data: imgData!)

    (cell.contentView.viewWithTag(2) as! UILabel).text = rowData["trackName"] as? String

    return cell
}

OR

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "imagedataCell")

    if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
        urlString = rowData["artworkUrl60"] as? String,
        imgURL = NSURL(string: urlString),
        formattedPrice = rowData["formattedPrice"] as? String,
        imgData = NSData(contentsOfURL: imgURL),
        trackName = rowData["trackName"] as? String {
            cell.detailTextLabel?.text = formattedPrice
            cell.imageView?.image = UIImage(data: imgData)
            cell.textLabel?.text = trackName
    }

    return cell
}

see also TableImage loader from github

self.tableView.reloadData() not working in Swift

You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.

//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()//Your tableView here
})

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
    //If you want to do changes in UI use this
    DispatchQueue.main.async(execute: {
        //Update UI
        self.tableView.reloadData()
    })
}

Add swipe to delete UITableViewCell

Simply add method:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: UITableViewRowActionStyle.destructive, title: "Delete") { (action, indexPath) in
        self.arrayFruit.remove(at: indexPath.row)
        self.tblList.reloadData()
    }

    let edit = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (action, indexpath) in

        let alert = UIAlertController(title: "FruitApp", message: "Enter Fuit Name", preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: { (textField) in
            textField.placeholder = "Enter new fruit name"
        })
        alert.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.default, handler: { [weak alert](_) in
            let textField = alert?.textFields![0]
            self.arrayFruit[indexPath.row] = (textField?.text!)!
            self.tblList.reloadData()
        }))

        self.present(alert, animated: true, completion: nil)
    }
    edit.backgroundColor = UIColor.blue
    return [delete,edit]
}

enter image description here

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash
        self.tableView.reloadData()

        completionHandler(true)
    }
    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration
}

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

Get button click inside UITableViewCell

// Add action in cell for row at index path -tableView

cell.buttonName.addTarget(self, action: #selector(ViewController.btnAction(_:)), for: .touchUpInside)

// Button Action

  @objc func btnAction(_ sender: AnyObject) {



        var position: CGPoint = sender.convert(.zero, to: self.tableView)


        let indexPath = self.tableView.indexPathForRow(at: position)
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath!)! as
        UITableViewCell




}

Changing Font Size For UITableView Section Headers

Swift 2:

As OP asked, only adjust the size, not setting it as a system bold font or whatever:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {

            let newSize = CGFloat(16)
            let fontName = textLabel.font.fontName
            textLabel.font = UIFont(name: fontName, size: newSize)
        }
    }

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

For Spring Boot RestTemplate:

  • add org.apache.httpcomponents.httpcore dependency
  • use NoopHostnameVerifier for SSL factory:

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new URL("file:pathToServerKeyStore"), storePassword)
    //        .loadKeyMaterial(new URL("file:pathToClientKeyStore"), storePassword, storePassword)
            .build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
    RestTemplate restTemplate = new RestTemplate(factory);
    

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

You can use UITableViewRowAction's backgroundColor to set custom image or view. The trick is using UIColor(patternImage:).

Basically the width of UITableViewRowAction area is decided by its title, so you can find a exact length of title(or whitespace) and set the exact size of image with patternImage.

To implement this, I made a UIView's extension method.

func image() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
    guard let context = UIGraphicsGetCurrentContext() else {
        return UIImage()
    }
    layer.render(in: context)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

and to make a string with whitespace and exact length,

fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
    let kPadding: CGFloat = 20
    let mutable = NSMutableString(string: "")
    let attribute = [NSFontAttributeName: font]
    while mutable.size(attributes: attribute).width < width - (2 * kPadding) {
        mutable.append(" ")
    }
    return mutable as String
}

and now, you can create UITableViewRowAction.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let whitespace = whitespaceString(width: kCellActionWidth)
    let deleteAction = UITableViewRowAction(style: .`default`, title: whitespace) { (action, indexPath) in
        // do whatever you want
    }

    // create a color from patter image and set the color as a background color of action
    let kActionImageSize: CGFloat = 34
    let view = UIView(frame: CGRect(x: 0, y: 0, width: kCellActionWidth, height: kCellHeight))
    view.backgroundColor = UIColor.white
    let imageView = UIImageView(frame: CGRect(x: (kCellActionWidth - kActionImageSize) / 2,
                                              y: (kCellHeight - kActionImageSize) / 2,
                                              width: 34,
                                              height: 34))
    imageView.image = UIImage(named: "x")
    view.addSubview(imageView)
    let image = view.image()

    deleteAction.backgroundColor = UIColor(patternImage: image)

    return [deleteAction]
}

The result will look like this.

enter image description here

Another way to do this is to import custom font which has the image you want to use as a font and use UIButton.appearance. However this will affect other buttons unless you manually set other button's font.

From iOS 11, it will show this message [TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.. Currently it is still working, but it wouldn't work in the future update.

==========================================

For iOS 11+, you can use:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
    // Perform your action here
      completion(true)
  }

  let muteAction = UIContextualAction(style: .normal, title: "Mute") { (action, view, completion) in
    // Perform your action here
    completion(true)
  }

  deleteAction.image = UIImage(named: "icon.png")
  deleteAction.backgroundColor = UIColor.red
  return UISwipeActionsConfiguration(actions: [deleteAction, muteAction])
} 

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

swift 4

    @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    private var context = 1
 override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.addObserver(self, forKeyPath: "contentSize", options: [.new,.prior], context: &context)
    }
  // Added observer to adjust tableview height based on the content

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &self.context{
            if let size = change?[NSKeyValueChangeKey.newKey] as? CGSize{
                print("-----")
                print(size.height)
                tableViewHeightConstraint.constant = size.height + 50
            }
        }
    }

//Remove observer
 deinit {

        NotificationCenter.default.removeObserver(self)

    }

How to use auto-layout to move other views when a view is hidden?

Try this,I have implemented below code ,

I have one View on ViewController in that added other three views, When any view is hidden other two view will move,Follow below steps. ,

1.ViewController.h File

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIView *viewOne;
@property (strong, nonatomic) IBOutlet UIView *viewTwo;
@property (strong, nonatomic) IBOutlet UIView *viewThree;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewOneWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewTwoWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewThreeWidth;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *viewBottomWidth;
@end

2.ViewController.m

 #import "ViewController.h"
 @interface ViewController ()
{
  CGFloat viewOneWidthConstant;
  CGFloat viewTwoWidthConstant;
  CGFloat viewThreeWidthConstant;
  CGFloat viewBottomWidthConstant;
}
@end

@implementation ViewController
@synthesize viewOne, viewTwo, viewThree;

- (void)viewDidLoad {
  [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a 
  nib.

  /*
   0  0   0
   0  0   1
   0  1   0
   0  1   1
   1  0   0
   1  0   1
   1  1   0
   1  1   1
   */

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:YES];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:YES];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:NO];
  //    [viewTwo setHidden:YES];
  //    [viewThree setHidden:YES];


  //    [viewOne setHidden:YES];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:NO];

  //    [viewOne setHidden:YES];
  //    [viewTwo setHidden:NO];
  //    [viewThree setHidden:YES];

 //    [viewOne setHidden:YES];
 //    [viewTwo setHidden:YES];
 //    [viewThree setHidden:NO];

//    [viewOne setHidden:YES];
//    [viewTwo setHidden:YES];
//    [viewThree setHidden:YES];

 [self hideShowBottomBar];
  }

- (void)hideShowBottomBar
{
  BOOL isOne = !viewOne.isHidden;
  BOOL isTwo = !viewTwo.isHidden;
  BOOL isThree = !viewThree.isHidden;

  viewOneWidthConstant = _viewOneWidth.constant;
  viewTwoWidthConstant = _viewTwoWidth.constant;
  viewThreeWidthConstant = _viewThreeWidth.constant;
  viewBottomWidthConstant = _viewBottomWidth.constant;

   if (isOne && isTwo && isThree) {
    // 0    0   0
    _viewOneWidth.constant = viewBottomWidthConstant / 3;
    _viewTwoWidth.constant = viewBottomWidthConstant / 3;
    _viewThreeWidth.constant = viewBottomWidthConstant / 3;
    }
    else if (isOne && isTwo && !isThree) {
     // 0    0   1
    _viewOneWidth.constant = viewBottomWidthConstant / 2;
    _viewTwoWidth.constant = viewBottomWidthConstant / 2;
    _viewThreeWidth.constant = 0;
    }
   else if (isOne && !isTwo && isThree) {
    // 0    1   0
    _viewOneWidth.constant = viewBottomWidthConstant / 2;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = viewBottomWidthConstant / 2;
    }
    else if (isOne && !isTwo && !isThree) {
    // 0    1   1
    _viewOneWidth.constant = viewBottomWidthConstant;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = 0;
   }
   else if (!isOne && isTwo && isThree) {
    // 1    0   0
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = viewBottomWidthConstant / 2;
    _viewThreeWidth.constant = viewBottomWidthConstant / 2;
   }
   else if (!isOne && isTwo && !isThree) {
    // 1    0   1
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = viewBottomWidthConstant;
    _viewThreeWidth.constant = 0;
   }
   else if (!isOne && !isTwo && isThree) {
    // 1    1   0
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = viewBottomWidthConstant;
   }
   else if (isOne && isTwo && isThree) {
    // 1    1   1
    _viewOneWidth.constant = 0;
    _viewTwoWidth.constant = 0;
    _viewThreeWidth.constant = 0;
   }
  }

 - (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
 // Dispose of any resources that can be recreated.
 }
 @end

enter image description here enter image description here enter image description here

Hope So this logic will help some one.

UITableView with fixed section headers

Change your TableView Style:

self.tableview = [[UITableView alloc] initwithFrame:frame style:UITableViewStyleGrouped];

As per apple documentation for UITableView:

UITableViewStylePlain- A plain table view. Any section headers or footers are displayed as inline separators and float when the table view is scrolled.

UITableViewStyleGrouped- A table view whose sections present distinct groups of rows. The section headers and footers do not float.

Hope this small change will help you ..

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

/* I have done it this way, and also tested it */

Step 1 = Register custom cell class (in case of prototype cell in table) or nib (in case of custom nib for custom cell) for table like this in viewDidLoad method:

[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];

OR

[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];

Step 2 = Use UITableView's "dequeueReusableCellWithIdentifier: forIndexPath:" method like this (for this, you must register class or nib) :

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];

            cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"];
            cell.textLabelCustom.text = @"Hello";

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                // retrive image on global queue
                UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:     [NSURL URLWithString:kImgLink]]];

                dispatch_async(dispatch_get_main_queue(), ^{

                    CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                  // assign cell image on main thread
                    cell.imageViewCustom.image = img;
                });
            });

            return cell;
        }

how to get data from selected row from datagridview

I was having the same issue and this works excellently.

Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting  
  'Display complete contents in tooltip even though column display cuts off part of it.   
  DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
End Sub

Creating a UITableView Programmatically

When you register a class, and use dequeueReusableCellWithIdentifier:forIndexPath:, the dequeue method is guaranteed to return a cell, so your if (cell == nil) clause is never entered. So, just do it the old way, don't register the class, and use dequeueReusableCellWithIdentifier:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newFriendCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
//etc.
return cell;
}

As for the segue, it can't be called because you can't make a segue to a table that you've created in code, not in IB. Again, go back to the old way and use tableView:didSelectRowAtIndexPath: which will be called when you select a cell. Instantiate your detail controller there and do the trasition in code.

After edit:

I didn't see your added code there. You've implemented didDeselectRowAtIndexPath rather than didSelectRowAtIndexPath. If you change that, your segue should work.

UICollectionView cell selection and cell reuse

Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];


if (cell.selected) {
     cell.backgroundColor = [UIColor blueColor]; // highlight selection 
}
else
{
     cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
 }  

 -(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath]; 
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}

c# datagridview doubleclick on row with FullRowSelect

You get the index number of the row in the datagridview using northwind database employees tables as an example:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed.
            this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees);

        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString();
            string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

            MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: "
                + cellValue.ToString());
        }
    }
}

the result will show you index number of record and the contents of the second table column in datagridview:

enter image description here

Change the row color in DataGridView based on the quantity of a cell value

I fixed my error. just removed "Value" from this line:

If drv.Item("Quantity").Value < 5  Then

So it will look like

If drv.Item("Quantity") < 5 Then

How to get the selected row values of DevExpress XtraGrid?

var rowHandle = gridView.FocusedRowHandle;

var obj = gridView.GetRowCellValue(rowHandle, "FieldName");

//For example  
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

This might seem stupid to some people but it got me. I was getting this error and the problem for me was that I was trying to use static cells but then dynamically add more stuff. If you are calling this method your cells need to be dynamic prototypes. Select the cell in storyboard and under the Attributes inspector, the very first thing says 'Content' and you should select dynamic prototypes not static.

Getting data from selected datagridview row and which event?

You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.

this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); 

I hope it helps.

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Hide separator line on one UITableViewCell

For iOS7 and above, the cleaner way is to use INFINITY instead of hardcoded value. You don't have to worry on updating the cell when the screen rotates.

if (indexPath.row == <row number>) {
    cell.separatorInset = UIEdgeInsetsMake(0, INFINITY, 0, 0);
}

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Using openssl to get the certificate from a server

The easiest command line for this, which includes the PEM output to add it to the keystore, as well as a human readable output and also supports SNI, which is important if you are working with an HTTP server is:

openssl s_client -servername example.com -connect example.com:443 \
    </dev/null 2>/dev/null | openssl x509 -text

The -servername option is to enable SNI support and the openssl x509 -text prints the certificate in human readable format.

How to add spacing between UITableViewCell

My situation was i used custom UIView to viewForHeader in section also heightForHeader in section return constant height say 40, issue was when there is no data all header views were touched to each other. so i wanted to space between the section in absent of data so i fixed by just changing "tableview style" plane to "Group".and it worked for me.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

Is it possible to refresh a single UITableViewCell in a UITableView?

reloadRowsAtIndexPaths: is fine, but still will force UITableViewDelegate methods to fire.

The simplest approach I can imagine is:

UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];

It's important to invoke your configureCell: implementation on main thread, as it wont work on non-UI thread (the same story with reloadData/reloadRowsAtIndexPaths:). Sometimes it might be helpful to add:

dispatch_async(dispatch_get_main_queue(), ^
{
    [self configureCell:cell forIndexPath:indexPath];
});

It's also worth to avoid work that would be done outside of the currently visible view:

BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
    ....
}

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

About the server can deliver to the clients the root cert or not, extracted from the RFC-5246 'The Transport Layer Security (TLS) Protocol Version 1.2' doc it says:

certificate_list
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY be omitted from the chain, under the
assumption that the remote end must already possess it in order to validate it in any case.

About the term 'MAY', extracted from the RFC-2119 "Best Current Practice" says:

5.MAY
This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a
particular marketplace requires it or because the vendor feels that
it enhances the product while another vendor may omit the same item.
An implementation which does not include a particular option MUST be
prepared to interoperate with another implementation which does
include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option
MUST be prepared to interoperate with another implementation which
does not include the option (except, of course, for the feature the
option provides.)

In conclusion, the root may be at the certification path delivered by the server in the handshake.

A practical use.
Think about, not in navigator user terms, but on a transfer tool at a server in a militarized zone with limited internet access.
The server, playing the client role at the transfer, receives all the certs path from the server.
All the certs in the chain should be checked to be trusted, root included.
The only way to check this is the root be included at the certs path in transfer time, being matched against a previously declared as 'trusted' local copy of them.

How to deselect a selected UITableView cell?

What I've found is that on top of setting the cell as selected, you have to let the table view know to select the row at the given index path.

// Swift 3+  

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if appDelegate.indexPathDelegate.row == indexPath.row {
        self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
        cell.setSelected(true, animated: true)
    }
}

Long press on UITableView

Answer in Swift:

Add delegate UIGestureRecognizerDelegate to your UITableViewController.

Within UITableViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.delegate = self
    self.tableView.addGestureRecognizer(longPressGesture)

}

And the function:

func handleLongPress(longPressGesture:UILongPressGestureRecognizer) {

    let p = longPressGesture.locationInView(self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(p)

    if indexPath == nil {
        print("Long press on table view, not row.")
    }
    else if (longPressGesture.state == UIGestureRecognizerState.Began) {
        print("Long press on row, at \(indexPath!.row)")
    }

}

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

UITableViewCell, show delete button on swipe

Swift 3

All you have to do is enable these two functions:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    return true

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete {
        tableView.reloadData()
    }

}

openssl s_client using a proxy

since openssl v1.1.0

C:\openssl>openssl version
OpenSSL 1.1.0g  2 Nov 2017
C:\openssl>openssl s_client -proxy 192.168.103.115:3128 -connect www.google.com -CAfile C:\TEMP\internalCA.crt
CONNECTED(00000088)
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = www.google.com
verify return:1
---
Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
   i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
 1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
   i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkTCCAnmgAwIBAgIJAIv4/hQAAAAAMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
BAYTAkZSMQ4wDAYDVQQHEwVDUk9JWDETMBEGA1UEAxMKc3Zwcm94eXNnMTEeMBwG

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

Here's how i did it. This technique takes care of moving the text and detail text labels appropriately to the left:

@interface SizableImageCell : UITableViewCell {}
@end
@implementation SizableImageCell
- (void)layoutSubviews {
    [super layoutSubviews];

    float desiredWidth = 80;
    float w=self.imageView.frame.size.width;
    if (w>desiredWidth) {
        float widthSub = w - desiredWidth;
        self.imageView.frame = CGRectMake(self.imageView.frame.origin.x,self.imageView.frame.origin.y,desiredWidth,self.imageView.frame.size.height);
        self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x-widthSub,self.textLabel.frame.origin.y,self.textLabel.frame.size.width+widthSub,self.textLabel.frame.size.height);
        self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x-widthSub,self.detailTextLabel.frame.origin.y,self.detailTextLabel.frame.size.width+widthSub,self.detailTextLabel.frame.size.height);
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
}
@end

...

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SizableImageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    cell.textLabel.text = ...
    cell.detailTextLabel.text = ...
    cell.imageView.image = ...
    return cell;
}

How to change the blue highlight color of a UITableViewCell?

If you want to change it app wide, you can add the logic to your App Delegate

class AppDelegate: UIResponder, UIApplicationDelegate {

    //... truncated

   func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

        // set up your background color view
        let colorView = UIView()
        colorView.backgroundColor = UIColor.yellowColor()

        // use UITableViewCell.appearance() to configure 
        // the default appearance of all UITableViewCells in your app
        UITableViewCell.appearance().selectedBackgroundView = colorView

        return true
    }

    //... truncated
}

Changing background color of selected cell?

I created UIView and set the property of cell selectedBackgroundView:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;

How can I get a uitableViewCell by indexPath?

Finally, I get the cell using the following code:

UITableViewCell *cell = (UITableViewCell *)[(UITableView *)self.view cellForRowAtIndexPath:nowIndex];

Because the class is extended UITableViewController:

@interface SearchHotelViewController : UITableViewController

So, the self is "SearchHotelViewController".

UITableView Cell selected Color?

Swift 3.0 extension

extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}

cell.selectionColor = UIColor.FormaCar.blue

Detecting which UIButton was pressed in a UITableView

TO HANDLE SECTIONS - I stored the NSIndexPath in a custom UITableViewCell

IN CLKIndexPricesHEADERTableViewCell.xib

IN IB Add UIButton to XIB - DONT add action!

Add outlet @property (retain, nonatomic) IBOutlet UIButton *buttonIndexSectionClose;

DO NOT CTRL+DRAG an action in IB(done in code below)

@interface CLKIndexPricesHEADERTableViewCell : UITableViewCell
...
@property (retain, nonatomic) IBOutlet UIButton *buttonIndexSectionClose;
@property (nonatomic, retain) NSIndexPath * indexPathForCell;
@end

In viewForHeaderInSection (should also work for cellForRow.... etc if you table has only 1 section)

- viewForHeaderInSection is called for each section 1...2...3
- get the cell CLKIndexPricesHEADERTableViewCell 
- getTableRowHEADER just does the normal dequeueReusableCellWithIdentifier
- STORE the indexPath IN the UITableView cell
- indexPath.section = (NSInteger)section
- indexPath.row = 0 always (we are only interested in sections)

- (UIView *) tableView:(UITableView *)tableView1 viewForHeaderInSection:(NSInteger)section {


    //Standard method for getting a UITableViewCell
    CLKIndexPricesHEADERTableViewCell * cellHEADER = [self getTableRowHEADER];

...use the section to get data for your cell

...fill it in

   indexName        = ffaIndex.routeCode;
   indexPrice       = ffaIndex.indexValue;

   //

   [cellHEADER.buttonIndexSectionClose addTarget:self
                                          action:@selector(buttonDELETEINDEXPressedAction:forEvent:)
                                forControlEvents:UIControlEventTouchUpInside];


   cellHEADER.indexPathForCell = [NSIndexPath indexPathForRow:0 inSection:section];


    return cellHEADER;
}

USER presses DELETE Button on a Section header and this calls

- (void)buttonDELETEINDEXPressedAction:(id)sender forEvent:(UIEvent *)event
{
    NSLog(@"%s", __PRETTY_FUNCTION__);


    UIView *  parent1 = [sender superview];   // UiTableViewCellContentView
    //UIView *myContentView = (UIView *)parent1;

    UIView *  parent2 = [parent1 superview];  // custom cell containing the content view
    //UIView *  parent3 = [parent2 superview];  // UITableView containing the cell
    //UIView *  parent4 = [parent3 superview];  // UIView containing the table


    if([parent2 isMemberOfClass:[CLKIndexPricesHEADERTableViewCell class]]){
        CLKIndexPricesHEADERTableViewCell *myTableCell = (CLKIndexPricesHEADERTableViewCell *)parent2;

        //UITableView *myTable = (UITableView *)parent3;
        //UIView *mainView = (UIView *)parent4;

        NSLog(@"%s indexPath.section,row[%d,%d]", __PRETTY_FUNCTION__, myTableCell.indexPathForCell.section,myTableCell.indexPathForCell.row);

        NSString *key = [self.sortedKeysArray objectAtIndex:myTableCell.indexPathForCell.section];
        if(key){
            NSLog(@"%s DELETE object at key:%@", __PRETTY_FUNCTION__,key);
            self.keyForSectionIndexToDelete = key;
            self.sectionIndexToDelete = myTableCell.indexPathForCell.section;

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Remove Index"
                                                                message:@"Are you sure"
                                                               delegate:self
                                                      cancelButtonTitle:@"No"
                                                      otherButtonTitles:@"Yes", nil];
            alertView.tag = kALERTVIEW_REMOVE_ONE_INDEX;
            [alertView show];
            [alertView release];
            //------
        }else{
            NSLog(@"ERROR: [%s] key is nil for section:%d", __PRETTY_FUNCTION__,myTableCell.indexPathForCell.section);
        }

    }else{
        NSLog(@"ERROR: [%s] CLKIndexPricesHEADERTableViewCell not found", __PRETTY_FUNCTION__);
    }
}

In this example I added a Delete button so should show UIAlertView to confirm it

I store the section and key into the dictionary storing info about the section in a ivar in the VC

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
   if(alertView.tag == kALERTVIEW_REMOVE_ONE_INDEX){
        if(buttonIndex==0){
            //NO
            NSLog(@"[%s] BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
            //do nothing
        }
        else if(buttonIndex==1){
            //YES
            NSLog(@"[%s] BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
            if(self.keyForSectionIndexToDelete != nil){

                //Remove the section by key
                [self.indexPricesDictionary removeObjectForKey:self.keyForSectionIndexToDelete];

                //sort the keys so sections appear alphabetically/numbericsearch (minus the one we just removed)
                [self updateTheSortedKeysArray];                

                //Delete the section from the table using animation
                [self.tableView beginUpdates];

                [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:self.sectionIndexToDelete]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
                [self.tableView endUpdates];

                //required to trigger refresh of myTableCell.indexPathForCell else old values in UITableViewCells
                [self.tableView reloadData];
            }else{
                NSLog(@"ERROR: [%s] OBJECT is nil", __PRETTY_FUNCTION__);
            }
        }
        else {
            NSLog(@"ERROR: [%s] UNHANDLED BUTTON:%d", __PRETTY_FUNCTION__,buttonIndex);
        }
    }else {
        NSLog(@"ERROR: [%s] unhandled ALERTVIEW TAG:%d", __PRETTY_FUNCTION__,alertView.tag);
    }
}

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

How to bind list to dataGridView?

may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you

public class FileName
{        
     [DisplayName("File Name")] 
     public string FileName {get;set;}
     [DisplayName("Value")] 
     public string Value {get;set;}
}

and then you can bind List as datasource as

private void BindGrid()
{
    var filelist = GetFileListOnWebServer().ToList();    
    gvFilesOnServer.DataSource = filelist.ToArray();
}

for further information you can visit this page Bind List of Class objects as Datasource to DataGridView

hope this will help you.

How do you load custom UITableViewCells from Xib files?

I've decided to post since I don't like any of these answers -- things can always be more simple and this is by far the most concise way I've found.

1. Build your Xib in Interface Builder as you like it

  • Set File's Owner to class NSObject
  • Add a UITableViewCell and set its class to MyTableViewCellSubclass -- if your IB crashes (happens in Xcode > 4 as of this writing), just use a UIView of do the interface in Xcode 4 if you still have it laying around
  • Layout your subviews inside this cell and attach your IBOutlet connections to your @interface in the .h or .m (.m is my preference)

2. In your UIViewController or UITableViewController subclass

@implementation ViewController

static NSString *cellIdentifier = @"MyCellIdentier";

- (void) viewDidLoad {

    ...
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCellSubclass" bundle:nil] forCellReuseIdentifier:cellIdentifier];
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCellSubclass *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    ...

    return cell;
}

3. In your MyTableViewCellSubclass

- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        ...
    }

    return self;
}

Setting custom UITableViewCells height

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    CGSize constraintSize = {245.0, 20000}
    CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize  lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18) 

   return 45
else return neededSize.height + 45 
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use  
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.

}

Can you animate a height change on a UITableViewCell when selected?

reloadData is no good because there's no animation...

This is what I'm currently trying:

NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

It almost works right. Almost. I'm increasing the height of the cell, and sometimes there's a little "hiccup" in the table view as the cell is replaced, as if some scrolling position in the table view is being preserved, the new cell (which is the first cell in the table) ends up with its offset too high, and the scrollview bounces to reposition it.

Having a UITextField in a UITableViewCell

Try this one. It can handle scrolling as well and you can reuse the cells without the hassle of removing subviews you added before.

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
    return 10;
}   

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
    if( cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];   

    cell.textLabel.text = [[NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh",@"Eighth",@"Nineth",@"Tenth",nil] 
                           objectAtIndex:indexPath.row];

    if (indexPath.row % 2) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
        textField.placeholder = @"Enter Text";
        textField.text = [inputTexts objectAtIndex:indexPath.row/2];
        textField.tag = indexPath.row/2;
        textField.delegate = self;
        cell.accessoryView = textField;
        [textField release];
    } else
        cell.accessoryView = nil;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;        
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [inputTexts replaceObjectAtIndex:textField.tag withObject:textField.text];
    return YES;
}

- (void)viewDidLoad {
    inputTexts = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",@"",nil];
    [super viewDidLoad];
}

How do I overload the square-bracket operator in C#?

you can find how to do it here. In short it is:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}

If you only need a getter the syntax in answer below can be used as well (starting from C# 6).

How to customize the background color of a UITableViewCell?

vlado.grigorov has some good advice - the best way is to create a backgroundView, and give that a colour, setting everything else to the clearColor. Also, I think that way is the only way to correctly clear the colour (try his sample - but set 'clearColor' instead of 'yellowColor'), which is what I was trying to do.

Java: Enum parameter in method

Sure, you could use an enum. Would something like the following work?

enum Alignment {
    LEFT,
    RIGHT
}

private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }

If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.

How do I uninstall nodejs installed from pkg (Mac OS X)?

This is the full list of commands I used (Many thanks to the posters above):

sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
brew install node

How to Disable landscape mode in Android?

If you want to disable Landscape mode for your android app ( or a single activity) all you need to do is add,

android:screenOrientation="portrait" to the activity tag in AndroidManifest.xml file.

Like:

<activity android:name="YourActivityName" 
    android:icon="@drawable/ic_launcher" 
    android:label="Your App Name" 
    android:screenOrientation="portrait">

Another Way , Programmatic Approach.

If you want to do this programatically ie. using Java code. You can do so by adding the below code in the Java class of the activity that you don't want to be displayed in landscape mode.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I hope it helps you .For more details you can visit here enter link description here

How to split the name string in mysql?

You could use the common_schema and use the tokenize function. For more information about this, follow the links. Your code the would end up like:

call tokenize(name, ' ');

However, be aware that a space is not a reliable separator for first and last name. E.g. In Spain it is common to have two last names.

How to get the number of threads in a Java process

Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.

ps -o nlwp <pid>

Empty set literal?

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

Wait until all promises complete even if some rejected

Instead of rejecting, resolve it with a object. You could do something like this when you are implementing promise

_x000D_
_x000D_
const promise = arg => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
      setTimeout(() => {_x000D_
        try{_x000D_
          if(arg != 2)_x000D_
            return resolve({success: true, data: arg});_x000D_
          else_x000D_
            throw new Error(arg)_x000D_
        }catch(e){_x000D_
          return resolve({success: false, error: e, data: arg})_x000D_
        }_x000D_
      }, 1000);_x000D_
  })_x000D_
}_x000D_
_x000D_
Promise.all([1,2,3,4,5].map(e => promise(e))).then(d => console.log(d))
_x000D_
_x000D_
_x000D_

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I tried most of the answers without success. What worked for me was (after following https://stackoverflow.com/a/21279068/2408893):

  • right click on project -> Properties
  • select Java Build Path
  • select the JRE System Library
  • click edit
  • In execution environment select a jdk

enter image description here

  • click Finish
  • build and run

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

SQL select only rows with max value on a column

My preference is to use as little code as possible...

You can do it using IN try this:

SELECT * 
FROM t1 WHERE (id,rev) IN 
( SELECT id, MAX(rev)
  FROM t1
  GROUP BY id
)

to my mind it is less complicated... easier to read and maintain.

Merging multiple PDFs using iTextSharp in c#.net

Merge byte arrays of multiple PDF files:

    public static byte[] MergePDFs(List<byte[]> pdfFiles)
    {  
        if (pdfFiles.Count > 1)
        {
            PdfReader finalPdf;
            Document pdfContainer;
            PdfWriter pdfCopy;
            MemoryStream msFinalPdf = new MemoryStream();

            finalPdf = new PdfReader(pdfFiles[0]);
            pdfContainer = new Document();
            pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);

            pdfContainer.Open();

            for (int k = 0; k < pdfFiles.Count; k++)
            {
                finalPdf = new PdfReader(pdfFiles[k]);
                for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
                {
                    ((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
                }
                pdfCopy.FreeReader(finalPdf);

            }
            finalPdf.Close();
            pdfCopy.Close();
            pdfContainer.Close();

            return msFinalPdf.ToArray();
        }
        else if (pdfFiles.Count == 1)
        {
            return pdfFiles[0];
        }
        return null;
    }

Getting a HeadlessException: No X11 DISPLAY variable was set

Your system does not have a GUI manager. Happens mostly in Solaris/Linux boxes. If you are using GUI in them make sure that you have a GUI manager installed and you may also want to google through the DISPLAY variable.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

What's the easiest way to escape HTML in Python?

Not the easiest way, but still straightforward. The main difference from cgi.escape module - it still will work properly if you already have &amp; in your text. As you see from comments to it:

cgi.escape version

def escape(s, quote=None):
    '''Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
is also translated.'''
    s = s.replace("&", "&amp;") # Must be done first!
    s = s.replace("<", "&lt;")
    s = s.replace(">", "&gt;")
    if quote:
        s = s.replace('"', "&quot;")
    return s

regex version

QUOTE_PATTERN = r"""([&<>"'])(?!(amp|lt|gt|quot|#39);)"""
def escape(word):
    """
    Replaces special characters <>&"' to HTML-safe sequences. 
    With attention to already escaped characters.
    """
    replace_with = {
        '<': '&gt;',
        '>': '&lt;',
        '&': '&amp;',
        '"': '&quot;', # should be escaped in attributes
        "'": '&#39'    # should be escaped in attributes
    }
    quote_pattern = re.compile(QUOTE_PATTERN)
    return re.sub(quote_pattern, lambda x: replace_with[x.group(0)], word)

How do I find the install time and date of Windows?

Open command prompt, type "systeminfo" and press enter. Your system may take few mins to get the information. In the result page you will find an entry as "System Installation Date". That is the date of windows installation. This process works in XP ,Win7 and also on win8.

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

PostgreSQL: Show tables in PostgreSQL

Running psql with the -E flag will echo the query used internally to implement \dt and similar:

sudo -u postgres psql -E

postgres=# \dt       
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name", 
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
    AND n.nspname <> 'pg_catalog'
    AND n.nspname <> 'information_schema'
    AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;        
**************************

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

Google Geocoding API - REQUEST_DENIED

I found that in my case, calling to the service without secure protocol (meaning: http), after adding the key=API_KEY, cause this issue. Changing to https solved it.

How do I make flex box work in safari?

display: flex;
display: -webkit-box;

did it for me. Also there were two display: flex; on the same element from different classes. So I removed the other one.

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

Is there a 'foreach' function in Python 3?

Yes, although it uses the same syntax as a for loop.

for x in ['a', 'b']: print(x)

Jquery, Clear / Empty all contents of tbody element?

Example for Remove table header or table body with jquery

_x000D_
_x000D_
function removeTableHeader(){_x000D_
  $('#myTableId thead').empty();_x000D_
}_x000D_
_x000D_
function removeTableBody(){_x000D_
    $('#myTableId tbody').empty();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id='myTableId'  border="1">_x000D_
  <thead>_x000D_
    <th>1st heading</th>_x000D_
    <th>2nd heading</th>_x000D_
    <th>3rd heading</th>_x000D_
  </thead>  _x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br/>_x000D_
<form>_x000D_
  <input type='button' value='Remove Table Header' onclick='removeTableHeader()'/>_x000D_
  <input type='button' value='Remove Table Body' onclick='removeTableBody()'/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

App installation failed due to application-identifier entitlement

In my case it was because of the certificate.

because my own certificate to sign the app wasn't part of the developper team (new employee), upgrading the app from the App Store to a new version wasn't allow.

So in case it happen to you and you can't manage to obtain a "good" certificate, just clone the git appStore version, open two Xcode projects, compile the old version, update the settings as you wish, the compile the new one and you're done.

a little bit dirty and tricky but I hope it could help someone.

INSERT VALUES WHERE NOT EXISTS

Ingnoring the duplicated unique constraint isn't a solution?

INSERT IGNORE INTO tblSoftwareTitles...

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

You have to put the path to the file. For example:

require_once('../web/a.php');

You cannot get the file to require it from internet (with http protocol) it's restricted. The files must be on the same server. With Possibility to see each others (rights)

Dir-1 -
         > Folder-1 -> a.php
Dir-2 -
         > Folder-2 -> b.php

To include a.php inside b.php => require_once('../../Dir-1/Folder-1/a.php');
To include b.php inside a.php => require_once('../../Dir-2/Folder-2/b.php');

Setting default permissions for newly created files and sub-directories under a directory in Linux?

It's ugly, but you can use the setfacl command to achieve exactly what you want.

On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):

user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x

Name the file acl.lst and fill in your real user names instead of user_X.

You can now set those acls on your directory by issuing the following command:

setfacl -f acl.lst /your/dir/here

Alter a MySQL column to be AUTO_INCREMENT

Try the following:

ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;

Switch statement: must default be the last case?

The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

Good Example :-

switch(5) {
  case 1:
    echo "1";
    break;
  case 2:
  default:
    echo "2, default";
    break;
  case 3;
    echo "3";
    break;
}


Outputs '2,default'

very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

How can I start an Activity from a non-Activity class?

Once you have obtained the context in your onTap() you can also do:

Intent myIntent = new Intent(mContext, theNewActivity.class);
mContext.startActivity(myIntent);

fatal: could not read Username for 'https://github.com': No such file or directory

I faced the exact same problem. This problem occurred when I cloned using HTTPS URL and then tried to push the changes using Git Bash on Windows using:

git clone https://github.com/{username}/{repo}.git

However, when I used SSH URL to clone, this problem didn't occur:

git clone [email protected]:{username}/{repo}.git

How to select true/false based on column value?

What does the UDF EntityHasProfile() do?

Typically you could do something like this with a LEFT JOIN:

SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
    ON EntityProfiles.EntityId = Entities.EntityId

This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.

Val and Var in Kotlin

Do you need to change a variable or set it permanently?

  • A good example if it is something like val pi5places = 3.14159 you would set it as val. Is there a possibility that you need to change that variable now or later, then you would set it as var.

  • For example : The color of a car, can be var colorCar = green. Later you can change that colorCar = blue, where as a val, you can not.

  • Responses here regarding mutable and immutable is fine, but may be scary if these terms are not well known or just getting into learning how to program.

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

git command to move a folder inside another

I solved this on windows by doing this:

  • Open Power shell console
  • run dir
  • Alt-click and drag over the file/folder name column, then copy
  • Paste to notepad++
  • run replace with regex: replace (.*) with git mv ".\\\1" ".\\<New_Folder_Here>\"
  • copy all text from notepad++ into powershell
  • hit enter

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Create a CSS rule / class with jQuery at runtime

Simply

$("<style>")
    .prop("type", "text/css")
    .html("\
    #my-window {\
        position: fixed;\
        z-index: 102;\
        display:none;\
        top:50%;\
        left:50%;\
    }")
    .appendTo("head");

Noticed the back slashes? They are used to join strings that are on new lines. Leaving them out generates an error.

Why is lock(this) {...} bad?

There's also some good discussion about this here: Is this the proper use of a mutex?

Replacement for deprecated sizeWithFont: in iOS 7?

Multi-line labels using dynamic height may require additional information to set the size properly. You can use sizeWithAttributes with UIFont and NSParagraphStyle to specify both the font and the line-break mode.

You would define the Paragraph Style and use an NSDictionary like this:

// set paragraph style
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
// make dictionary of attributes with paragraph style
NSDictionary *sizeAttributes        = @{NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: style};
// get the CGSize
CGSize adjustedSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);

// alternatively you can also get a CGRect to determine height
CGRect rect = [myLabel.text boundingRectWithSize:adjustedSize
                                                         options:NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:sizeAttributes
                                                         context:nil];

You can use the CGSize 'adjustedSize' or CGRect as rect.size.height property if you're looking for the height.

More info on NSParagraphStyle here: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSParagraphStyle_Class/Reference/Reference.html

Adding maven nexus repo to my pom.xml

From maven setting reference, you can not put your username/password in a pom.xml

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

You can first add a repository in your pom and then add the username/password in the $MAVEN_HOME/conf/settings.xml:

  <servers>
    <server>
        <id>my-internal-site</id>
        <username>yourUsername</username>
        <password>yourPassword</password>
    </server>
  </servers>

Time comparison

Adam explain well in his answer But I used this way. I think this is easiest way to understand time comparison in java

First create 3 calender object with set your time only , Hour and min.

then get GMT milliseconds of that time and simply compare.

Ex.

Calendar chechDateTime = Calendar.getInstance();
chechDateTime.set(Calendar.MILLISECOND, 0);
chechDateTime.set(Calendar.SECOND, 0);
chechDateTime.set(Calendar.HOUR, 11);
chechDateTime.set(Calendar.MINUTE, 22);


Calendar startDateTime = Calendar.getInstance();
startDateTime.set(Calendar.MILLISECOND, 0);
startDateTime.set(Calendar.SECOND, 0);
startDateTime.set(Calendar.HOUR, 10);
startDateTime.set(Calendar.MINUTE, 0);

Calendar endDateTime = Calendar.getInstance();
endDateTime.set(Calendar.MILLISECOND, 0);
endDateTime.set(Calendar.SECOND, 0);
endDateTime.set(Calendar.HOUR, 18);
endDateTime.set(Calendar.MINUTE, 22);

 long chechDateTimeMilliseconds=chechDateTime.getTime().getTime();
 long startDateTimeMilliseconds=startDateTime.getTime().getTime();
 long endDateTimeMilliseconds=endDateTime.getTime().getTime();


System.out.println("chechDateTime : "+chechDateTimeMilliseconds);
System.out.println("startDateTime "+startDateTimeMilliseconds);
System.out.println("endDateTime "+endDateTimeMilliseconds);



if(chechDateTimeMilliseconds>=startDateTimeMilliseconds && chechDateTimeMilliseconds <= endDateTimeMilliseconds ){
       System.out.println("In between ");
    }else{
         System.out.println("Not In between ");
    }

Output will look like this :

chechDateTime : 1397238720000
startDateTime 1397233800000
endDateTime 1397263920000
In between 

What is String pool in Java?

I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.

String s1 = "Arul"; //case 1 
String s2 = "Arul"; //case 2 

In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

if(s1 == s2) System.out.println("equal"); //Prints equal. 

String n1 = new String("Arul"); 
String n2 = new String("Arul"); 
if(n1 == n2) System.out.println("equal"); //No output.  

http://p2p.wrox.com/java-espanol/29312-string-pooling.html

MySQL "incorrect string value" error when save unicode string in Django

You aren't trying to save unicode strings, you're trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:

user.last_name = u'Slatkevicius'

or (when you don't have string literals) decode them using the utf-8 encoding:

user.last_name = lastname.decode('utf-8')

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

How to check null objects in jQuery

use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)

How to install OpenJDK 11 on Windows?

AdoptOpenJDK is a new website hosted by the java community. You can find .msi installers for OpenJDK 8 through 14 there, which will perform all the things listed in the question (Unpacking, registry keys, PATH variable updating (and JAVA_HOME), uninstaller...).

How to determine if a number is odd in JavaScript

A more functional approach in modern javascript:

const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")

const negate = f=> (...args)=> !f(...args)
const isOdd  = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)

input() error - NameError: name '...' is not defined

We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

How to pass a value from one Activity to another in Android?

You can use Bundle to do the same in Android

Create the intent:

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();

//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString(“stuff”, getrec);

//Add the bundle to the intent
i.putExtras(bundle);

//Fire that second activity
startActivity(i);

Now in your second activity retrieve your data from the bundle:

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String stuff = bundle.getString(“stuff”); 

Invoking Java main method with parameters from Eclipse

Another idea:

Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)). So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...

Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

Why should text files end with a newline?

It's very late here but I just faced one bug in file processing and that came because the files were not ending with empty newline. We were processing text files with sed and sed was omitting the last line from output which was causing invalid json structure and sending rest of the process to fail state.

All we were doing was:

There is one sample file say: foo.txt with some json content inside it.

[{
    someProp: value
},
{
    someProp: value
}] <-- No newline here

The file was created in widows machine and window scripts were processing that file using PowerShell commands. All good.

When we processed same file using sed command sed 's|value|newValue|g' foo.txt > foo.txt.tmp

The newly generated file was

[{
    someProp: value
},
{
    someProp: value

and boom, it failed the rest of the processes because of the invalid JSON.

So it's always a good practice to end your file with empty new line.

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

What does %w(array) mean?

I was given a bunch of columns from a CSV spreadsheet of full names of users and I needed to keep the formatting, with spaces. The easiest way I found to get them in while using ruby was to do:

names = %( Porter Smith
Jimmy Jones
Ronald Jackson).split('\n')

This highlights that %() creates a string like "Porter Smith\nJimmyJones\nRonald Jackson" and to get the array you split the string on the "\n" ["Porter Smith", "Jimmy Jones", "Ronald Jackson"]

So to answer the OP's original question too, they could have wrote %(cgi\ spaeinfilename.rb;complex.rb;date.rb).split(';') if there happened to be space when you want the space to exist in the final array output.

Reading a date using DataReader

 (DateTime)MyReader["ColumnName"];

OR

Convert.ToDateTime(MyReader["ColumnName"]);

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

first Download the ssl certificate then you can go to your java bin path execute the below command in the console.

C:\java\JDK1.8.0_66-X64\bin>keytool -printcert -file C:\Users\lova\openapi.cer -keystore openapistore

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

jQuery: select an element's class and id at the same time?

It will work when adding space between id and class identifier

$("#countery .save")...

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

@Transactional =javax.transaction.Transactional. Put it just beside @Repository.

Switch statement for greater-than/less-than

switch (Math.floor(scrollLeft/1000)) {
  case 0: // (<1000)
   //do stuff
   break;
  case 1: // (>=1000 && <2000)
   //do stuff;
   break;
}

Only works if you have regular steps...

EDIT: since this solution keeps getting upvotes, I must advice that mofolo's solution is a way better

Why can't I declare static methods in an interface?

An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.

How to access cookies in AngularJS?

FYI, I put together a JSFiddle of this using the $cookieStore, two controllers, a $rootScope, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...

The gist of it is:

Javascript

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

myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
    $scope.bump = function () {
        var lastVal = $cookieStore.get('lastValue');
        if (!lastVal) {
            $rootScope.lastVal = 1;
        } else {
            $rootScope.lastVal = lastVal + 1;
        }
        $cookieStore.put('lastValue', $rootScope.lastVal);
    }
});

myApp.controller('ShowerCtrl', function () {
});

HTML

<div ng-app="myApp">
    <div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
    <div id="button-holder" ng-controller="CookieCtrl">
        <button ng-click="bump()">Bump!</button>
    </div>
</div>

How can I check if a user is logged-in in php?

Logins are not too complicated, but there are some specific pieces that almost all login processes need.

First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:

session_start();

Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:

if (match_found_in_database()) {
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
                                       // something like this is optional, of course
}

Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
    echo "Please log in first to see this page.";
}

Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

jQuery .get error response function?

If you want a generic error you can setup all $.ajax() (which $.get() uses underneath) requests jQuery makes to display an error using $.ajaxSetup(), for example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error);
  }
});

Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error option to default to the handler/function above, if you made a full $.ajax() call and specified the error handler then what you had would override the above.

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

How to check if an integer is in a given range?

if you are using Spring data you can also use the Range object from Spring.

range = new org.springframework.data.domain.Range(3, 8); range.contains(5) will return true.

Run ssh and immediately execute command

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t [email protected] 'cd /some/path; bash -l'

What is the difference between DBMS and RDBMS?

DBMS : Data Base Management System ..... for storage of data and efficient retrieval of data. Eg: Foxpro

1)A DBMS has to be persistent (it should be accessible when the program created the data donot exist or even the application that created the data restarted).

2) DBMS has to provide some uniform methods independent of a specific application for accessing the information that is stored.

3)DBMS does not impose any constraints or security with regard to data manipulation. It is user or the programmer responsibility to ensure the ACID PROPERTY of the database

4)In DBMS Normalization process will not be present

5)In dbms no relationship concept

6)It supports Single User only

7)It treats Data as Files internally

8)It supports 3 rules of E.F.CODD out off 12 rules

9)It requires low Software and Hardware Requirements.

FoxPro, IMS are Examples

RDBMS: Relational Data Base Management System

.....the database which is used by relations(tables) to acquire information retrieval Eg: oracle, SQL..,

1)RDBMS is based on relational model, in which data is represented in the form of relations, with enforced relationships between the tables.

2)RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY.

3)In RDBMS, normalization process will be present to check the database table cosistency

4)RDBMS helps in recovery of the database in case of loss of data

5)It is used to establish the relationship concept between two database objects, i.e, tables

6)It supports multiple users

7)It treats data as Tables internally

8)It supports minimum 6 rules of E.F.CODD

9)It requires High software and hardware

How to convert object array to string array in Java

The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:

Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
        String apply(Object from){
             return from.toString();
        }
 });

This take you away from using arrays,but I think this would be my prefered way.

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Laravel Eloquent LEFT JOIN WHERE NULL

You can also specify the columns in a select like so:

$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
  $join->on('customers.id', '=', 'orders.customer_id') 
})->whereNull('orders.customer_id')->first();

How to update UI from another thread running in another class

If this is a long calculation then I would go background worker. It has progress support. It also has support for cancel.

http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

Here I have a TextBox bound to contents.

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Debug.Write("backgroundWorker_RunWorkerCompleted");
        if (e.Cancelled)
        {
            contents = "Cancelled get contents.";
            NotifyPropertyChanged("Contents");
        }
        else if (e.Error != null)
        {
            contents = "An Error Occured in get contents";
            NotifyPropertyChanged("Contents");
        }
        else
        {
            contents = (string)e.Result;
            if (contentTabSelectd) NotifyPropertyChanged("Contents");
        }
    }

error: expected primary-expression before ')' token (C)

You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

Example of Mockito's argumentCaptor

The two main differences are:

  • when you capture even a single argument, you are able to make much more elaborate tests on this argument, and with more obvious code;
  • an ArgumentCaptor can capture more than once.

To illustrate the latter, say you have:

final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);

verify(x, times(4)).someMethod(captor.capture()); // for instance

Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.

This or any number of arguments in fact, since a VerificationMode is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.

This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatchers -- particularly if you combine mockito with assertj.

Oh, and please consider using TestNG instead of JUnit.

Oracle SQL Developer and PostgreSQL

I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.

The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).

Those who need a single tool to connect to multiple database engines can now use SQL Developer.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

iPad/iPhone hover problem causes the user to double click a link

I just found out that it works if you add an empty listener, don't ask me why, but I tested it on iPhone and iPad with iOS 9.3.2 and it worked fine.

if(/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream){
    var elements = document.getElementsByTagName('a');
    for(var i = 0; i < elements.length; i++){
        elements[i].addEventListener('touchend',function(){});
    }
}

I get Access Forbidden (Error 403) when setting up new alias

Apache 2.4 virtual hosts hack

1.In http.conf specify the ports , below “Listen”

Listen 80
Listen 4000
Listen 7000
Listen 9000
  1. In httpd-vhosts.conf

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"  
    ServerName hitesh_web.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
    Allow from all
    Require all granted
    </Directory>
    
    </VirtualHost>
    

    this is 2nd virtual host

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "E:/dabkick_git/DabKickWebsite"
    ServerName  www.my_mobile.dev
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
    
    <Directory "E:/dabkick_git/DabKickWebsite">
     Allow from all
     Require all granted
     </Directory>
    </VirtualHost>
    
  2. In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”

    127.0.0.1             localhost
    127.0.0.1             hitesh_web.dev
    127.0.0.1             www.my_mobile.dev
    127.0.0.1             demo.multisite.dev
    

4.now type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path

5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache

   <VirtualHost *:4000>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>

</VirtualHost>

this is the 2nd vhost

<VirtualHost *:7000>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName  www.dabkick_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common

<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>

Note: for port number given virtual hosts you have to ping in browser like “http://hitesh_web.dev:4000/” or “http://www.dabkick_mobile.dev:7000/

6.After doing all those changes you have to save the files and restart apache respectively.

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

How can I get a list of locally installed Python modules?

Here is a python code solution that will return a list of modules installed. One can easily modify the code to include version numbers.

import subprocess
import sys
from pprint import pprint

installed_packages = reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')
installed_packages = installed_packages.split('\r\n')
installed_packages = [pkg.split('==')[0] for pkg in installed_packages if pkg != '']
pprint(installed_packages)

What is "with (nolock)" in SQL Server?

My 2 cents - it makes sense to use WITH (NOLOCK) when you need to generate reports. At this point, the data wouldn't change much & you wouldn't want to lock those records.

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

git reset --soft origin/my_remote_tracking_branch

This way you will not loose your local changes

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

Steps:

1) Download git for windows https://git-scm.com/downloads

2) Install downloaded git with default setup

3) From Android Studio close if any project is open then Click on Configure -> Settings -> Version Control -> Git

4) Change Path to Git executable : git.exe to C:\Program Files\Git\cmd\git.exe

5) Apply and Ok

6) Try to clone from Check out project from Version Control

7) Done

enter image description here

How to print a int64_t type in C

Coming from the embedded world, where even uclibc is not always available, and code like

uint64_t myval = 0xdeadfacedeadbeef; printf("%llx", myval);

is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

char* ullx(uint64_t val)
{
    static char buf[34] = { [0 ... 33] = 0 };
    char* out = &buf[33];
    uint64_t hval = val;
    unsigned int hbase = 16;

    do {
        *out = "0123456789abcdef"[hval % hbase];
        --out;
        hval /= hbase;
    } while(hval);

    *out-- = 'x', *out = '0';

    return out;
}

How to paste into a terminal?

Gnome terminal defaults to ControlShiftv

OSX terminal defaults to Commandv. You can also use CommandControlv to paste the text in escaped form.

Windows 7 terminal defaults to CtrlShiftInsert

Default port for SQL Server

SQL Server default port is 1434.

To allow remote access I had to release those ports on my firewall:

Protocol  |   Port
---------------------
UDP       |   1050
TCP       |   1050
TCP       |   1433
UDP       |   1434

How to load CSS Asynchronously

Please care to update the answer as all of the above fails to impress google pagespeed insights now.

According to Google this is how you should implement async loading of Css

 < noscript id="deferred-styles" >
        < link rel="stylesheet" type="text/css" href="small.css"/ >
    < /noscript >

<script>
  var loadDeferredStyles = function() {
    var addStylesNode = document.getElementById("deferred-styles");
    var replacement = document.createElement("div");
    replacement.innerHTML = addStylesNode.textContent;
    document.body.appendChild(replacement)
    addStylesNode.parentElement.removeChild(addStylesNode);
  };
  var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
      window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
  else window.addEventListener('load', loadDeferredStyles);
</script>

How to read/write arbitrary bits in C/C++

int x = 0xFF;   //your number - 11111111

How do I for example read a 3 bit integer value starting at the second bit

int y = x & ( 0x7 << 2 ) // 0x7 is 111
                         // and you shift it 2 to the left

How to get value of a div using javascript

You can try this:

var theValue = document.getElementById("demo").getAttribute("value");

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

MVC Redirect to View from jQuery with parameters

This would also work I believe:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
            window.location.href = url; 
        })

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

What is the Eclipse shortcut for "public static void main(String args[])"?

To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.

enter image description here

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How to use multiple databases in Laravel

Using .env >= 5.0 (tested on 5.5)

In .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret

In config/database.php

'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],

'mysql2' => [
    'driver'    => env('DB_CONNECTION_SECOND'),
    'host'      => env('DB_HOST_SECOND'),
    'port'      => env('DB_PORT_SECOND'),
    'database'  => env('DB_DATABASE_SECOND'),
    'username'  => env('DB_USERNAME_SECOND'),
    'password'  => env('DB_PASSWORD_SECOND'),
],

Note: In mysql2 if DB_username and DB_password is same, then you can use env('DB_USERNAME') which is metioned in .env first few lines.

Without .env <5.0

Define Connections

app/config/database.php

return array(

    'default' => 'mysql',

    'connections' => array(

        # Primary/Default database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database1',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => '127.0.0.1',
            'database'  => 'database2',
            'username'  => 'root',
            'password'  => 'secret'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

Schema

To specify which connection to use, simply run the connection() method

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

Query Builder

$users = DB::connection('mysql2')->select(...);

Eloquent

Set the $connection variable in your model

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method or the on static method:

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2'); // non-static method

        $something = $someModel->find(1);

        $something = SomeModel::on('mysql2')->find(1); // static method

        return $something;
    }

}

Note Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.


From Laravel Docs

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

$users = DB::connection('foo')->select(...);

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection()->getPdo();

Useful Links

  1. Laravel 5 multiple database connection FROM laracasts.com
  2. Connect multiple databases in laravel FROM tutsnare.com
  3. Multiple DB Connections in Laravel FROM fideloper.com

Why do we check up to the square root of a prime number to determine if it is prime?

If a number n is not a prime, it can be factored into two factors a and b:

n = a * b

Now a and b can't be both greater than the square root of n, since then the product a * b would be greater than sqrt(n) * sqrt(n) = n. So in any factorization of n, at least one of the factors must be smaller than the square root of n, and if we can't find any factors less than or equal to the square root, n must be a prime.

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

Know relationships between all the tables of database in SQL Server

Microsoft Visio is probably the best I've came across, although as far as I know it won't automatically generate based on your relationships.

EDIT: try this in Visio, could give you what you need http://office.microsoft.com/en-us/visio-help/reverse-engineering-an-existing-database-HA001182257.aspx

Test if string is URL encoded in PHP

What about:

if (urldecode(trim($url)) == trim($url)) { $url_form = 'decoded'; }
  else { $url_form = 'encoded'; }

Will not work with double encoding but this is out of scope anyway I suppose?

Mapping a JDBC ResultSet to an object

I would like to hint on q2o. It is a JPA based Java object mapper which helps with many of the tedious SQL and JDBC ResultSet related tasks, but without all the complexity an ORM framework comes with. With its help mapping a ResultSet to an object is as easy as this:

while(rs.next()) {
    users.add(Q2Obj.fromResultSet(rs, User.class));
}

More about q2o can be found here.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I faced the same problem (ORA-01000) today. I had a for loop in the try{}, to execute a SELECT statement in an Oracle DB many times, (each time changing a parameter), and in the finally{} I had my code to close Resultset, PreparedStatement and Connection as usual. But as soon as I reached a specific amount of loops (1000) I got the Oracle error about too many open cursors.

Based on the post by Andrew Alcock above, I made changes so that inside the loop, I closed each resultset and each statement after getting the data and before looping again, and that solved the problem.

Additionaly, the exact same problem occured in another loop of Insert Statements, in another Oracle DB (ORA-01000), this time after 300 statements. Again it was solved in the same way, so either the PreparedStatement or the ResultSet or both, count as open cursors until they are closed.

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID

OR

global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

Convert datatable to JSON in C#

Try this custom function.

    public static string DataTableToJsonObj(DataTable dt)
    {
        DataSet ds = new DataSet();
        ds.Merge(dt);
        StringBuilder jsonString = new StringBuilder();

        if (ds.Tables[0].Rows.Count > 0)
        {
            jsonString.Append("[");
            for (int rows = 0; rows < ds.Tables[0].Rows.Count; rows++)
            {
                jsonString.Append("{");
                for (int cols = 0; cols < ds.Tables[0].Columns.Count; cols++)
                {
                    jsonString.Append(@"""" + ds.Tables[0].Columns[cols].ColumnName + @""":");

                    /* 
                    //IF NOT LAST PROPERTY

                    if (cols < ds.Tables[0].Columns.Count - 1)
                    {
                        GenerateJsonProperty(ds, rows, cols, jsonString);
                    }

                    //IF LAST PROPERTY

                    else if (cols == ds.Tables[0].Columns.Count - 1)
                    {
                        GenerateJsonProperty(ds, rows, cols, jsonString, true);
                    }
                    */

                    var b = (cols < ds.Tables[0].Columns.Count - 1)
                        ? GenerateJsonProperty(ds, rows, cols, jsonString)
                        : (cols != ds.Tables[0].Columns.Count - 1)
                          || GenerateJsonProperty(ds, rows, cols, jsonString, true);
                }
                jsonString.Append(rows == ds.Tables[0].Rows.Count - 1 ? "}" : "},");
            }
            jsonString.Append("]");
            return jsonString.ToString();
        }
        return null;
    }

    private static bool GenerateJsonProperty(DataSet ds, int rows, int cols, StringBuilder jsonString, bool isLast = false)
    {

        // IF LAST PROPERTY THEN REMOVE 'COMMA'  IF NOT LAST PROPERTY THEN ADD 'COMMA'
        string addComma = isLast ? "" : ",";

        if (ds.Tables[0].Rows[rows][cols] == DBNull.Value)
        {
            jsonString.Append(" null " + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(DateTime))
        {
            jsonString.Append(@"""" + (((DateTime)ds.Tables[0].Rows[rows][cols]).ToString("yyyy-MM-dd HH':'mm':'ss")) + @"""" + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(string))
        {
            jsonString.Append(@"""" + (ds.Tables[0].Rows[rows][cols]) + @"""" + addComma);
        }
        else if (ds.Tables[0].Columns[cols].DataType == typeof(bool))
        {
            jsonString.Append(Convert.ToBoolean(ds.Tables[0].Rows[rows][cols]) ? "true" : "fasle");
        }
        else
        {
            jsonString.Append(ds.Tables[0].Rows[rows][cols] + addComma);
        }

        return true;
    }

How does database indexing work?

Why is it needed?

When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.

Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires N/2 block accesses (on average), where N is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at N block accesses.

Whereas with a sorted field, a Binary Search may be used, which has log2 N block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.

What is indexing?

Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.

The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.

How does it work?

Firstly, let’s outline a sample database table schema;

Field name       Data type      Size on disk
id (Primary key) Unsigned INT   4 bytes
firstName        Char(50)       50 bytes
lastName         Char(50)       50 bytes
emailAddress     Char(100)      100 bytes

Note: char was used in place of varchar to allow for an accurate size on disk value. This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the id (a sorted key field) and one using the firstName (a non-key unsorted field).

Example 1 - sorted vs unsorted fields

Given our sample database of r = 5,000,000 records of a fixed size giving a record length of R = 204 bytes and they are stored in a table using the MyISAM engine which is using the default block size B = 1,024 bytes. The blocking factor of the table would be bfr = (B/R) = 1024/204 = 5 records per disk block. The total number of blocks required to hold the table is N = (r/bfr) = 5000000/5 = 1,000,000 blocks.

A linear search on the id field would require an average of N/2 = 500,000 block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of log2 1000000 = 19.93 = 20 block accesses. Instantly we can see this is a drastic improvement.

Now the firstName field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact N = 1,000,000 block accesses. It is this situation that indexing aims to correct.

Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the firstName field is outlined below;

Field name       Data type      Size on disk
firstName        Char(50)       50 bytes
(record pointer) Special        4 bytes

Note: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.

Example 2 - indexing

Given our sample database of r = 5,000,000 records with an index record length of R = 54 bytes and using the default block size B = 1,024 bytes. The blocking factor of the index would be bfr = (B/R) = 1024/54 = 18 records per disk block. The total number of blocks required to hold the index is N = (r/bfr) = 5000000/18 = 277,778 blocks.

Now a search using the firstName field can utilize the index to increase performance. This allows for a binary search of the index with an average of log2 277778 = 18.08 = 19 block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to 19 + 1 = 20 block accesses, a far cry from the 1,000,000 block accesses required to find a firstName match in the non-indexed table.

When should it be used?

Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.

Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.

Select from one table where not in another

Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)

Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.

On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.

Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.

Maven: How to include jars, which are not available in reps into a J2EE project?

@Ric Jafe's solution is what worked for me.

This is exactly what I was looking for. A way to push it through for research test code. Nothing fancy. Yeah I know that that's what they all say :) The various maven plugin solutions seem to be overkill for my purposes. I have some jars that were given to me as 3rd party libs with a pom file. I want it to compile/run quickly. This solution which I trivially adapted to python worked wonders for me. Cut and pasted into my pom. Python/Perl code for this task is in this Q&A: Can I add jars to maven 2 build classpath without installing them?

def AddJars(jarList):
  s1 = ''
  for elem in jarList:
   s1+= """
     <dependency>
        <groupId>local.dummy</groupId>
        <artifactId>%s</artifactId>
        <version>0.0.1</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/manual_jars/%s</systemPath>
     </dependency>\n"""%(elem, elem)
  return s1

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

Copy array by value

In my particular case I needed to ensure the array remained intact so this worked for me:

// Empty array
arr1.length = 0;
// Add items from source array to target array
for (var i = 0; i < arr2.length; i++) {
    arr1.push(arr2[i]);
}

Html.Raw() in ASP.NET MVC Razor view

The accepted answer is correct, but I prefer:

@{int count = 0;} 
@foreach (var item in Model.Resources) 
{ 
    @Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")  
    // some code 
    @Html.Raw(count <= 3 ? "</div>" : "")  
    @(count++)
} 

I hope this inspires someone, even though I'm late to the party.

Extract substring in Bash

Use cut:

echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2

More generic:

INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING

UITableViewCell Selected Background Color on Multiple Selection

UITableViewCell has an attribute multipleSelectionBackgroundView. https://developer.apple.com/documentation/uikit/uitableviewcell/1623226-selectedbackgroundview

Just create an UIView define the .backgroundColor of your choice and assign it to your cells .multipleSelectionBackgroundView attribute.

List all devices, partitions and volumes in Powershell

To get all of the file system drives, you can use the following command:

gdr -PSProvider 'FileSystem'

gdr is an alias for Get-PSDrive, which includes all of the "virtual drives" for the registry, etc.

Interpreting "condition has length > 1" warning from `if` function

Just adding a point to the whole discussion as to why this warning comes up (It wasn't clear to me before). The reason one gets this is as mentioned before is because 'a' in this case is a vector and the inequality 'a>0' produces another vector of TRUE and FALSE (where 'a' is >0 or not).

If you would like to instead test if any value of 'a>0', you can use functions - 'any' or 'all'

Best

Getting time and date from timestamp with php

Optionally you can use database function for date/time formatting. For example in MySQL query use:

SELECT DATE_FORMAT(DATETIMEAPP,'%d-%m-%Y') AS date, DATE_FORMT(DATETIMEAPP,'%H:%i:%s') AS time FROM yourtable

I think that over databases provides solutions for date formatting too

Spring security CORS Filter

There's 8 hours of my life I will never get back...

Make sure that you set both Exposed Headers AND Allowed Headers in your CorsConfiguration

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Changing the default title of confirm() in JavaScript?

YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)

var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
    // what to do if answer "YES"
}else{
    // what to do if answer "NO"
}

Enjoy it!

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

Getting A File's Mime Type In Java

Unfortunately,

mimeType = file.toURL().openConnection().getContentType();

does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.

However, you have this:

mimeType= URLConnection.guessContentTypeFromName(file.getName());

and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream

However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).

Check file size before upload

I created a jQuery version of PhpMyCoder's answer:

$('form').submit(function( e ) {    
    if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
        //Prevent default and display error
        alert("File is wrong type or over 10Mb in size!");
        e.preventDefault();
    }
});

function get_extension(filename) {
    return filename.split('.').pop().toLowerCase();
}

C# List<> Sort by x then y

For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

Warning :-Presenting view controllers on detached view controllers is discouraged

To avoid getting the warning in a push navigation, you can directly use :

[self.view.window.rootViewController presentViewController:viewController animated:YES completion:nil];

And then in your modal view controller, when everything is finished, you can just call :

[self dismissViewControllerAnimated:YES completion:nil];

Get the cartesian product of a series of lists?

I would use list comprehension :

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]

Convert UTC/GMT time to local time

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

How do we adjust for the extra hour?

Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

By the looks the code might look something like:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.

How to convert int[] to Integer[] in Java?

you don't need. int[] is an object and can be used as a key inside a map.

Map<int[], Double> frequencies = new HashMap<int[], Double>();

is the proper definition of the frequencies map.

This was wrong :-). The proper solution is posted too :-).

How to detect incoming calls, in an Android device?

You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED This will call your received whenever the phone-state changes from idle, ringing, offhook so from the previous value and the new value you can detect if this is an incoming/outgoing call.

Required permission would be:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

But if you also want to receive the EXTRA_INCOMING_NUMBER in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"

And the code something like this:

val receiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "onReceive")
    }
}

override fun onResume() {
    val filter = IntentFilter()
    filter.addAction("android.intent.action.PHONE_STATE")
    registerReceiver(receiver, filter)
    super.onResume()
}

override fun onPause() {
    unregisterReceiver(receiver)
    super.onPause()
}

and in receiver class, we can get current state by reading intent like this:

intent.extras["state"]

the result of extras could be:

RINGING -> If your phone is ringing

OFFHOOK -> If you are talking with someone (Incoming or Outcoming call)

IDLE -> if call ended (Incoming or Outcoming call)

With PHONE_STATE broadcast we don't need to use PROCESS_OUTGOING_CALLS permission or deprecated NEW_OUTGOING_CALL action.

How to avoid a System.Runtime.InteropServices.COMException?

Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.

You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException. Tick the option to break when it's thrown and then debug your application.

Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

jQuery `.is(":visible")` not working in Chrome

I don't know why your code doesn't work on chrome, but I suggest you use some workarounds :

$el.is(':visible') === $el.is(':not(:hidden)');

or

$el.is(':visible') === !$el.is(':hidden');  

If you are certain that jQuery gives you some bad results in chrome, you can just rely on the css rule checking :

if($el.css('display') !== 'none') {
    // i'm visible
}

Plus, you might want to use the latest jQuery because it might have bugs from older version fixed.

How to write a confusion matrix in Python?

Here is a simple implementation that handles an unequal number of classes in the predicted and actual labels (see examples 3 and 4). I hope this helps!

For folks just learning this, here's a quick review. The labels for the columns indicate the predicted class, and the labels for the rows indicate the correct class. In example 1, we have [3 1] on the top row. Again, rows indicate truth, so this means that the correct label is "0" and there are 4 examples with ground truth label of "0". Columns indicate predictions, so we have 3/4 of the samples correctly labeled as "0", but 1/4 was incorrectly labeled as a "1".

def confusion_matrix(actual, predicted):
    classes       = np.unique(np.concatenate((actual,predicted)))
    confusion_mtx = np.empty((len(classes),len(classes)),dtype=np.int)
    for i,a in enumerate(classes):
        for j,p in enumerate(classes):
            confusion_mtx[i,j] = np.where((actual==a)*(predicted==p))[0].shape[0]
    return confusion_mtx

Example 1:

actual    = np.array([1,1,1,1,0,0,0,0])
predicted = np.array([1,1,1,1,0,0,0,1])
confusion_matrix(actual,predicted)

   0  1
0  3  1
1  0  4

Example 2:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","a"])
confusion_matrix(actual,predicted)

   0  1
0  4  0
1  1  3

Example 3:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","z"]) # <-- notice the 3rd class, "z"
confusion_matrix(actual,predicted)

   0  1  2
0  4  0  0
1  0  3  1
2  0  0  0

Example 4:

actual    = np.array(["a","a","a","x","x","b","b","b"]) # <-- notice the 4th class, "x"
predicted = np.array(["a","a","a","a","b","b","b","z"])
confusion_matrix(actual,predicted)

   0  1  2  3
0  3  0  0  0
1  0  2  0  1
2  1  1  0  0
3  0  0  0  0

Using getResources() in non-activity class

There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.

Follow the steps to access getResources() in a non activity class without passing a context through the object.

  • Create a subclass of Application, for instance public class App extends Application {. Refer the code next to the steps.
  • Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
  • In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getContext().
  • Now you can use: App.getContext() whenever you want to get a context, and then we can use App.getContext().getResources() to get values from the resources.

This is how it should look:

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}

How to increase Maximum Upload size in cPanel?

Unfortunately, this is something you will have to ask you provider to do.

If your the owner of the server and can login to WHM it's under:

Tweak Settings => PHP Settings => Maximum Upload Size

Newer version have it listed under:

Home => Service Configuration => PHP Configuration Editor => Tweak Settings => PHP

How do I check if file exists in Makefile so I can delete it?

The second top answer mentions ifeq, however, it fails to mention that these must be on the same level as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:

download:
ifeq (,$(wildcard ./glob.c))
    curl … -o glob.c
endif

# THIS DOES NOT WORK!
download:
    ifeq (,$(wildcard ./glob.c))
        curl … -o glob.c
    endif

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

Whereas @jbarrueta answer is perfect, in the 2.12 version of Jackson was introduced a new long-awaited type for the @JsonTypeInfo annotation, DEDUCTION.

It is useful for the cases when you have no way to change the incoming json or must not do so. I'd still recommend to use use = JsonTypeInfo.Id.NAME, as the new way may throw an exception in complex cases when it has no way to determine which subtype to use.

Now you can simply write

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
    @JsonSubTypes.Type(Dog.class),
    @JsonSubTypes.Type(Cat.class) }
)
public abstract class Animal {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

And it will produce {"name":"ruffus", "breed":"english shepherd"} and {"name":"goya", "favoriteToy":"mice"}

Once again, it's safer to use NAME if some of the fields may be not present, like breed or favoriteToy.

Python dictionary: are keys() and values() always the same order?

I wasn't satisfied with these answers since I wanted to ensure the exported values had the same ordering even when using different dicts.

Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

keys = dict1.keys()
ordered_keys1 = [dict1[cur_key] for cur_key in keys]
ordered_keys2 = [dict2[cur_key] for cur_key in keys]

conversion from infix to prefix

https://en.wikipedia.org/wiki/Shunting-yard_algorithm

The shunting yard algorithm can also be applied to produce prefix notation (also known as polish notation). To do this one would simply start from the end of a string of tokens to be parsed and work backwards, reverse the output queue (therefore making the output queue an output stack), and flip the left and right parenthesis behavior (remembering that the now-left parenthesis behavior should pop until it finds a now-right parenthesis).

from collections import deque
def convertToPN(expression):
    precedence = {}
    precedence["*"] = precedence["/"] = 3
    precedence["+"] = precedence["-"] = 2
    precedence[")"] = 1

    stack  = []
    result = deque([])
    for token in expression[::-1]:
        if token == ')':
            stack.append(token)
        elif token == '(':
            while stack:
                t = stack.pop()
                if t == ")": break
                result.appendleft(t)
        elif token not in precedence:
            result.appendleft(token)
        else:
            # XXX: associativity should be considered here
            # https://en.wikipedia.org/wiki/Operator_associativity
            while stack and precedence[stack[-1]] > precedence[token]:
                result.appendleft(stack.pop())
            stack.append(token)

    while stack:
        result.appendleft(stack.pop())

    return list(result)

expression = "(a - b) / c * (d + e - f / g)".replace(" ", "")
convertToPN(expression)

step through:

step 1 : token ) ; stack:[ ) ]
result:[  ]
step 2 : token g ; stack:[ ) ]
result:[ g ]
step 3 : token / ; stack:[ ) / ]
result:[ g ]
step 4 : token f ; stack:[ ) / ]
result:[ f g ]
step 5 : token - ; stack:[ ) - ]
result:[ / f g ]
step 6 : token e ; stack:[ ) - ]
result:[ e / f g ]
step 7 : token + ; stack:[ ) - + ]
result:[ e / f g ]
step 8 : token d ; stack:[ ) - + ]
result:[ d e / f g ]
step 9 : token ( ; stack:[  ]
result:[ - + d e / f g ]
step 10 : token * ; stack:[ * ]
result:[ - + d e / f g ]
step 11 : token c ; stack:[ * ]
result:[ c - + d e / f g ]
step 12 : token / ; stack:[ * / ]
result:[ c - + d e / f g ]
step 13 : token ) ; stack:[ * / ) ]
result:[ c - + d e / f g ]
step 14 : token b ; stack:[ * / ) ]
result:[ b c - + d e / f g ]
step 15 : token - ; stack:[ * / ) - ]
result:[ b c - + d e / f g ]
step 16 : token a ; stack:[ * / ) - ]
result:[ a b c - + d e / f g ]
step 17 : token ( ; stack:[ * / ]
result:[ - a b c - + d e / f g ]

# the final while
step 18 : token ( ; stack:[  ]
result:[ * / - a b c - + d e / f g ]

CodeIgniter removing index.php from url

Follow these step your problem will be solved

1- Download .htaccess file from here https://www.dropbox.com/s/tupcu1ctkb8pmmd/.htaccess?dl=0

2- Change the CodeIgnitor directory name on Line #5. like my directory name is abc (add your name)

3- Save .htaccess file on main directory (abc) of your codeignitor folder

4- Change uri_protocol from AUTO to PATH_INFO in Config.php file

Note: First of all you have to enable mod_rewrite from httpd.conf of apachi by removing the comments

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

Is Laravel really this slow?

I faced 1.40s while working with a pure laravel in development area!

the problem was using: php artisan serve to run the webserver

when I used apache webserver (or NGINX) instead for the same code I got it down to 153ms

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Visual Studio 2017: Display method references

For display references on the top of method you have to enabled the CodeLens option in Visual Studio Professional and Visual Studio Enterprise.

Use below steps to enabled it.

1. Go to Tools and then select Options :

enter image description here

2. Then Select Text Editor -> All Languages -> CodeLens

enter image description here

3. Click on check box to Enable Code Lens: enter image description here

Now you can see the references on the top of methods.

This will not work for VS - Community Edition.

Cheers!

How to use XMLReader in PHP?

The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:

$xml_reader = new XMLReader;
$xml_reader->open($feed_url);

// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');

// loop through the products
while ($xml_reader->name == 'product')
{
    // load the current xml element into simplexml and we’re off and running!
    $xml = simplexml_load_string($xml_reader->readOuterXML());

    // now you can use your simpleXML object ($xml).
    echo $xml->element_1;

    // move the pointer to the next product
    $xml_reader->next('product');
}

// don’t forget to close the file
$xml_reader->close();

Using AES encryption in C#

Look at sample in here..

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=VS.100).aspx#Y2262

The example on MSDN does not run normally (an error occurs) because there is no initial value of Initial Vector(iv) and Key. I add 2 line code and now work normally.

More details see below:

using System.Windows.Forms;
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace AES_TESTER
{
   public partial class Form1 : Form
   {
       public Form1()
       {
          InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {
          try
          {

            string original = "Here is some data to encrypt!";
            MessageBox.Show("Original:   " + original);

            // Create a new instance of the RijndaelManaged
            // class.  This generates a new key and initialization 
            // vector (IV).
            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                 myRijndael.GenerateKey();
                 myRijndael.GenerateIV();

                // Encrypt the string to an array of bytes.
                byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                StringBuilder s = new StringBuilder();
                foreach (byte item in encrypted)
                {
                   s.Append(item.ToString("X2") + " ");
                }
                MessageBox.Show("Encrypted:   " + s);

                // Decrypt the bytes to a string.
                string decrypted = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                //Display the original data and the decrypted data.
                MessageBox.Show("Decrypted:    " + decrypted);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: {0}", ex.Message);
        }
    }

    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        byte[] encrypted;
        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.Zeros;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }


        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

    static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.Zeros;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
     }
   }
}

iOS 7: UITableView shows under status bar

For Xcode 7, un-ticking the 'translucent' check mark for the Navigation Bar worked for me.

enter image description here

Linux bash: Multiple variable assignment

First thing that comes into my mind:

read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"

output is, unsurprisingly

1|2|3

Can I use a binary literal in C or C++?

A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:

#define B_0000    0
#define B_0001    1
#define B_0010    2
#define B_0011    3
#define B_0100    4
#define B_0101    5
#define B_0110    6
#define B_0111    7
#define B_1000    8
#define B_1001    9
#define B_1010    a
#define B_1011    b
#define B_1100    c
#define B_1101    d
#define B_1110    e
#define B_1111    f

#define _B2H(bits)    B_##bits
#define B2H(bits)    _B2H(bits)
#define _HEX(n)        0x##n
#define HEX(n)        _HEX(n)
#define _CCAT(a,b)    a##b
#define CCAT(a,b)   _CCAT(a,b)

#define BYTE(a,b)        HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d)    HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h)    HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )

// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;

Disadvantages (it's not such a big ones):

  • The binary numbers have to be grouped 4 by 4;
  • The binary literals have to be only unsigned integer numbers;

Advantages:

  • Total preprocessor driven, not spending processor time in pointless operations (like "?.. :..", "<<", "+") to the executable program (it may be performed hundred of times in the final application);
  • It works "mainly in C" compilers and C++ as well (template+enum solution works only in C++ compilers);
  • It has only the limitation of "longness" for expressing "literal constant" values. There would have been earlyish longness limitation (usually 8 bits: 0-255) if one had expressed constant values by parsing resolve of "enum solution" (usually 255 = reach enum definition limit), differently, "literal constant" limitations, in the compiler allows greater numbers;
  • Some other solutions demand exaggerated number of constant definitions (too many defines in my opinion) including long or several header files (in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()");
  • Simplicity of the solution: easily readable, understandable and adjustable for other cases (could be extended for grouping 8 by 8 too);

How do I do a Date comparison in Javascript?

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

Add A Year To Today's Date

Use the Date.prototype.setFullYear method to set the year to what you want it to be.

For example:

var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);

There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.

meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]

Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

How to see the changes in a Git commit?

For checking complete changes:

  git diff <commit_Id_1> <commit_Id_2>

For checking only the changed/added/deleted files:

  git diff <commit_Id_1> <commit_Id_2> --name-only

NOTE: For checking diff without commit in between, you don't need to put the commit ids.

Submitting a multidimensional array via POST with php

I made a function which handles arrays as well as single GET or POST values

function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode

    $retVal = "";
    $retArray = array();

    if($isArray) {
        if(isset($_POST[$varName])) {
            foreach ( $_POST[$varName] as $var ) {  // multidimensional POST array elements
                $retArray[]=$var;
            }
        }
        $retVal=$retArray;
    }

    elseif (isset($_POST[$varName]) )  {  // simple POST array element
        $retVal = $_POST[$varName];
    }

    else {
        if (isset($_GET[$varName]) ) {
            $retVal = $_GET[$varName];    // simple GET array element
        }
        else {
            $retVal = $default;
        }
    }

    return $retVal;

}

Examples:

$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");

C subscripted value is neither array nor pointer nor vector when assigning an array element value

You have "int* arr" so "arr[n]" is an int, right? Then your "[M - 1 + 1]" bit is trying to use that int as an array/pointer/vector.

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

Why are interface variables static and final by default?

Interface : System requirement service.

In interface, variable are by default assign by public,static,final access modifier. Because :

public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.

static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of interface_filename.variable_name

final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.

Removing display of row names from data frame

If you want to format your table via kable, you can use row.names = F

kable(df, row.names = F)

Get month name from date in Oracle

Try this

select to_char(SYSDATE,'Month') from dual;

for full name and try this

select to_char(SYSDATE,'Mon') from dual;

for abbreviation

you can find more option here:

https://www.techonthenet.com/oracle/functions/to_char.php

Changing the JFrame title

I strongly recommend you learn how to use layout managers to get the layout you want to see. null layouts are fragile, and cause no end of trouble.

Try this source & check the comments.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class VolumeCalculator extends JFrame implements ActionListener {
    private JTabbedPane jtabbedPane;
    private JPanel options;
    JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
            hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
            myTitle;
    JTextArea labelTubStatus;

    public VolumeCalculator(){
        setSize(400, 250);
        setVisible(true);
        setSize(400, 250);
        setVisible(true);
        setTitle("Volume Calculator");
        setSize(300, 200);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel);

        createOptions();

        jtabbedPane = new JTabbedPane();

        jtabbedPane.addTab("Options", options);

        topPanel.add(jtabbedPane, BorderLayout.CENTER);
    }
    /* CREATE OPTIONS */

    public void createOptions(){
        options = new JPanel();
        //options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        JTextField newTitle = new JTextField("Some Title");
        //newTitle.setBounds(80, 40, 225, 20);    
        options.add(newTitle);
        myTitle = new JTextField(20);
        // myTitle WAS NEVER ADDED to the GUI!
        options.add(myTitle);
        //myTitle.setBounds(80, 40, 225, 20);
        //myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        //newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        //Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

    public void actionPerformed(ActionEvent event){
        JButton button = (JButton) event.getSource();
        String buttonLabel = button.getText();
        if ("Exit".equalsIgnoreCase(buttonLabel)){
            Exit_pressed();
            return;
        }
        if ("Set New Name".equalsIgnoreCase(buttonLabel)){
            New_Name();
            return;
        }
    }

    private void Exit_pressed(){
        System.exit(0);
    }

    private void New_Name(){
        System.out.println("'" + myTitle.getText() + "'");
        this.setTitle(myTitle.getText());
    }

    private void Options(){
    }

    public static void main(String[] args){
        JFrame frame = new VolumeCalculator();
        frame.pack();
        frame.setSize(380, 350);
        frame.setVisible(true);
    }
}

Difference between SurfaceView and View?

A few things I've noted:

  • SurfaceViews contain a nice rendering mechanism that allows threads to update the surface's content without using a handler (good for animation).
  • Surfaceviews cannot be transparent, they can only appear behind other elements in the view hierarchy.
  • I've found that they are much faster for animation than rendering onto a View.

For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.

package javax.mail and javax.mail.internet do not exist

Download javax.mail.jar and add it to your project using the following steps:

  1. Extract the mail.jar file
  2. Right click the project node (JavaMail), click Properties to change properties of the project
  3. Now go to Libraries Tab
  4. Click on Add JAR/Folder Button. A window opens up.
  5. Browse to the location where you have unzipped your Mail.jar
  6. Press ok
  7. Compile your program to check whether the JAR files have been successfully included

Order of items in classes: Fields, Properties, Constructors, Methods

I don't know about a language or industry standard, but I tend to put things in this order with each section wrapped in a #region:

using Statements

Namespace

Class

Private members

Public properties

Constructors

Public methods

Private methods

CSS rounded corners in IE8

http://fetchak.com/ie-css3/ works for IE 6+. Use this if css3pie doesn't work for you.

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

What is the most efficient way to store a list in the Django models?

Using one-to-many relation (FK from Friend to parent class) will make your app more scalable (as you can trivially extend the Friend object with additional attributes beyond the simple name). And thus this is the best way

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

How do I mock a static method that returns void with PowerMock?

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

Putting a simple if-then-else statement on one line

That's more specifically a ternary operator expression than an if-then, here's the python syntax

value_when_true if condition else value_when_false

Better Example: (thanks Mr. Burns)

'Yes' if fruit == 'Apple' else 'No'

Now with assignment and contrast with if syntax

fruit = 'Apple'
isApple = True if fruit == 'Apple' else False

vs

fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

How to write specific CSS for mozilla, chrome and IE

You could use php to echo the browser name as a body class, e.g.

<body class="mozilla">

Then, your conditional CSS would look like

.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}

HTTP response header content disposition for attachments

Try the Content-Disposition header

Content-Disposition: attachment; filename=<file name.ext> 

cannot make a static reference to the non-static field

you can keep your withdraw and deposit methods static if you want however you'd have to write it like the code below. sb = starting balance and eB = ending balance.

Account account = new Account(1122, 20000, 4.5);

    double sB = Account.withdraw(account.getBalance(), 2500);
    double eB = Account.deposit(sB, 3000);
    System.out.println("Balance is " + eB);
    System.out.println("Monthly interest is " + (account.getAnnualInterestRate()/12));
    account.setDateCreated(new Date());
    System.out.println("The account was created " + account.getDateCreated());

Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference : https://stackoverflow.com/a/3145655/28557

-----------------------Update-----------------------

Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site : http://developer.android.com/google/play-services/location.html

Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example

http://blog.lemberg.co.uk/fused-location-provider

--------------------------------------------------------

When to use Common Table Expression (CTE)

One example, if you need to reference/join the same data set multiple times you can do so by defining a CTE. Therefore, it can be a form of code re-use.

An example of self referencing is recursion: Recursive Queries Using CTE

For exciting Microsoft definitions Taken from Books Online:

A CTE can be used to:

  • Create a recursive query. For more information, see Recursive Queries Using Common Table Expressions.

  • Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.

  • Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access.

  • Reference the resulting table multiple times in the same statement.

What do two question marks together mean in C#?

?? is there to provide a value for a nullable type when the value is null. So, if formsAuth is null, it will return new FormsAuthenticationWrapper().

How to enable scrolling on website that disabled scrolling?

In a browser like Chrome etc.:

  1. Inspect the code (for e.g. in Chrome press ctrl + shift + c);
  2. Set overflow: visible on body element (for e.g., <body style="overflow: visible">)
  3. Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
    • To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
    • If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).

Good luck!

Add directives from directive in AngularJS

Here's a solution that moves the directives that need to be added dynamically, into the view and also adds some optional (basic) conditional-logic. This keeps the directive clean with no hard-coded logic.

The directive takes an array of objects, each object contains the name of the directive to be added and the value to pass to it (if any).

I was struggling to think of a use-case for a directive like this until I thought that it might be useful to add some conditional logic that only adds a directive based on some condition (though the answer below is still contrived). I added an optional if property that should contain a bool value, expression or function (e.g. defined in your controller) that determines if the directive should be added or not.

I'm also using attrs.$attr.dynamicDirectives to get the exact attribute declaration used to add the directive (e.g. data-dynamic-directive, dynamic-directive) without hard-coding string values to check for.

Plunker Demo

_x000D_
_x000D_
angular.module('plunker', ['ui.bootstrap'])_x000D_
    .controller('DatepickerDemoCtrl', ['$scope',_x000D_
        function($scope) {_x000D_
            $scope.dt = function() {_x000D_
                return new Date();_x000D_
            };_x000D_
            $scope.selects = [1, 2, 3, 4];_x000D_
            $scope.el = 2;_x000D_
_x000D_
            // For use with our dynamic-directive_x000D_
            $scope.selectIsRequired = true;_x000D_
            $scope.addTooltip = function() {_x000D_
                return true;_x000D_
            };_x000D_
        }_x000D_
    ])_x000D_
    .directive('dynamicDirectives', ['$compile',_x000D_
        function($compile) {_x000D_
            _x000D_
             var addDirectiveToElement = function(scope, element, dir) {_x000D_
                var propName;_x000D_
                if (dir.if) {_x000D_
                    propName = Object.keys(dir)[1];_x000D_
                    var addDirective = scope.$eval(dir.if);_x000D_
                    if (addDirective) {_x000D_
                        element.attr(propName, dir[propName]);_x000D_
                    }_x000D_
                } else { // No condition, just add directive_x000D_
                    propName = Object.keys(dir)[0];_x000D_
                    element.attr(propName, dir[propName]);_x000D_
                }_x000D_
            };_x000D_
            _x000D_
            var linker = function(scope, element, attrs) {_x000D_
                var directives = scope.$eval(attrs.dynamicDirectives);_x000D_
        _x000D_
                if (!directives || !angular.isArray(directives)) {_x000D_
                    return $compile(element)(scope);_x000D_
                }_x000D_
               _x000D_
                // Add all directives in the array_x000D_
                angular.forEach(directives, function(dir){_x000D_
                    addDirectiveToElement(scope, element, dir);_x000D_
                });_x000D_
                _x000D_
                // Remove attribute used to add this directive_x000D_
                element.removeAttr(attrs.$attr.dynamicDirectives);_x000D_
                // Compile element to run other directives_x000D_
                $compile(element)(scope);_x000D_
            };_x000D_
        _x000D_
            return {_x000D_
                priority: 1001, // Run before other directives e.g.  ng-repeat_x000D_
                terminal: true, // Stop other directives running_x000D_
                link: linker_x000D_
            };_x000D_
        }_x000D_
    ]);
_x000D_
<!doctype html>_x000D_
<html ng-app="plunker">_x000D_
_x000D_
<head>_x000D_
    <script src="//code.angularjs.org/1.2.20/angular.js"></script>_x000D_
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>_x000D_
    <script src="example.js"></script>_x000D_
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <div data-ng-controller="DatepickerDemoCtrl">_x000D_
_x000D_
        <select data-ng-options="s for s in selects" data-ng-model="el" _x000D_
            data-dynamic-directives="[_x000D_
                { 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },_x000D_
                { 'tooltip-placement' : 'bottom' },_x000D_
                { 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }_x000D_
            ]">_x000D_
            <option value=""></option>_x000D_
        </select>_x000D_
_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Change some value inside the List<T>

This is the way I would do it : saying that "list" is a <List<t>> where t is a class with a Name and a Value field; but of course you can do it with any other class type.

    list = list.Where(c=>c.Name == "height")
        .Select( new t(){Name = c.Name, Value = 30})
        .Union(list.Where(c=> c.Name != "height"))
        .ToList();

This works perfectly ! It's a simple linq expression without any loop logic. The only thing you should be aware is that the order of the lines in the result dataset will be different from the order you had in the source dataset. So if sorting is important to you, just reproduce the same order by clauses in the final linq query.

Getting data from selected datagridview row and which event?

First take a label. set its visibility to false, then on the DataGridView_CellClick event write this

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
    // then perform your select statement according to that label.
}
//try it it might work for you

Creating layout constraints programmatically

Swift version

Updated for Swift 3

This example will show two methods to programmatically add the following constraints the same as if doing it in the Interface Builder:

Width and Height

enter image description here

Center in Container

enter image description here

Boilerplate code

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here (choose one of the methods below)
    // ...
}

Method 1: Anchor Style

// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true

// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true

// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • See also the Programmatically Creating Constraints documentation.
  • See this answer for a similar example of adding a pinning constraint.

iPhone - Get Position of UIView within entire UIWindow

That's an easy one:

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  1. don't change when rotating the device.
  2. always have their origin in the top left corner of the unrotated screen.
  3. are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.