Programs & Examples On #Xcode

Xcode is Apple's integrated development environment (IDE). USAGE NOTE: Use this tag only for questions about the Xcode IDE itself, and not for general Mac or iOS programming topics. Use [cocoa] for Mac programming questions, and [cocoa-touch] or [ios] or [Swift] for iOS programming questions.

Change tab bar item selected color in a storyboard

Add Runtime Color attribute named "tintColor" from StoryBoard. This is working(for Xcode 8 and above).

if you want unselected color.. you can add unselectedItemTintColor too.

setting tintColor as Runtime Attribute

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Fixed by rebooting my phone after deleting the app, then rebuilding it clean and running again. Works fine now.

Weird.

UICollectionView Set number of columns

If you are lazy using delegate.

extension UICollectionView {
    func setItemsInRow(items: Int) {
        if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
            let contentInset = self.contentInset
            let itemsInRow: CGFloat = CGFloat(items);
            let innerSpace = layout.minimumInteritemSpacing * (itemsInRow - 1.0)
            let insetSpace = contentInset.left + contentInset.right + layout.sectionInset.left + layout.sectionInset.right
            let width = floor((CGRectGetWidth(frame) - insetSpace - innerSpace) / itemsInRow);
            layout.itemSize = CGSizeMake(width, width)
        }
    }
}

PS: Should be called after rotation too

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

To add .pch file-

1) Add new .pch file to your project->New file->other->PCH file

2) Goto your project's build setting.

3) Search "prefix header". You can find that under Apple LLVM.

4) Paste this in the field $(SRCROOT)/yourPrefixHeaderFileName.pch

5) Clean and build the project. That's it!!!

enter image description here

Set a button background image iPhone programmatically

This will work

UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was doing what doug suggests ("Reset Content and Settings") which works but takes a lot of time and it is really annoying... until I recently found completely accidental another solution that is much quicker and seems to also work so far! Just hit cmd+L on your simulator or go to the simulator menu "Hardware -> Lock", which locks the screen, when you unlock the screen the app works like nothing ever happened :)

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:

iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.

The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.

Update:

There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.

http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

How can I add NSAppTransportSecurity to my info.plist file?

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>com</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>net</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>org</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

This will allow to connect to .com .net .org

iPhone get SSID without private library

Here's the cleaned up ARC version, based on @elsurudo's code:

- (id)fetchSSIDInfo {
     NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
     NSLog(@"Supported interfaces: %@", ifs);
     NSDictionary *info;
     for (NSString *ifnam in ifs) {
         info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
         NSLog(@"%@ => %@", ifnam, info);
         if (info && [info count]) { break; }
     }
     return info;
}

How to print out the method name and line number and conditionally disable NSLog?

There are a new trick that no answer give. You can use printf instead NSLog. This will give you a clean log:

With NSLog you get things like this:

2011-11-03 13:43:55.632 myApp[3739:207] Hello Word

But with printf you get only:

Hello World

Use this code

#ifdef DEBUG
    #define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
    #define NSLog(...) {}              
#endif

How can I programmatically determine if my app is running in the iphone simulator?

My answer is based on @Daniel Magnusson answer and comments of @Nuthatch and @n.Drake. and I write it to save some time for swift users working on iOS9 and onwards.

This is what worked for me:

if UIDevice.currentDevice().name.hasSuffix("Simulator"){
    //Code executing on Simulator
} else{
    //Code executing on Device
}

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

It seems that you can transfer your Certificates and Provisioning profiles from one machine to the other, so if you are having issues in setting up your certificate and/or profiles because you migrated your Dev machine, have a look at this:

how to transfer xcode certificates between macs

A server with the specified hostname could not be found

I faced this issue when we changed from one domain to another for API service.

Restarting the network router/modem fixed this issue.

Xcode Debugger: view value of variable

Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.

The expresion

indexPath.row

is equivalent to

[indexPath row]

and the assignment

delegate.myData = [myData objectAtIndex:indexPath.row];

is equivalent to

[delegate setMyData:[myData objectAtIndex:[indexPath row]]];

assuming standard naming for synthesised properties.

Furthermore, delegate is probably declared as being of type id<SomeProtocol>, i.e., the compiler hasn’t been able to provide actual type information for delegate at that point, and the debugger is relying on information provided at compile-time. Since id is a generic type, there’s no compile-time information about the instance variables in delegate.

Those are the reasons why you don’t see myData or row as variables.

If you want to inspect the result of sending -row or -myData, you can use commands p or po:

p (NSInteger)[indexPath row]
po [delegate myData]

or use the expressions window (for instance, if you know your delegate is of actual type MyClass *, you can add an expression (MyClass *)delegate, or right-click delegate, choose View Value as… and type the actual type of delegate (e.g. MyClass *).

That being said, I agree that the debugger could be more helpful:

  • There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;

  • Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.

Xcode is not currently available from the Software Update server

I had to run Xcode.app and agree to the License Agreement

Setup: Brand new MacBook with Mavericks, then brew install and other c/l type things 'just work'.

How can I regenerate ios folder in React Native project?

The process you need to follow is so similar to renaming a react native app. Basically you just need to run react-native upgrade in your root project directory. For further info you can check another question here. The instructions below explains how to create another react native project based on a copied one with a new name.

  • First copy the directory which your to-be-name-changed application exists. And go to your newly cloned directory.
  • Change the name at index.ios/android.js file which is given as a parameter to AppRegistry.
  • Change the name and version accordingly on package.json
  • Delete /ios and /android folders which are remaining from your older app.
  • Run $react-native upgrade to generate /ios and /android folders again.
  • Run $react-native link for any native dependency.
  • Finally run $react-native run-ios or anything you want.

How to pass prepareForSegue: an object

I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.

This basic example works like this:

enter image description here

The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

First View Controller

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // get a reference to the second view controller
        let secondViewController = segue.destinationViewController as! SecondViewController

        // set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}

Second View Controller

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}

Remember to

  • Make the segue by control clicking on the button and draging it over to the Second View Controller.
  • Hook up the outlets for the UITextField and the UILabel.
  • Set the first and second View Controllers to the appropriate Swift files in IB.

Source

How to send data through segue (swift) (YouTube tutorial)

See also

View Controllers: Passing data forward and passing data back (fuller answer)

Hide strange unwanted Xcode logs

Alright. There seems to be a lot of commotion about this one, so I'll give y'all a way to persist it without using that scheme trick. I'll address the iOS Simulator specifically, but this also might need to be applied for the TV Sim as well which is located in a different dir.

The problem that is causing all of this stuff are plists located within the Xcode directory. There is a process that gets launched called configd_sim when the Sim starts that reads the plists in and prints debugging information if the plists specify they should be logged.

The plists are located here:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Preferences/Logging/Subsystems

If you are playing around with a beta, take note that the dir will be different.

You will see numerous plists in this directory. Now, build and run your application and observe the logs. You are looking for the content immediately followed by the subsystem: part. It is the name immediately following this that represents the corresponding problematic plist.

enter image description here

From there, either modify the plist to knock out the debugging [Level] key/value which is a dictionary containing the "Enable" => "Default" key/value... or just simply delete the plist. Note, that you will need to be root to do either of these since they're located in the Xcode application.

the plutil -p command might be of use to you as well. i.e.

plutil -p /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/System/Library/Preferences/Logging/Subsystems/com.apple.BackBoardServices.fence.plist

This gave me one of the problematic plists which contained:

{ "DEFAULT-OPTIONS" => { "Level" => { "Enable" => "Default" }}}

Good luck :]

/usr/bin/codesign failed with exit code 1

One possible cause is that you doesn't have permission to write on the build directory.

Solution: Delete all build directory on your project folder and rebuild your application.

How to make a simple rounded button in Storyboard?

While adding layer.cornerRadius in the storyboard make sure that you don't have leading or trailing spaces. If you do copy paste, you might get spaces inserted. Would be nice if XCode say some kind of warning or error.

Command CompileSwift failed with a nonzero exit code in Xcode 10

in my case the problem was due to watchkit extension being set to swift 3 while the main project's target was set to swift 4.2

Xcode "Device Locked" When iPhone is unlocked

All the previous solutions didn't work.

Finlay, changing the iPhone's cable solved the problem.

How to remove CocoaPods from a project?

  1. The first thing that you will need to do is remove the Podfile, Podfile.lock, the Pods folder, and the generated workspace.
  2. Next, in the .xcodeproj, remove the references to the Pods.xcconfig files and the libPods.a file.
  3. Within the Build Phases project tab, delete the Check Pods Manifest.lock section (open), Copy Pods Resources section (bottom) and Embed Pod Resources(bottom).
  4. Remove Pods.framework.

The only thing you may want to do is include some of the libraries that you were using before. You can do this by simply draging whatever folders where in the pods folders into your project (I prefer to put them into my Supporting Files folder).

It worked for me.

How to change the background color of a UIButton while it's highlighted?

UPDATE:

Use the UIButtonBackgroundColor Swift library.

OLD:

Use the helpers below to create a 1 px x 1 px image with a grayscale fill color:

UIImage *image = ACUTilingImageGray(248/255.0, 1);

or an RGB fill color:

UIImage *image = ACUTilingImageRGB(253/255.0, 123/255.0, 43/255.0, 1);

Then, use that image to set the button's background image:

[button setBackgroundImage:image forState:UIControlStateNormal];

Helpers

#pragma mark - Helpers

UIImage *ACUTilingImageGray(CGFloat gray, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetGrayFillColor(context, gray, alpha);
    });
}

UIImage *ACUTilingImageRGB(CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)
{
    return ACUTilingImage(alpha, ^(CGContextRef context) {
        CGContextSetRGBFillColor(context, red, green, blue, alpha);
    });
}

UIImage *ACUTilingImage(CGFloat alpha, void (^setFillColor)(CGContextRef context))
{
    CGRect rect = CGRectMake(0, 0, 0.5, 0.5);
    UIGraphicsBeginImageContextWithOptions(rect.size, alpha == 1, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    setFillColor(context);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Note: ACU is the class prefix of my Cocoa Touch Static Library called Acani Utilities, where AC is for Acani, and U is for Utilities.

Make a VStack fill the width of the screen in SwiftUI

enter image description here

Login Page design using SwiftUI

import SwiftUI

struct ContentView: View {

    @State var email: String = "[email protected]"
    @State var password: String = ""
    @State static var labelTitle: String = ""


    var body: some View {
        VStack(alignment: .center){
            //Label
            Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
            //TextField
            TextField("Email", text: $email)
                .textContentType(.emailAddress)
                .foregroundColor(.blue)
                .frame(minHeight: 40)
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            TextField("Password", text: $password) //Placeholder
                .textContentType(.newPassword)
                .frame(minHeight: 40)
                .foregroundColor(.blue) // Text color
                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))

            //Button
            Button(action: {

            }) {
                HStack {
                    Image(uiImage: UIImage(named: "Login")!)
                        .renderingMode(.original)
                        .font(.title)
                        .foregroundColor(.blue)
                    Text("Login")
                        .font(.title)
                        .foregroundColor(.white)
                }


                .font(.headline)
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
                .cornerRadius(40)
                .padding(.horizontal, 20)

                .frame(width: 200, height: 50, alignment: .center)
            }
            Spacer()

        }.padding(10)

            .frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
            .background(Color.gray)

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Try to remove armv7s from project's "Valid architecture" to release from this issue for iOS 5.1 phone

command/usr/bin/codesign failed with exit code 1- code sign error

For me, i just cleaned the app and it worked (cmd + shift + k), removing the error. I got the error after updating to swift 2.3.

iOS 7 - Failing to instantiate default view controller

If you have been committing your code to source control regularly, this may save you the hassle of creating a new Storyboard and possibly introducing more problems...

I was able to solve this by comparing the Git source code of the version that worked against the broken one. The diff showed that the first line should contain the Id of the initial view controller, in my case, initialViewController="Q7U-eo-vxw". I searched through the source code to be sure that the id existed. All I had to do was put it back and everything worked again!

<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="5056" systemVersion="13E28" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="Q7U-eo-vxw">
    <dependencies>
        <deployment defaultVersion="1296" identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3733"/>
    </dependencies>
    <scenes>

Here are some steps that can help you troubleshoot:

  1. Right click the failing Storyboard and use Source Control > Commit... to preserve your changes since the last commit.
  2. Try right clicking your failing Storyboard and use "Open As > Source Code" to view the XML of the storyboard.
  3. In the document element, look for the attribute named "initialViewController". If it is missing, don't worry, we'll fix that. If it is there, double click the id that is assigned to it, command-c to copy it, command-f command-v to search for it deeper in the document. This is the identifier of the controller that should provide the initial view. If it is not defined in the document then that is a problem - you should remove it from the document tag, in my case initialViewController="Q7U-eo-vxw".
  4. Go to Xcode menu item called View and choose Version Editor > Show Comparison View
  5. This shows your local version on the left and the historical version on the right. Click on the date beneath the historical version to get a list of the commits for this story board. Choose one that you know worked and compare the document element. What is the id of the *initialViewController? Is it different? If so, try editing it back in by hand and running. xcode historical compare tool in action

Open a facebook link by native Facebook app on iOS

Here are some schemes the Facebook app uses, there are a ton more on the source link:

Example

NSURL *url = [NSURL URLWithString:@"fb://profile/<id>"];
[[UIApplication sharedApplication] openURL:url];

Schemes

fb://profile – Open Facebook app to the user’s profile

fb://friends – Open Facebook app to the friends list

fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)

fb://feed – Open Facebook app to the News Feed

fb://events – Open Facebook app to the Events page

fb://requests – Open Facebook app to the Requests list

fb://notes – Open Facebook app to the Notes page

fb://albums – Open Facebook app to Photo Albums list

If before opening this url you want to check wether the user fas the facebook app you can do the following (as explained in another answer below):

if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
    [[UIApplication sharedApplication] openURL:nsurl];
}
else {
    //Open the url as usual
}

Source

http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Converting NSString to NSDictionary / JSON

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

For resovle this issue:

  1. Go to Xcode/Preferences/Accounts
  2. Click on your apple id account;
  3. Click - "View Details" (is open a new window with "signing identities" and "provisioning profiles";
  4. Delete all certificates from "Provisioning profiles", empty trash;
  5. Delete your Apple-ID account;
  6. Log in again with your apple id and build app!

Good luck!

Apple Mach-O Linker Error when compiling for device

If you're getting a Mach-O Linker warning or error that says "Directory not found for option", lookup the path of that directory. If it's missing try downloading the latest version of RestKit and putting the folder in manually.

Failed to create provisioning profile

Change bundle identifier, Straight solution

iOS how to set app icon and launch images

You can easily do it without resizing yourself or doing anything, just choose your icon at an app store icon generator website https://getappscreenshots.com/app-icon-generator and it'll generate all required files and all icon sizes so you can just copy the files and paste in your project's folder!

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

The identity used to sign the executable is no longer valid

@vomako 's solution almost solved my problem but I had to take another couple of steps.

I refer to the following...

In Xcode 6.1.1, I went to Preferences --> Accounts --> View Details

After upgrading to Xcode 6.1.1, the main issue for me that the >View Details button was greyed out.

I had to delete my account, restart Xcode, then add my developer account back in.

After this step, I could yet again view details and refresh my provisioning profiles.

libxml/tree.h no such file or directory

You also need to add /usr/include/libxml2 to your include path.

Xcode 9 error: "iPhone has denied the launch request"

The problem is that xcode 'times out' after certain seconds. The fix is to edit the scheme and ask xcode to 'wait' until the executable is launched.

In Edit Scheme, check 'Wait for executable to be launched' instead of 'Automatically'

Xcode warning: "Multiple build commands for output file"

Open the Frameworks folder in your project and make sure there are only frameworks inside. I added by mistake the whole Developer folder!

This action could not be completed. Try Again (-22421)

I was too having this issues, I had uploaded my application and also updated it once but had no issues, but as i was uploading it for the 3rd time, i came across this issue, tried hell lot of things, scratched my head, googled it for hours, kept on trying the whole day, but nothing happened, but next day( a new light came) and my app uploaded on the first attempt.

Feel like there was some issue from apple side(be it there server, there software xCode or there mac).

So don not get dishearten if facing this problem, you can explore diff things with this problem but its just simple thing to correct this issue is to wait for some time take rest and try again.

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

Python in Xcode 4+?

Procedure to get Python Working in XCode 7

Step 1: Setup your Project with a External Build System

enter image description here

Step 1.1: Edit the Project Scheme

enter image description here

Step 2: Specify Python as the executable for the project (shift-command-g) the path should be /usr/bin/python

enter image description here

Step 3: Specify your custom working directory

enter image description here

Step 4: Specify your command line arguments to be the name of your python file. (in this example "test.py")

enter image description here

enter image description here

Step 5: Thankfully thats it!

(debugging can't be added until OSX supports a python debugger?)

How to Completely Uninstall Xcode and Clear All Settings

Before taking such drastic measures, quit Xcode and follow all the instructions here for cleaning out the caches:

How to Empty Caches and Clean All Targets Xcode 4

If that doesn't help, and you decide you really need a clean installation of Xcode, then, in addition to all of the stuff in that answer, trash the Xcode app itself, plus trash your ~/Library/Developer folder and your ~/Library/Preferences/com.apple.dt.Xcode.plist file. I think that should just about do it.

How can I add private key to the distribution certificate?

This site explain step by step that what you need to do Certificates, Identifiers & Profiles and as your question

"Valid Signing identity not found"?

You need the private key that were used to sign the code base with provisioning profile. . If you don't have then you can generate a new signing request on the iOS developer portal.

For Export:

Xcode -> Organizer, select your team. Click Export. Specify a filename and a password, and click Save.`

For Import:

Xcode -> Organizer, select your team. Click Import. Select the file containing your code signing assets. Enter the password for the file, and click Open.

Reason: no suitable image found

In my case, it was an issue with one of the pods I was using. I ended up removing that pod and placing the code from it into my project manually.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

How to update Xcode from command line

What you are actually using is the command to install the Xcode command line tools - xcode-select --install. Hence the error message you got - the tools are already installed.

The command you need to update Xcode is softwareupdate command [args ...]. You can use softwareupdate --list to see what's available and then softwareupdate --install -a to install all updates or softwareupdate --install <product name> to install just the Xcode update (if available). You can get the name from the list command.

As it was mentioned in the comments here is the man page for the softwareupdate tool.

2019 Update

A lot of users are experiencing problems where softwareupdate --install -a will in fact not update to the newest version of Xcode. The cause for this is more than likely a pending macOS update (as @brianlmerritt pointed out below). In most cases updating macOS first will solve the problem and allow Xcode to be updated as well.

Updating the Xcode Command Line Tools

A large portion of users are landing on this answer in an attempt to update the Xcode Command Line Tools. The easiest way to achieve this is by removing the old version of the tools, and installing the new one.

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

A popup will appear and guide you through the rest of the process.

How do I print a list of "Build Settings" in Xcode project?

Apple's "Build Setting Reference" documentation for what's officially documented (or as rjstelling's answer shows, use env in a build script to see what Xcode actually passes you.

In case the above link changes, Google search for: "build setting reference" site:developer.apple.com

Can I have multiple Xcode versions installed?

It seems that Xcode really likes to be in the Applications folder and be called Xcode, especially when using xcodebuild (when building for Carthage for example) - and xcode-select doesn't always seem to cut it.

I have a client project that's still using Swift 2.2, and I'm stuck on Xcode 7 for that and using Xcode 8 for anything else.

So, in my Applications folder, I have Xcode 7 (renamed to Xcode_7) and Xcode 8 (renamed to Xcode_8). Then I rename whichever one I need to simply Xcode, and back again when done. It's a ball-ache, but seems to work.

This shell script simplifies it a bit…

xcode-version.sh

cd /Applications

if  [[ $1 = "-8" ]]
then 
    if [ -e Xcode_8.app ] 
    then            
        mv Xcode.app Xcode_7.app
        mv Xcode_8.app Xcode.app
        echo "Switched to Xcode 8"
    else
        echo "Already using Xcode 8"
    fi
elif  [[ $1 = "-7" ]]
then
    if [ -e Xcode_7.app ] 
    then            
        mv Xcode.app Xcode_8.app
        mv Xcode_7.app Xcode.app
        echo "Switched to Xcode 7"
    else
        echo "Already using Xcode 7"
    fi
else
    echo "usage: xcode-version -7/8"
fi

xcode-select --switch Xcode.app

"Could not find Developer Disk Image"

If you want to develop with Xcode 7 on your iOS10 device :
(Note: you can adapt this command to other Xcode and iOS versions)

  1. Rename your Xcode.app to Xcode7.app and download Xcode 8 from the app store.
  2. Run Xcode 8 once to install it.
  3. Open the terminal and create a symbolic link from Xcode 8 Developer Disk Image 10.0 to Xcode 8 Developer Disk Image folder using this command:

    ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0\ \(14A345\)/ /Applications/Xcode7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
    

Source

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

I faced the same problem when running my app on iPad using xcode 5.1. It got resolved by removing armv7s from 'valid architectures' and setting the 'build active architectures only' value to No. Both these fields can be found in your app->targets->build settings->architectures.

Xcode 5 and iOS 7: Architecture and Valid architectures

Set the architecture in build setting to Standard architectures(armv7,armv7s)

enter image description here

iPhone 5S is powered by A7 64bit processor. From apple docs

Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.

Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.

From the documentation what i understood is

  • Xcode can create both 64bit 32bit binaries for a single app but the deployment target should be iOS7. They are saying in future it will be iOS 6.0
  • 32 bit binary will work fine in iPhone 5S(64 bit processor).

Update (Xcode 5.0.1)
In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.

Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.

Update (Xcode 5.1)
Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you. Check this

Dynamic Height Issue for UITableView Cells (Swift)

Set automatic dimension for row height & estimated row height and ensure following steps:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Set automatic dimensions for row height
    // Swift 4.2 onwards
    table.rowHeight = UITableView.automaticDimension
    table.estimatedRowHeight = UITableView.automaticDimension


    // Swift 4.1 and below
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension

}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Swift 4.2 onwards
    return UITableView.automaticDimension

    // Swift 4.1 and below
    return UITableViewAutomaticDimension
}

For Example: if you have a label in your UITableviewCell then,

  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

Here is sample label with dynamic height constraints.

enter image description here

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

How to update the constant height constraint of a UIView programmatically?

First connect the Height constraint in to our viewcontroller for creating IBOutlet like the below code shown

@IBOutlet weak var select_dateHeight: NSLayoutConstraint!

then put the below code in view did load or inside any actions

self.select_dateHeight.constant = 0 // we can change the height value

if it is inside a button click

@IBAction func Feedback_button(_ sender: Any) {
 self.select_dateHeight.constant = 0

}

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

I had the exact same problem and tried everything. For whatever reason the solution was that all my certificates had migrated to a keychain called "microsoft_intermediate_certificates". As it probably happened during an Xcode upgrade I have absolutely no idea why, but it may help somebody.

I moved all content of the Microsoft keychain to the login keychain and everything went back to normal.

How to use UIScrollView in Storyboard

Here is a simple solution.

  1. Set the size attribute of your view controller in the storyboard to "Freeform" and set the size you want. Make sure it's big enough to fit the full content of your scroll view.

  2. Add your scroll view and set the constraints as you normally would. i.e. if you wants the scroll view to be the size of your view, then attach your top, bottom, leading, trailing margins to the superview as you normally would.

  3. Now just make sure there are constraints in the subviews of the scrollview that connect the top and bottom of the scroll view. Same for left and right if you have horizontal scrolling.

enter image description here

Xcode - ld: library not found for -lPods

I had the same problem

pod install and pod update on command line resolve my problem

How to symbolicate crash log Xcode?

Apple gives you crash log in .txt format , which is unsymbolicated

**

With the device connected

**

  • Download ".txt" file , change extension to ".crash" enter image description here
    • Open devices and simulators from window tab in Xcode
    • select device and select device logs
    • drag and drop .crash file to the device log window

enter image description here

We will be able to see symbolicated crash logs over there

Please see the link for more details on Symbolicating Crash logs

How can I load storyboard programmatically from class?

Swift 3

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "viewController")
self.navigationController!.pushViewController(vc, animated: true)

Swift 2

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController")
self.navigationController!.pushViewController(vc, animated: true)

Prerequisite

Assign a Storyboard ID to your view controller.

Storyboard ID

IB > Show the Identity inspector > Identity > Storyboard ID

Swift (legacy)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewController") as? UIViewController
self.navigationController!.pushViewController(vc!, animated: true)

Edit: Swift 2 suggested in a comment by Fred A.

if you want to use without any navigationController you have to use like following :

    let Storyboard  = UIStoryboard(name: "Main", bundle: nil)
    let vc = Storyboard.instantiateViewController(withIdentifier: "viewController")
    present(vc , animated: true , completion: nil)

How to force a UIViewController to Portrait orientation in iOS 6

The answers using subclasses or categories to allow VCs within UINavigationController and UITabBarController classes work well. Launching a portrait-only modal from a landscape tab bar controller failed. If you need to do this, then use the trick of displaying and hiding a non-animated modal view, but do it in the viewDidAppear method. It didn't work for me in viewDidLoad or viewWillAppear.

Apart from that, the solutions above work fine.

Swift 3 - Comparing Date objects

SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.

func checkTimeStamp(date: String!) -> Bool {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier:"en_US_POSIX")
        let datecomponents = dateFormatter.date(from: date)

        let now = Date()

        if (datecomponents! >= now) {
            return true
        } else {
            return false
        }
    }

To use it:

if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
    // Do something
}

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How to add a border just on the top side of a UIView

The best way for me is a category on UIView, but adding views instead of CALayers, so we can take advantage of AutoresizingMasks to make sure borders resize along with the superview.

Objective C

- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
    [self addSubview:border];
}

- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
    border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
    [self addSubview:border];
}

Swift 5

func addTopBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
    border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addLeftBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.frame = CGRect(x: 0, y: 0, width: borderWidth, height: frame.size.height)
    border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
    addSubview(border)
}

func addRightBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
    border.frame = CGRect(x: frame.size.width - borderWidth, y: 0, width: borderWidth, height: frame.size.height)
    addSubview(border)
}

How do I set up NSZombieEnabled in Xcode 4?

I find this alternative more convenient:

  1. Click the "Run Button Dropdown"
  2. From the list choose Profile
  3. The program "Instruments" should open where you can also choose Zombies
  4. Now you can interact with your app and try to cause the error
  5. As soon as the error happens you should get a hint on when your object was released and therefore deallocated.

Zombies

As soon as a zombie is detected you then get a neat "Zombie Stack" that shows you when the object in question was allocated and where it was retained or released:

Event Type    RefCt     Responsible Caller
Malloc            1     -[MyViewController loadData:]
Retain            2     -[MyDataManager initWithBaseURL:]
Release           1     -[MyDataManager initWithBaseURL:]
Release           0     -[MyViewController loadData:]
Zombie           -1     -[MyService prepareURLReuqest]

Advantages compared to using the diagnostic tab of the Xcode Schemes:

  1. If you forget to uncheck the option in the diagnostic tab there no objects will be released from memory.

  2. You get a more detailed stack that shows you in what methods your corrupt object was allocated / released or retained.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

If you have similar issues in Intellij do as others said above me :

  1. Open Terminal.
  2. Enter this command: sudo xcodebuild --license.
  3. Enter system password.
  4. Go to the end of file: Press space(button) to do that.
  5. Type 'Agree' to the license.

And you are done.!!

How can I indent multiple lines in Xcode?

? + [ and ? + ] are the equivalents to shift+tab in Xcode.

The executable gets signed with invalid entitlements in Xcode

It seems to be a little bug inside Xcode. Try to archive it anyway, even there is a problem with entitlements. If your entitlements are fine, it will be uploaded without any problem. Apple accept it, and your app will be published to the AppStore.

I did it, and it worked:)

What is a provisioning profile used for when developing iPhone applications?

Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:

  • When you need to test/debug an app on a real device the Development Provisioning Profile allows you to do it
  • When you publish an app you send a Distribution Provisioning Profile[About] and Apple after review reassign it by they own key

Development Provisioning Profile is stored on device and contains:

  • Application ID - application which are going to run
  • List of Development certificates - who can debug the app
  • List of devices - which devices can run this app

Xcode by default take cares about

How to create .ipa file using Xcode?

Here is the steps I followed to export the .ipa

  • Validate the archive
  • Click on on distribute the app
  • Click the distribution method
  • Choose the export in the next screen (The screen shown only if the archive is validated)

iOS - Ensure execution on main thread

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

ios simulator: how to close an app

For iOS 7 & above:

  • shift+command+H twice to simulate the double tap of home button
  • swipe your app's screenshot upward to close it

You'll see screenshots representing the apps suspended on your device - those screenshots respond to touch events. Swiping is the gesture you'll make to "fling" the screenshot off of the screen. Note that on machines where your mouse is intended to represent your finger, you'll click and swipe as if it is your finger tapping and making the gesture.

New warnings in iOS 9: "all bitcode will be dropped"

After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:

  1. Update your library with bit code,
  2. Say NO to Enable Bitcode in your target Build Settings

Enter image description here

And the Library Build Settings to remove the warnings.

For more information, go to documentation of bitcode in developer library.

And WWDC 2015 Session 102: "Platforms State of the Union"

Enter image description here

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

How can I find out if I have Xcode commandline tools installed?

First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc if you have not installed it you will get an alert. You can verify that you have installed it by

$ xcode-select -p
/Library/Developer/CommandLineTools

And to be sure then enter $ gcc --version

You can read more about the process here: Xcode command line tools for Mavericks

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

As others have pointed out, if you get this error, you need to check that the Bundle ID value in both your .plist file and also here:

Xcode project Build Settings tab with Product Bundle Identifier focused

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

Codesign error: Provisioning profile cannot be found after deleting expired profile

At least in Xcode 5, this is the thing that solved the problem for me:

Under provisioning profile, select the offending provisioning profile and then select a valid provisioning profile in the pull-down menu.

enter image description here

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

Error "library not found for" after putting application in AdMob

@raurora's answer pointed me in the right direction. I was including libraries in my "watchkitapp Extension/lib" path. In this case, the Library Search Path needed to be escaped with a '\', but the linker didn't seem to understand this. To fix / work-around the issue, I moved my lib path up one level so it was no longer in a directory that contained a space in the name.

An App ID with Identifier '' is not available. Please enter a different string

TARGETS->General->Identity

At first, modify the value of 'Bundle Identifier', so that it is different from the previous value.Then team chose 'None'. Xcode6~Xcode7.3.1

enter image description here

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

The problem is that Xcode Command-line Tools needs to be updated.

Solution #1

Go back to your terminal and enter:

xcode-select --install

You'll then receive the following output:

xcode-select: note: install requested for command line developer tools

You will then be prompted in a window to update Xcode Command Line tools. (which may take a while)

Open a new terminal window and your development tools should be returned.

Addition: With any major or semi-major update you'll need to update the command line tools in order to get them functioning properly again. Check Xcode with any update. This goes beyond Mojave...

After that restart your terminal

Alternatively, IF that fails, and it very well might.... you'll get a pop-up box saying "Software not found on server", see below!

Solution #2

and you hit xcode-select --install and it doesn't find the software, log into Apple Developer, and install it via webpage.

Login or sign up here:

https://developer.apple.com/download/more/

Look for: "Command Line Tools for Xcode 12.x" in the list of downloads Then click the dmg and download.

image of apple developer page and dmg for DL

Undefined symbols for architecture arm64

Setting -ObjC to Other Linker Flags in Build Settings of the target solved the problem.

Creating a UITableView Programmatically

Creating a tableview using tableViewController .

import UIKit

class TableViewController: UITableViewController
{
    let tableViewModel = TableViewModel()
    var product: [String] = []
    var price: [String] = []
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
        let priceProductDetails = tableViewModel.dataProvider()

        for (key, value) in priceProductDetails
        {
            product.append(key)
            price.append(value)
        }
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
        cell.textLabel?.text = product[indexPath.row]
        cell.detailTextLabel?.text = price[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }
}

iPhone/iPad browser simulator?

There's no good substitute to testing on an actual device.

Real devices have higher display densities, meaning that pixels are smaller. If you don't test on a real device, you may not realise that your design includes text that is too small to read or buttons that are too small to tap.

You use real devices with your fingers, not a mouse. This means that the accuracy of your taps is much lower and what you are tapping is obscured by your finger. If you don't test on a real device, you may not realise you've introduced usability problems into your design.

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

Check for internet connection with Swift

Use this for Swift-5+

import Foundation
import UIKit
import SystemConfiguration

public class InternetConnectionManager {
    
    
    private init() {
        
    }
    
    public static func isConnectedToNetwork() -> Bool {
        
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                
                SCNetworkReachabilityCreateWithAddress(nil, $0)
                
            }
            
        }) else {
            
            return false
        }
        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
    
}

Usage:

if InternetConnectionManager.isConnectedToNetwork(){
    print("Connected")
}else{
    print("Not Connected")
}

Or Just use this framework for more Utilities: Link

Execute action when back bar button of UINavigationController is pressed

You can subclass UINavigationController and override popViewController(animated: Bool). Beside being able to execute some code there you can also prevent the user from going back altogether, for instance to prompt to save or discard his current work.

Sample implementation where you can set a popHandler that gets set/cleared by pushed controllers.

class NavigationController: UINavigationController
{
    var popHandler: (() -> Bool)?

    override func popViewController(animated: Bool) -> UIViewController?
    {
        guard self.popHandler?() != false else
        {
            return nil
        }
        self.popHandler = nil
        return super.popViewController(animated: animated)
    }
}

And sample usage from a pushed controller that tracks unsaved work.

let hasUnsavedWork: Bool = // ...
(self.navigationController as! NavigationController).popHandler = hasUnsavedWork ?
    {
        // Prompt saving work here with an alert

        return false // Prevent pop until as user choses to save or discard

    } : nil // No unsaved work, we clear popHandler to let it pop normally

As a nice touch, this will also get called by interactivePopGestureRecognizer when the user tries to go back using a swipe gesture.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

Try to run xcrun simctl delete unavailable in your terminal.

Original answer: Xcode - free to clear devices folder?

Version vs build in Xcode

Apple sort of rearranged/repurposed the fields.

Going forward, if you look on the Info tab for your Application Target, you should use the "Bundle versions string, short" as your Version (e.g., 3.4.0) and "Bundle version" as your Build (e.g., 500 or 1A500). If you don't see them both, you can add them. Those will map to the proper Version and Build textboxes on the Summary tab; they are the same values.

When viewing the Info tab, if you right-click and select Show Raw Keys/Values, you'll see the actual names are CFBundleShortVersionString (Version) and CFBundleVersion (Build).

The Version is usually used how you appear to have been using it with Xcode 3. I'm not sure on what level you're asking about the Version/Build difference, so I'll answer it philosophically.

There are all sorts of schemes, but a popular one is:

{MajorVersion}.{MinorVersion}.{Revision}

  • Major version - Major changes, redesigns, and functionality changes
  • Minor version - Minor improvements, additions to functionality
  • Revision - A patch number for bug-fixes

Then the Build is used separately to indicate the total number of builds for a release or for the entire product lifetime.

Many developers start the Build number at 0, and every time they build they increase the number by one, increasing forever. In my projects, I have a script that automatically increases the build number every time I build. See instructions for that below.

  • Release 1.0.0 might be build 542. It took 542 builds to get to a 1.0.0 release.
  • Release 1.0.1 might be build 578.
  • Release 1.1.0 might be build 694.
  • Release 2.0.0 might be build 949.

Other developers, including Apple, have a Build number comprised of a major version + minor version + number of builds for the release. These are the actual software version numbers, as opposed to the values used for marketing.

If you go to Xcode menu > About Xcode, you'll see the Version and Build numbers. If you hit the More Info... button you'll see a bunch of different versions. Since the More Info... button was removed in Xcode 5, this information is also available from the Software > Developer section of the System Information app, available by opening Apple menu > About This Mac > System Report....

For example, Xcode 4.2 (4C139). Marketing version 4.2 is Build major version 4, Build minor version C, and Build number 139. The next release (presumably 4.3) will likely be Build release 4D, and the Build number will start over at 0 and increment from there.

The iPhone Simulator Version/Build numbers are the same way, as are iPhones, Macs, etc.

  • 3.2: (7W367a)
  • 4.0: (8A400)
  • 4.1: (8B117)
  • 4.2: (8C134)
  • 4.3: (8H7)

Update: By request, here are the steps to create a script that runs each time you build your app in Xcode to read the Build number, increment it, and write it back to the app's {App}-Info.plist file. There are optional, additional steps if you want to write your version/build numbers to your Settings.bundle/Root*.plist file(s).

This is extended from the how-to article here.

In Xcode 4.2 - 5.0:

  1. Load your Xcode project.
  2. In the left hand pane, click on your project at the very top of the hierarchy. This will load the project settings editor.
  3. On the left-hand side of the center window pane, click on your app under the TARGETS heading. You will need to configure this setup for each project target.
  4. Select the Build Phases tab.
    • In Xcode 4, at the bottom right, click the Add Build Phase button and select Add Run Script.
    • In Xcode 5, select Editor menu > Add Build Phase > Add Run Script Build Phase.
  5. Drag-and-drop the new Run Script phase to move it to just before the Copy Bundle Resources phase (when the app-info.plist file will be bundled with your app).
  6. In the new Run Script phase, set Shell: /bin/bash.
  7. Copy and paste the following into the script area for integer build numbers:

    buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
    buildNumber=$(($buildNumber + 1))
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
    

    As @Bdebeez pointed out, the Apple Generic Versioning Tool (agvtool) is also available. If you prefer to use it instead, then there are a couple things to change first:

    • Select the Build Settings tab.
    • Under the Versioning section, set the Current Project Version to the initial build number you want to use, e.g., 1.
    • Back on the Build Phases tab, drag-and-drop your Run Script phase after the Copy Bundle Resources phase to avoid a race condition when trying to both build and update the source file that includes your build number.

    Note that with the agvtool method you may still periodically get failed/canceled builds with no errors. For this reason, I don't recommend using agvtool with this script.

    Nevertheless, in your Run Script phase, you can use the following script:

    "${DEVELOPER_BIN_DIR}/agvtool" next-version -all
    

    The next-version argument increments the build number (bump is also an alias for the same thing), and -all updates Info.plist with the new build number.

  8. And if you have a Settings bundle where you show the Version and Build, you can add the following to the end of the script to update the version and build. Note: Change the PreferenceSpecifiers values to match your settings. PreferenceSpecifiers:2 means look at the item at index 2 under the PreferenceSpecifiers array in your plist file, so for a 0-based index, that's the 3rd preference setting in the array.

    productVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$INFOPLIST_FILE")
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
    

    If you're using agvtool instead of reading the Info.plist directly, you can add the following to your script instead:

    buildNumber=$("${DEVELOPER_BIN_DIR}/agvtool" what-version -terse)
    productVersion=$("${DEVELOPER_BIN_DIR}/agvtool" what-marketing-version -terse1)
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root.plist
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root.plist
    
  9. And if you have a universal app for iPad & iPhone, then you can also set the settings for the iPhone file:

    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:2:DefaultValue $buildNumber" Settings.bundle/Root~iphone.plist    
    /usr/libexec/PlistBuddy -c "Set PreferenceSpecifiers:1:DefaultValue $productVersion" Settings.bundle/Root~iphone.plist
    

Using NSLog for debugging

Try this piece of code:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);

The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I met it when import a ViewController.m in TableViewController. Try to delete '#import "ViewController.m"' if it exited. Hope this help!

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

If you are not using https in api calls, Please add this key "App Uses Non-Exempt Encryption" in your info.plist and set it to "NO"

Distribution certificate / private key not installed

EDIT: I thought that the other computer is dead so I'm fixing my answer:

You should export the certificate from the first computer with it's private key and import it in the new computer.

I prefer the iCloud way, backup to iCloud and get it in the new computer.

If you can't do it with some reason, you can revoke the certificate in Apple developers site, then let Xcode to create a new one for you, it'll also create a fresh new private key and store it in your Keychain, just be sure to back it up in your preferred way

Build fat static library (device + simulator) using Xcode and SDK 4+

ALTERNATIVES:

Easy copy/paste of latest version (but install instructions may change - see below!)

Karl's library takes much more effort to setup, but much nicer long-term solution (it converts your library into a Framework).

Use this, then tweak it to add support for Archive builds - c.f. @Frederik's comment below on the changes he's using to make this work nicely with Archive mode.


RECENT CHANGES: 1. Added support for iOS 10.x (while maintaining support for older platforms)

  1. Info on how to use this script with a project-embedded-in-another-project (although I highly recommend NOT doing that, ever - Apple has a couple of show-stopper bugs in Xcode if you embed projects inside each other, from Xcode 3.x through to Xcode 4.6.x)

  2. Bonus script to let you auto-include Bundles (i.e. include PNG files, PLIST files etc from your library!) - see below (scroll to bottom)

  3. now supports iPhone5 (using Apple's workaround to the bugs in lipo). NOTE: the install instructions have changed (I can probably simplify this by changing the script in future, but don't want to risk it now)

  4. "copy headers" section now respects the build setting for the location of the public headers (courtesy of Frederik Wallner)

  5. Added explicit setting of SYMROOT (maybe need OBJROOT to be set too?), thanks to Doug Dickinson


SCRIPT (this is what you have to copy/paste)

For usage / install instructions, see below

##########################################
#
# c.f. https://stackoverflow.com/questions/3520977/build-fat-static-library-device-simulator-using-xcode-and-sdk-4
#
# Version 2.82
#
# Latest Change:
# - MORE tweaks to get the iOS 10+ and 9- working
# - Support iOS 10+
# - Corrected typo for iOS 1-10+ (thanks @stuikomma)
# 
# Purpose:
#   Automatically create a Universal static library for iPhone + iPad + iPhone Simulator from within XCode
#
# Author: Adam Martin - http://twitter.com/redglassesapps
# Based on: original script from Eonil (main changes: Eonil's script WILL NOT WORK in Xcode GUI - it WILL CRASH YOUR COMPUTER)
#

set -e
set -o pipefail

#################[ Tests: helps workaround any future bugs in Xcode ]########
#
DEBUG_THIS_SCRIPT="false"

if [ $DEBUG_THIS_SCRIPT = "true" ]
then
echo "########### TESTS #############"
echo "Use the following variables when debugging this script; note that they may change on recursions"
echo "BUILD_DIR = $BUILD_DIR"
echo "BUILD_ROOT = $BUILD_ROOT"
echo "CONFIGURATION_BUILD_DIR = $CONFIGURATION_BUILD_DIR"
echo "BUILT_PRODUCTS_DIR = $BUILT_PRODUCTS_DIR"
echo "CONFIGURATION_TEMP_DIR = $CONFIGURATION_TEMP_DIR"
echo "TARGET_BUILD_DIR = $TARGET_BUILD_DIR"
fi

#####################[ part 1 ]##################
# First, work out the BASESDK version number (NB: Apple ought to report this, but they hide it)
#    (incidental: searching for substrings in sh is a nightmare! Sob)

SDK_VERSION=$(echo ${SDK_NAME} | grep -o '\d\{1,2\}\.\d\{1,2\}$')

# Next, work out if we're in SIM or DEVICE

if [ ${PLATFORM_NAME} = "iphonesimulator" ]
then
OTHER_SDK_TO_BUILD=iphoneos${SDK_VERSION}
else
OTHER_SDK_TO_BUILD=iphonesimulator${SDK_VERSION}
fi

echo "XCode has selected SDK: ${PLATFORM_NAME} with version: ${SDK_VERSION} (although back-targetting: ${IPHONEOS_DEPLOYMENT_TARGET})"
echo "...therefore, OTHER_SDK_TO_BUILD = ${OTHER_SDK_TO_BUILD}"
#
#####################[ end of part 1 ]##################

#####################[ part 2 ]##################
#
# IF this is the original invocation, invoke WHATEVER other builds are required
#
# Xcode is already building ONE target...
#
# ...but this is a LIBRARY, so Apple is wrong to set it to build just one.
# ...we need to build ALL targets
# ...we MUST NOT re-build the target that is ALREADY being built: Xcode WILL CRASH YOUR COMPUTER if you try this (infinite recursion!)
#
#
# So: build ONLY the missing platforms/configurations.

if [ "true" == ${ALREADYINVOKED:-false} ]
then
echo "RECURSION: I am NOT the root invocation, so I'm NOT going to recurse"
else
# CRITICAL:
# Prevent infinite recursion (Xcode sucks)
export ALREADYINVOKED="true"

echo "RECURSION: I am the root ... recursing all missing build targets NOW..."
echo "RECURSION: ...about to invoke: xcodebuild -configuration \"${CONFIGURATION}\" -project \"${PROJECT_NAME}.xcodeproj\" -target \"${TARGET_NAME}\" -sdk \"${OTHER_SDK_TO_BUILD}\" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO" BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" SYMROOT=\"${SYMROOT}\"

xcodebuild -configuration "${CONFIGURATION}" -project "${PROJECT_NAME}.xcodeproj" -target "${TARGET_NAME}" -sdk "${OTHER_SDK_TO_BUILD}" ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}" SYMROOT="${SYMROOT}"

ACTION="build"

#Merge all platform binaries as a fat binary for each configurations.

# Calculate where the (multiple) built files are coming from:
CURRENTCONFIG_DEVICE_DIR=${SYMROOT}/${CONFIGURATION}-iphoneos
CURRENTCONFIG_SIMULATOR_DIR=${SYMROOT}/${CONFIGURATION}-iphonesimulator

echo "Taking device build from: ${CURRENTCONFIG_DEVICE_DIR}"
echo "Taking simulator build from: ${CURRENTCONFIG_SIMULATOR_DIR}"

CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
echo "...I will output a universal build to: ${CREATING_UNIVERSAL_DIR}"

# ... remove the products of previous runs of this script
#      NB: this directory is ONLY created by this script - it should be safe to delete!

rm -rf "${CREATING_UNIVERSAL_DIR}"
mkdir "${CREATING_UNIVERSAL_DIR}"

#
echo "lipo: for current configuration (${CONFIGURATION}) creating output file: ${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}"
xcrun -sdk iphoneos lipo -create -output "${CREATING_UNIVERSAL_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_DEVICE_DIR}/${EXECUTABLE_NAME}" "${CURRENTCONFIG_SIMULATOR_DIR}/${EXECUTABLE_NAME}"

#########
#
# Added: StackOverflow suggestion to also copy "include" files
#    (untested, but should work OK)
#
echo "Fetching headers from ${PUBLIC_HEADERS_FOLDER_PATH}"
echo "  (if you embed your library project in another project, you will need to add"
echo "   a "User Search Headers" build setting of: (NB INCLUDE THE DOUBLE QUOTES BELOW!)"
echo '        "$(TARGET_BUILD_DIR)/usr/local/include/"'
if [ -d "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}" ]
then
mkdir -p "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
# * needs to be outside the double quotes?
cp -r "${CURRENTCONFIG_DEVICE_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"* "${CREATING_UNIVERSAL_DIR}${PUBLIC_HEADERS_FOLDER_PATH}"
fi
fi

INSTALL INSTRUCTIONS

  1. Create a static lib project
  2. Select the Target
  3. In "Build Settings" tab, set "Build Active Architecture Only" to "NO" (for all items)
  4. In "Build Phases" tab, select "Add ... New Build Phase ... New Run Script Build Phase"
  5. Copy/paste the script (above) into the box

...BONUS OPTIONAL usage:

  1. OPTIONAL: if you have headers in your library, add them to the "Copy Headers" phase
  2. OPTIONAL: ...and drag/drop them from the "Project" section to the "Public" section
  3. OPTIONAL: ...and they will AUTOMATICALLY be exported every time you build the app, into a sub-directory of the "debug-universal" directory (they will be in usr/local/include)
  4. OPTIONAL: NOTE: if you also try to drag/drop your project into another Xcode project, this exposes a bug in Xcode 4, where it cannot create an .IPA file if you have Public Headers in your drag/dropped project. The workaround: dont' embed xcode projects (too many bugs in Apple's code!)

If you can't find the output file, here's a workaround:

  1. Add the following code to the very end of the script (courtesy of Frederik Wallner): open "${CREATING_UNIVERSAL_DIR}"

  2. Apple deletes all output after 200 lines. Select your Target, and in the Run Script Phase, you MUST untick: "Show environment variables in build log"

  3. if you're using a custom "build output" directory for XCode4, then XCode puts all your "unexpected" files in the wrong place.

    1. Build the project
    2. Click on the last icon on the right, in the top left area of Xcode4.
    3. Select the top item (this is your "most recent build". Apple should auto-select it, but they didn't think of that)
    4. in the main window, scroll to bottom. The very last line should read: lipo: for current configuration (Debug) creating output file: /Users/blah/Library/Developer/Xcode/DerivedData/AppName-ashwnbutvodmoleijzlncudsekyf/Build/Products/Debug-universal/libTargetName.a

    ...that is the location of your Universal Build.


How to include "non sourcecode" files in your project (PNG, PLIST, XML, etc)

  1. Do everything above, check it works
  2. Create a new Run Script phase that comes AFTER THE FIRST ONE (copy/paste the code below)
  3. Create a new Target in Xcode, of type "bundle"
  4. In your MAIN PROJECT, in "Build Phases", add the new bundle as something it "depends on" (top section, hit the plus button, scroll to bottom, find the ".bundle" file in your Products)
  5. In your NEW BUNDLE TARGET, in "Build Phases", add a "Copy Bundle Resources" section, and drag/drop all the PNG files etc into it

Script to auto-copy the built bundle(s) into same folder as your FAT static library:

echo "RunScript2:"
echo "Autocopying any bundles into the 'universal' output folder created by RunScript1"
CREATING_UNIVERSAL_DIR=${SYMROOT}/${CONFIGURATION}-universal
cp -r "${BUILT_PRODUCTS_DIR}/"*.bundle "${CREATING_UNIVERSAL_DIR}"

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

Select Pandas rows based on list index

ind_list = [1, 3]
df.ix[ind_list]

should do the trick! When I index with data frames I always use the .ix() method. Its so much easier and more flexible...

UPDATE This is no longer the accepted method for indexing. The ix method is deprecated. Use .iloc for integer based indexing and .loc for label based indexing.

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Because linux is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.

There are a lot of such predefined macros. With GCC, you can use:

cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c

to get a list of macros. (I've not managed to persuade GCC to accept /dev/null directly, but the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:

#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong 
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak 
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__ 
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3

That's 236 macros from an empty file. When I added #include <stdio.h> to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.

How do I get Month and Date of JavaScript in 2 digit format?

$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

    var someFormattedDate = year+'-'+month+'-'+day;

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});

Android Color Picker

I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.

This is the project: Android Color Picker

Android Color Picker dialog

enter image description here

HOW TO USE IT

Adding the library to your project

The aar artifact is available at the jcenter repository. Declare the repository and the dependency in your build.gradle.

(root)

repositories {
    jcenter()
}

(module)

dependencies {
    compile 'com.pes.materialcolorpicker:library:1.0.2'
}

Use the library

Create a color picker dialog object

final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);

defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument

Then show the dialog (when & where you want) and save the selected color

/* Show color picker dialog */
cp.show();

/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);

okColor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            
        /* You can get single channel (value 0-255) */
        selectedColorR = cp.getRed();
        selectedColorG = cp.getGreen();
        selectedColorB = cp.getBlue();
            
        /* Or the android RGB Color (see the android Color class reference) */
        selectedColorRGB = cp.getColor();

        cp.dismiss();
    }
});

That's all :)

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Converting AM/PM Time string to 24 Hours Format. Example 9:30 PM to 21:30

function get24HrsFrmAMPM(timeStr) {
    if (timeStr && timeStr.indexOf(' ') !== -1 && timeStr.indexOf(':') !== -1) {
        var hrs = 0;
        var tempAry = timeStr.split(' ');
        var hrsMinAry = tempAry[0].split(':');
        hrs = parseInt(hrsMinAry[0], 10);
        if ((tempAry[1] == 'AM' || tempAry[1] == 'am') && hrs == 12) {
            hrs = 0;
        } else if ((tempAry[1] == 'PM' || tempAry[1] == 'pm') && hrs != 12) {
            hrs += 12;
        }
        return ('0' + hrs).slice(-2) + ':' + ('0' + parseInt(hrsMinAry[1], 10)).slice(-2);
    } else {
        return null;
    }
}

Retrieve the position (X,Y) of an HTML element relative to the browser window

I did it like this so it was cross-compatible with old browsers.

// For really old browser's or incompatible ones
    function getOffsetSum(elem) {
        var top = 0,
            left = 0,
            bottom = 0,
            right = 0

         var width = elem.offsetWidth;
         var height = elem.offsetHeight;

        while (elem) {
            top += elem.offsetTop;
            left += elem.offsetLeft;
            elem = elem.offsetParent;
        }

         right = left + width;
         bottom = top + height;

        return {
            top: top,
            left: left,
            bottom: bottom,
            right: right,
        }
    }

    function getOffsetRect(elem) {
        var box = elem.getBoundingClientRect();

        var body = document.body;
        var docElem = document.documentElement;

        var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
        var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;

        var clientTop = docElem.clientTop;
        var clientLeft = docElem.clientLeft;


        var top = box.top + scrollTop - clientTop;
        var left = box.left + scrollLeft - clientLeft;
        var bottom = top + (box.bottom - box.top);
        var right = left + (box.right - box.left);

        return {
            top: Math.round(top),
            left: Math.round(left),
            bottom: Math.round(bottom),
            right: Math.round(right),
        }
    }

    function getOffset(elem) {
        if (elem) {
            if (elem.getBoundingClientRect) {
                return getOffsetRect(elem);
            } else { // old browser
                return getOffsetSum(elem);
            }
        } else
            return null;
    }

More about coordinates in JavaScript here: http://javascript.info/tutorial/coordinates

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

How do I add an image to a JButton

public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

try like this. hope it works

drawable-sw720dp-xxhdpi and values-sw720dp-xxhdpi

drawable-sw720dp-xxxhdpi and values-sw720dp-xxxhdpi

link might destroy so pasted ans

reference Android xxx-hdpi real devices

xxxhdpi was only introduced because of the way that launcher icons are scaled on the nexus 5's launcher Because the nexus 5's default launcher uses bigger icons, xxxhdpi was introduced so that icons would still look good on the nexus 5's launcher.

also check these links

Different resolution support android

Application Skeleton to support multiple screen

Is there a list of screen resolutions for all Android based phones and tablets?

$on and $broadcast in angular

First, a short description of $on(), $broadcast() and $emit():

  • .$on(name, listener) - Listens for a specific event by a given name
  • .$broadcast(name, args) - Broadcast an event down through the $scope of all children
  • .$emit(name, args) - Emit an event up the $scope hierarchy to all parents, including the $rootScope

Based on the following HTML (see full example here):

<div ng-controller="Controller1">
    <button ng-click="broadcast()">Broadcast 1</button>
    <button ng-click="emit()">Emit 1</button>
</div>

<div ng-controller="Controller2">
    <button ng-click="broadcast()">Broadcast 2</button>
    <button ng-click="emit()">Emit 2</button>
    <div ng-controller="Controller3">
        <button ng-click="broadcast()">Broadcast 3</button>
        <button ng-click="emit()">Emit 3</button>
        <br>
        <button ng-click="broadcastRoot()">Broadcast Root</button>
        <button ng-click="emitRoot()">Emit Root</button>
    </div>
</div>

The fired events will traverse the $scopes as follows:

  • Broadcast 1 - Will only be seen by Controller 1 $scope
  • Emit 1 - Will be seen by Controller 1 $scope then $rootScope
  • Broadcast 2 - Will be seen by Controller 2 $scope then Controller 3 $scope
  • Emit 2 - Will be seen by Controller 2 $scope then $rootScope
  • Broadcast 3 - Will only be seen by Controller 3 $scope
  • Emit 3 - Will be seen by Controller 3 $scope, Controller 2 $scope then $rootScope
  • Broadcast Root - Will be seen by $rootScope and $scope of all the Controllers (1, 2 then 3)
  • Emit Root - Will only be seen by $rootScope

JavaScript to trigger events (again, you can see a working example here):

app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
    $scope.broadcastAndEmit = function(){
        // This will be seen by Controller 1 $scope and all children $scopes 
        $scope.$broadcast('eventX', {data: '$scope.broadcast'});

        // Because this event is fired as an emit (goes up) on the $rootScope,
        // only the $rootScope will see it
        $rootScope.$emit('eventX', {data: '$rootScope.emit'});
    };
    $scope.emit = function(){
        // Controller 1 $scope, and all parent $scopes (including $rootScope) 
        // will see this event
        $scope.$emit('eventX', {data: '$scope.emit'});
    };

    $scope.$on('eventX', function(ev, args){
        console.log('eventX found on Controller1 $scope');
    });
    $rootScope.$on('eventX', function(ev, args){
        console.log('eventX found on $rootScope');
    });
}]);

Relational Database Design Patterns?

There's a book in Martin Fowler's Signature Series called Refactoring Databases. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.

I would also highly recommend David C. Hay's Data Model Patterns and the follow up A Metadata Map which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.

Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series Volume 1 contains universally applicable data models (employees, accounts, shipping, purchases, etc), Volume 2 contains industry specific data models (accounting, healthcare, etc), Volume 3 provides data model patterns.

Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's Modeling in Color With UML provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

How to hide collapsible Bootstrap 4 navbar on click

With trying out above solutions, I was missing a solution for Dropdown toggles, so here you go! Also opens submenu items.

Maybe you have to tweak it a bit if your toggle class is different.

$('.navbar-nav li a').on('click', function(){
    if(!$( this ).hasClass('dropdown-toggle')){
        $('.navbar-collapse').collapse('hide');
    }
});

Bootstrap 4 Center Vertical and Horizontal Alignment

been going thru a lot of posts on getting a form centered in the page and none of them worked. code below is from a react component using bootstrap 4.1. height should be 100vh and not 100%

<div className="container">
      <div className="d-flex justify-content-center align-items-center" style={height}>
        <form>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Email" type="email"/>
          </div>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Password" type="password"/>
          </div>
          <div className="form-group">
            <button className="btn btn-info btn-lg btn-block">Sign In</button>
          </div>
        </form>
      </div>
    </div>

where height in style is:

const height = { height: '100vh' }

How do I fetch only one branch of a remote Git repository?

One way is the following:

git fetch <remotename> <remote branch>:refs/remotes/<remotename>/<local branch>

This does not set up tracking though.

For more information, see the documentation of git fetch.

EDIT: As @user1338062 notes below: if you don't already have a local clone of the repository where you want to add the new branch, but you want to create a fresh local repository, then the git clone --branch <branch_name> --single-branch <repo_url> provides a shorter solution.

Send Email to multiple Recipients with MailMessage?

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);

Resource interpreted as Document but transferred with MIME type application/zip

This issue was re-appeared at Chrome 61 version. But it seems it is fixed at Chrome 62.

I have a RewriteRule like below

RewriteRule ^/ShowGuide/?$ https://<website>/help.pdf [L,NC,R,QSA]

With Chrome 61, the PDF was not opening, in console it was showing the message

"Resource interpreted as Document but transferred with MIME type application/pdf: "

We tried to add mime type in the rewrite rule as below but it didn't help.

RewriteRule ^/ShowGuide/?$ https://<website>/help.pdf [L,NC,R,QSA, t:application/pdf]

I have updated my Chrome to latest 62 version and it started to showing the PDF again. But the message is still there in the console.

With all other browsers, it was/is working fine.

Looping through dictionary object

It depends on what you are after in the Dictionary

Models.TestModels obj = new Models.TestModels();

foreach (var keyValuPair in obj.sp)
{
    // KeyValuePair<int, dynamic>
}

foreach (var key in obj.sp.Keys)
{
     // Int 
}

foreach (var value in obj.sp.Values)
{
    // dynamic
}

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

How to view the stored procedure code in SQL Server Management Studio

exec sp_helptext 'your_sp_name' -- don't forget the quotes

In management studio by default results come in grid view. If you would like to see it in text view go to:

Query --> Results to --> Results to Text

or CTRL + T and then Execute.

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

Broadcast receiver for checking internet connection in android app

Use this method to check the network state:

private void checkInternetConnection() {

    if (br == null) {

        br = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle extras = intent.getExtras();

                NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                State state = info.getState();
                Log.d("TEST Internet", info.toString() + " "
                        + state.toString());

                if (state == State.CONNECTED) {
                      Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();

                } else {
                       Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                }

            }
        };

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver((BroadcastReceiver) br, intentFilter);
    }
}

remember to unregister service in onDestroy.

Cheers!!

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

Copy Paste Values only( xlPasteValues )

If you are wanting to just copy the whole column, you can simplify the code a lot by doing something like this:

Sub CopyCol()

    Sheets("Sheet1").Columns(1).Copy

    Sheets("Sheet2").Columns(2).PasteSpecial xlPasteValues

End Sub

Or

Sub CopyCol()

    Sheets("Sheet1").Columns("A").Copy

    Sheets("Sheet2").Columns("B").PasteSpecial xlPasteValues

End Sub

Or if you want to keep the loop

Public Sub CopyrangeA()

    Dim firstrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    firstrowDB = 1
    arr1 = Array("BJ", "BK")
    arr2 = Array("A", "B")

    For i = LBound(arr1) To UBound(arr1)

        Sheets("Sheet1").Columns(arr1(i)).Copy

        Sheets("Sheet2").Columns(arr2(i)).PasteSpecial xlPasteValues

    Next
    Application.CutCopyMode = False

End Sub

PHP server on local machine?

AppServ is a small program in Windows to run:

  • Apache
  • PHP
  • MySQL
  • phpMyAdmin

It will also give you a startup and stop button for Apache. Which I find very useful.

Hibernate: best practice to pull all lazy collections

Not the best solution, but here is what I got:

1) Annotate getter you want to initialize with this annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {

}

2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:

    public <T> void forceLoadLazyCollections(T entity) {

    Session session = getSession().openSession();
    Transaction tx = null;
    try {

        tx = session.beginTransaction();
        session.refresh(entity);
        if (entity == null) {
            throw new RuntimeException("Entity is null!");
        }
        for (Method m : entityClass.getMethods()) {

            Lazy annotation = m.getAnnotation(Lazy.class);
            if (annotation != null) {
                m.setAccessible(true);
                logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
                try {
                    Hibernate.initialize(m.invoke(entity));
                }
                catch (Exception e) {
                    logger.warn("initialization exception", e);
                }
            }
        }

    }
    finally {
        session.close();
    }
}

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

Shortcuts in Objective-C to concatenate NSStrings

If you have 2 NSString literals, you can also just do this:

NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";

That's also useful for joining #defines:

#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB

Enjoy.

How can I generate an HTML report for Junit results?

I found the above answers quite useful but not really general purpose, they all need some other major build system like Ant or Maven.

I wanted to generate a report in a simple one-shot command that I could call from anything (from a build, test or just myself) so I have created junit2html which can be found here: https://github.com/inorton/junit2html

You can install it by doing:

pip install junit2html

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Replace

new Timestamp();

with

new java.util.Date()

because there is no default constructor for Timestamp, or you can do it with the method:

new Timestamp(System.currentTimeMillis());

MySQL's now() +1 day

better use quoted `data` and `date`. AFAIR these may be reserved words my version is:

INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The Html.TextboxFor always creates a textbox (<input type="text" ...).

While the EditorFor looks at the type and meta information, and can render another control or a template you supply.

For example for DateTime properties you can create a template that uses the jQuery DatePicker.

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Remove special symbols and extra spaces and replace with underscore using the replace method

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

_x000D_
_x000D_
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
 * Replaces all accented chars with regular ones_x000D_
 */_x000D_
function replaceAccents(str) {_x000D_
  // Verifies if the String has accents and replace them_x000D_
  if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
    str = str_x000D_
      .replace(/[\xC0-\xC5]/g, "A")_x000D_
      .replace(/[\xC6]/g, "AE")_x000D_
      .replace(/[\xC7]/g, "C")_x000D_
      .replace(/[\xC8-\xCB]/g, "E")_x000D_
      .replace(/[\xCC-\xCF]/g, "I")_x000D_
      .replace(/[\xD0]/g, "D")_x000D_
      .replace(/[\xD1]/g, "N")_x000D_
      .replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
      .replace(/[\xD9-\xDC]/g, "U")_x000D_
      .replace(/[\xDD]/g, "Y")_x000D_
      .replace(/[\xDE]/g, "P")_x000D_
      .replace(/[\xE0-\xE5]/g, "a")_x000D_
      .replace(/[\xE6]/g, "ae")_x000D_
      .replace(/[\xE7]/g, "c")_x000D_
      .replace(/[\xE8-\xEB]/g, "e")_x000D_
      .replace(/[\xEC-\xEF]/g, "i")_x000D_
      .replace(/[\xF1]/g, "n")_x000D_
      .replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
      .replace(/[\xF9-\xFC]/g, "u")_x000D_
      .replace(/[\xFE]/g, "p")_x000D_
      .replace(/[\xFD\xFF]/g, "y");_x000D_
  }_x000D_
_x000D_
  return str;_x000D_
}
_x000D_
_x000D_
_x000D_

Source: https://gist.github.com/jonlabelle/5375315

Fragment pressing back button

Solution for Pressing or handling back button in Fragment.

The way I solved my issue I am sure it will helps you too:

1.If you don't have any Edit Text-box in your fragment you can use below code

Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)

    @Override
    public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;    
            }    
            return false;
        }
    }); }

2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.

private EditText editText;

Then In,

onCreateView():    
editText = (EditText) view.findViewById(R.id.editText);

Then Override OnResume,

@Override
public void onResume() {
    super.onResume();

    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                editTextOFS.clearFocus();
                getView().requestFocus();
            }
            return false;
        }
    });

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;

            }

            return false;
        }
    });

}

That's all folks (amitamie.com) :-) ;-)

How can I delete derived data in Xcode 8?

(Working in Xcode 11 and 12)

You can go to File > Workspace Settings if you are in a workspace environment or File > Project Settings for a regular project environment.

Then click over the little grey arrow under Derived data section and select your project folder to delete it.

How can I add "href" attribute to a link dynamically using JavaScript?

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

<a href="somelink">Link</a>

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

BeanFactory vs ApplicationContext

In summary:

The ApplicationContext includes all functionality of the BeanFactory. It is generally recommended to use the former.

There are some limited situations such as in a Mobile application, where memory consumption might be critical.

In that scenarios, It can be justifiable to use the more lightweight BeanFactory. However, in the most enterprise applications, the ApplicationContext is what you will want to use.

For more, see my blog post:

Difference between BeanFactory and ApplicationContext in Spring – The java spring blog from the basics

Volley JsonObjectRequest Post request not working

All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.

How to configure heroku application DNS to Godaddy Domain?

I used this videocast to set up my GoDaddy domain with Heroku, and it worked perfectly. Very clear and well explained.

Note: Skip the part about CNAME yourdomain.com. (note the .) and the heroku addons:add "custom domains"

http://blog.heroku.com/archives/2009/10/7/heroku_casts_setting_up_custom_domains/


To summarize the video:

1) on GoDaddy and create a CNAME with

Alias Name: www
Host Name: proxy.heroku.com

2) check that your domain has propagated by typing host www.yourdomain.com on the command line

3) run heroku domains:add www.yourdomain.com

4) run heroku domains:add yourdomain.com

It worked for me after these steps. Hope it works for you too!

UPDATE: things have changed, check out this post Heroku/GoDaddy: send naked domain to www

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I already tried all of the possible solutions on stackoverflow and didn't work What I tried:

  1. Disable Hyper-V in windows feature
  2. Disable Hyper-V with command
  3. Disable Device Guard
  4. etc etc Above solution still give me information about Hyper-V in System Information and the HAXM still failed to install.

But finally I found the solution, you have to disable Hyper-V from System Configuration:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Check System Information then Hyper-V is off now

Removing All Items From A ComboBox?

me.Combobox1.Clear

This is the common method

Close iOS Keyboard by touching anywhere using Swift

You can also add a tap gesture recognizer to resign the keyboard. :D

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    backgroundView.addGestureRecognizer(recognizer)
}
    func handleTap(recognizer: UITapGestureRecognizer) {
    textField.resignFirstResponder()
    textFieldtwo.resignFirstResponder()
    textFieldthree.resignFirstResponder()

    println("tappped")
}

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Swift Bridging Header import issue

In my case this was actually an error as a result of a circular reference. I had a class imported in the bridging header, and that class' header file was importing the swift header (<MODULE_NAME>-Swift.h). I was doing this because in the Obj-C header file I needed to use a class that was declared in Swift, the solution was to simply use the @class declarative.

So basically the error said "Failed to import bridging header", the error above it said <MODULE_NAME>-Swift.h file not found, above that was an error pointing at a specific Obj-C Header file (namely a View Controller).

Inspecting this file I noticed that it had the -Swift.h declared inside the header. Moving this import to the implementation resolved the issue. So I needed to use an object, lets call it MyObject defined in Swift, so I simply changed the header to say

@class MyObject;

Remove non-ascii character in string

You can use the following regex to replace non-ASCII characters

str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')

However, note that spaces, colons and commas are all valid ASCII, so the result will be

> str
"INFO] :, , ,  (Higashikurume)"

Opposite of append in jquery

just had the same problem and ive come across this - which actually does the trick for me:

// $("#the_div").contents().remove();
// or short: 
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");

How to declare and use 1D and 2D byte arrays in Verilog?

It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.

reg a[0:3]; 

This will create a 1D of array of single bit. Similarly 2D array can be created like this:

reg [0:3][0:2];

Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:

reg [0:4] a [0:3][0:2];

How do I stop a program when an exception is raised in Python?

If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Why are empty catch blocks a bad idea?

Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up and being handled correctly by another try block. Always try and do something with the exception you are catching.

Working with huge files in VIM

Old thread. But nevertheless( pun :) ).

 $less filename

less works efficiently if you don't want to edit and just look around which is the case for examining huge log files.

Search in less works like vi

Best part, it's available by default on most distros. So won't be problem for production environment as well.

Android Fastboot devices not returning device

If you got nothing when inputted fastboot devices, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-'). Then you can see you devices via fastboot devices and continue to flash your devices.

note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

You can do this:

IEnumerable<object> list = new List<object>(){1, 4, 5}.AsEnumerable();
CallFunction(list);

Best database field type for a URL

This really depends on your use case (see below), but storing as TEXT has performance issues, and a huge VARCHAR sounds like overkill for most cases.

My approach: use a generous, but not unreasonably large VARCHAR length, such as VARCHAR(500) or so, and encourage the users who need a larger URL to use a URL shortener such as safe.mn.

The Twitter approach: For a really nice UX, provide an automatic URL shortener for overly-long URL's and store the "display version" of the link as a snippet of the URL with ellipses at the end. (Example: http://stackoverflow.com/q/219569/1235702 would be displayed as stackoverflow.com/q/21956... and would link to a shortened URL http://ex.ampl/e1234)

Notes and Caveats

  • Obviously, the Twitter approach is nicer, but for my app's needs, recommending a URL shortener was sufficient.
  • URL shorteners have their drawbacks, such as security concerns. In my case, it's not a huge risk because the URL's are not public and not heavily used; however, this obviously won't work for everyone. safe.mn appears to block a lot of spam and phishing URL's, but I would still recommend caution.
  • Be sure to note that you shouldn't force your users to use a URL shortener. For most cases (at least for my app's needs), 500 characters is overly sufficient for what most users will be using it for. Only use/recommend a URL shortener for overly-long links.

How to open every file in a folder

Os

You can list all files in the current directory using os.listdir:

import os
for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Glob

Or you can list only some files, depending on the file pattern using the glob module:

import glob
for filename in glob.glob('*.txt'):
   with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Pipe Or you can even use the pipe as you specified using fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

And then use it with piping:

ls -1 | python parse.py

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.

This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!

  • The Video shows you the JavaFx Sdk download
  • How to set it as a Global Library
  • Set the module-info.java (i prefer the bottom one)

module thisIsTheNameOfYourProject {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens sample;
}

The entire thing took me only 5mins !!!

RuntimeError: module compiled against API version a but this version of numpy is 9

You are likely running the Mac default (/usr/bin/python) which has an older version of numpy installed in the system folders. The easiest way to get python working with opencv is to use brew to install both python and opencv into /usr/local and run the /usr/local/bin/python.

brew install python
brew tap homebrew/science
brew install opencv

How to remove duplicates from Python list and keep order?

> but I don't know how to retrieve the list members from the hash in alphabetical order.

Not really your main question, but for future reference Rod's answer using sorted can be used for traversing a dict's keys in sorted order:

for key in sorted(my_dict.keys()):
   print key, my_dict[key]
   ...

and also because tuple's are ordered by the first member of the tuple, you can do the same with items:

for key, val in sorted(my_dict.items()):
    print key, val
    ...

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

This terminal command:

open /Applications/Python\ 3.7/Install\ Certificates.command

Found here: https://stackoverflow.com/a/57614113/6207266

Resolved it for me. With my config

pip install --upgrade certifi

had no impact.

Node.js/Express.js App Only Works on Port 3000

In app.js, just add...

process.env.PORT=2999;

This will isolate the PORT variable to the express application.

Get current date, given a timezone in PHP?

<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>

How to install PyQt5 on Windows?

Another command under the cmd is:

easy_install pyqt5

VSCode Change Default Terminal

You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.

Terminal Selection

Terminal Selection

Java image resize, maintain aspect ratio

public class ImageTransformation {

public static final String PNG = "png";

public static byte[] resize(FileItem fileItem, int width, int height) {

    try {
        ResampleOp resampleOp = new ResampleOp(width, height);
        BufferedImage scaledImage = resampleOp.filter(ImageIO.read(fileItem.getInputStream()), null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(scaledImage, PNG, baos);

        return baos.toByteArray();
    } catch (Exception ex) {
        throw new MapsException("An error occured during image resizing.", ex);
    }

}

public static byte[] resizeAdjustMax(FileItem fileItem, int maxWidth, int maxHeight) {

    try {
        BufferedInputStream bis = new BufferedInputStream(fileItem.getInputStream());  
        BufferedImage bufimg = ImageIO.read(bis);   

        //check size of image 
        int img_width = bufimg.getWidth();
        int img_height = bufimg.getHeight();
        if(img_width > maxWidth || img_height > maxHeight) {
            float factx = (float) img_width / maxWidth;
            float facty = (float) img_height / maxHeight;
            float fact = (factx>facty) ? factx : facty;
            img_width = (int) ((int) img_width / fact);
            img_height = (int) ((int) img_height / fact);
        }

        return resize(fileItem,img_width, img_height);

    } catch (Exception ex) {
        throw new MapsException("An error occured during image resizing.", ex);
    }

}

}

Check if element is visible in DOM

If you're interested in visible by the user:

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

Tested on (using mocha terminology):

describe.only('visibility', function () {
    let div, visible, notVisible, inViewport, leftOfViewport, rightOfViewport, aboveViewport,
        belowViewport, notDisplayed, zeroOpacity, zIndex1, zIndex2;
    before(() => {
        div = document.createElement('div');
        document.querySelector('body').appendChild(div);
        div.appendChild(visible = document.createElement('div'));
        visible.style       = 'border: 1px solid black; margin: 5px; display: inline-block;';
        visible.textContent = 'visible';
        div.appendChild(inViewport = visible.cloneNode(false));
        inViewport.textContent = 'inViewport';
        div.appendChild(notDisplayed = visible.cloneNode(false));
        notDisplayed.style.display = 'none';
        notDisplayed.textContent   = 'notDisplayed';
        div.appendChild(notVisible = visible.cloneNode(false));
        notVisible.style.visibility = 'hidden';
        notVisible.textContent      = 'notVisible';
        div.appendChild(leftOfViewport = visible.cloneNode(false));
        leftOfViewport.style.position = 'absolute';
        leftOfViewport.style.right = '100000px';
        leftOfViewport.textContent = 'leftOfViewport';
        div.appendChild(rightOfViewport = leftOfViewport.cloneNode(false));
        rightOfViewport.style.right       = '0';
        rightOfViewport.style.left       = '100000px';
        rightOfViewport.textContent = 'rightOfViewport';
        div.appendChild(aboveViewport = leftOfViewport.cloneNode(false));
        aboveViewport.style.right       = '0';
        aboveViewport.style.bottom       = '100000px';
        aboveViewport.textContent = 'aboveViewport';
        div.appendChild(belowViewport = leftOfViewport.cloneNode(false));
        belowViewport.style.right       = '0';
        belowViewport.style.top       = '100000px';
        belowViewport.textContent = 'belowViewport';
        div.appendChild(zeroOpacity = visible.cloneNode(false));
        zeroOpacity.textContent   = 'zeroOpacity';
        zeroOpacity.style.opacity = '0';
        div.appendChild(zIndex1 = visible.cloneNode(false));
        zIndex1.textContent = 'zIndex1';
        zIndex1.style.position = 'absolute';
        zIndex1.style.left = zIndex1.style.top = zIndex1.style.width = zIndex1.style.height = '100px';
        zIndex1.style.zIndex = '1';
        div.appendChild(zIndex2 = zIndex1.cloneNode(false));
        zIndex2.textContent = 'zIndex2';
        zIndex2.style.left = zIndex2.style.top = '90px';
        zIndex2.style.width = zIndex2.style.height = '120px';
        zIndex2.style.backgroundColor = 'red';
        zIndex2.style.zIndex = '2';
    });
    after(() => {
        div.parentNode.removeChild(div);
    });
    it('isVisible = true', () => {
        expect(isVisible(div)).to.be.true;
        expect(isVisible(visible)).to.be.true;
        expect(isVisible(inViewport)).to.be.true;
        expect(isVisible(zIndex2)).to.be.true;
    });
    it('isVisible = false', () => {
        expect(isVisible(notDisplayed)).to.be.false;
        expect(isVisible(notVisible)).to.be.false;
        expect(isVisible(document.createElement('div'))).to.be.false;
        expect(isVisible(zIndex1)).to.be.false;
        expect(isVisible(zeroOpacity)).to.be.false;
        expect(isVisible(leftOfViewport)).to.be.false;
        expect(isVisible(rightOfViewport)).to.be.false;
        expect(isVisible(aboveViewport)).to.be.false;
        expect(isVisible(belowViewport)).to.be.false;
    });
});

Predicate in Java

Adding up to what Micheal has said:

You can use Predicate as follows in filtering collections in java:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);

jQuery textbox change event

There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.

function InitPageControls() {
        CheckIfChanged();
    }

    function CheckIfChanged() {
        // do logic

        setTimeout(function () {
            CheckIfChanged();
        }, 1000);
    }

Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...

How to convert a string of bytes into an int?

In Python 3.2 and later, use

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
2043455163

or

>>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little')
3148270713

according to the endianness of your byte-string.

This also works for bytestring-integers of arbitrary length, and for two's-complement signed integers by specifying signed=True. See the docs for from_bytes.

Instantiating a generic type

No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?

JavaScript get clipboard data on paste event (Cross browser)

The situation has changed since writing this answer: now that Firefox has added support in version 22, all major browsers now support accessing the clipboard data in a paste event. See Nico Burns's answer for an example.

In the past this was not generally possible in a cross-browser way. The ideal would be to be able to get the pasted content via the paste event, which is possible in recent browsers but not in some older browsers (in particular, Firefox < 22).

When you need to support older browsers, what you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and WebKit browsers such as Safari or Chrome. Recent versions of both TinyMCE and CKEditor use this technique:

  1. Detect a ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a textarea element off-screen (say at left -1000px) to the document, turn designMode off and call focus() on the textarea, thus moving the caret and effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that stores the textarea value, removes the textarea from the document, turns designMode back on, restores the user selection and pastes the text in.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the textarea (in some browsers, at least).

In the unlikely event that you need to support Firefox 2, note that you'll need to place the textarea in the parent document rather than the WYSIWYG editor iframe's document in that browser.

How to fix a Div to top of page with CSS only

You can also use flexbox, but you'd have to add a parent div that covers div#top and div#term-defs. So the HTML looks like this:

_x000D_
_x000D_
    #content {_x000D_
        width: 100%;_x000D_
        height: 100%;_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
    }_x000D_
_x000D_
    #term-defs {_x000D_
        flex-grow: 1;_x000D_
        overflow: auto;_x000D_
    } 
_x000D_
    <body>_x000D_
        <div id="content">_x000D_
            <div id="top">_x000D_
                <a href="#A">A</a> |_x000D_
                <a href="#B">B</a> |_x000D_
                <a href="#Z">Z</a>_x000D_
            </div>_x000D_
    _x000D_
            <div id="term-defs">_x000D_
                <dl>_x000D_
                    <span id="A"></span>_x000D_
                    <dt>foo</dt>_x000D_
                    <dd>This is the sound made by a fool</dd>_x000D_
                    <!-- and so on ... -->_x000D_
                </dl>_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

flex-grow ensures that the div's size is equal to the remaining size.

You could do the same without flexbox, but it would be more complicated to work out the height of #term-defs (you'd have to know the height of #top and use calc(100% - 999px) or set the height of #term-defs directly).
With flexbox dynamic sizes of the divs are possible.

One difference is that the scrollbar only appears on the term-defs div.

download file using an ajax request

there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.

First you need to separate the page processing from the results download.

1) Only the page calculations are made in the ajax call.

$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" },

       function(data, status) 
       {
            if (status == "success") 
            {
                /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */
                window.location.href = DownloadPage.php+"?ID="+29;
            }               
       }
);

// For example: in the CalculusPage.php

    if ( !empty($_POST["calculusFunction"]) ) 
    {
        $ID = $_POST["ID"];

        $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;
        ...
    }

// For example: in the DownloadPage.php

    $ID = $_GET["ID"];

    $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID;
    ...

    $filename="Export_Data.xls";
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: inline; filename=$filename");

    ...

I hope this solution can be useful for many, as it was for me.

Getting GET "?" variable in laravel

In laravel 5.3

I want to show the get param in my view

Step 1 : my route

Route::get('my_route/{myvalue}', 'myController@myfunction');

Step 2 : Write a function inside your controller

public function myfunction($myvalue)
{
    return view('get')->with('myvalue', $myvalue);
}

Now you're returning the parameter that you passed to the view

Step 3 : Showing it in my View

Inside my view you i can simply echo it by using

{{ $myvalue }}

So If you have this in your url

http://127.0.0.1/yourproject/refral/[email protected]

Then it will print [email protected] in you view file

hope this helps someone.

Invalid hook call. Hooks can only be called inside of the body of a function component

Caught this error: found solution.

For some reason, there were 2 onClick attributes on my tag. Be careful with using your or somebodies' custom components, maybe some of them already have onClick attribute.

Regular Expression for any number greater than 0?

there you go:

MatchCollection myMatches = Regex.Matches(yourstring, @"[1-9][0-9]*");

on submit:

if(myMatches.Count > 0)
{
   //do whatever you want
}

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

Maven in Eclipse: step by step installation

You have to follow the following steps in the Eclipse IDE

  1. Go to Help - > Install New Software
  2. Click add button at top right corner
  3. In the popup coming, type in name as "Maven" and location as "http://download.eclipse.org/technology/m2e/releases"
  4. Click on OK.

Maven integration for eclipse will be dowloaded and installed. Restart the workspace.

In the .m2 folder(usually under C:\user\ directory) add settings.xml. Give proper proxy and profiles. Now create a new Maven project in eclipse.

Identifying and removing null characters in UNIX

I discovered the following, which prints out which lines, if any, have null characters:

perl -ne '/\000/ and print;' file-with-nulls

Also, an octal dump can tell you if there are nulls:

od file-with-nulls | grep ' 000'

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

I tried all the above and found them wanting. This is the simplest most flexible solution I could figure out (thanks to all of the above for inspiration).

HTML

<div id="container">
<ul>
    <li>HOME</li>
    <li>ABOUT US</li>
    <li>SERVICES</li>
    <li>PREVIOUS PROJECTS</li>
    <li>TESTIMONIALS</li>
    <li>NEWS</li>
    <li>RESEARCH &amp; DEV</li>
    <li>CONTACT</li>
</ul>
</div>

CSS

div#container{
  width:900px;
  background-color:#eee;
    padding:20px;
}
ul {
    display:table;
    width: 100%;
    margin:0 0;
    -webkit-padding-start:0px; /* reset chrome default */
}
ul li {
    display:table-cell;
    height:30px;
    line-height:30px;
    font-size:12px;    
    padding:20px 10px;
    text-align: center;
    background-color:#999;
    border-right:2px solid #fff;
}
ul li:first-child {
    border-radius:10px 0 0 10px;
}
ul li:last-child {
    border-radius:0 10px 10px 0;
    border-right:0 none;
}

You can drop the first/last child-rounded ends, obviously, but I think they're real purdy (and so does your client ;)

The container width limits the horizontal list, but you can ditch this and just apply an absolute value to the UL if you like.

Fiddle with it, if you like..

http://jsfiddle.net/tobyworth/esehY/1/

How to set seekbar min and max value

    private static final int MIN_METERS = 100;
    private static final int JUMP_BY = 50;

    metersText.setText(meters+"");
    metersBar.setProgress((meters-MIN_METERS));
    metersBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            progress = progress + MIN_METERS;
            progress = progress / JUMP_BY;
            progress = progress * JUMP_BY;
            metersText.setText((progress)+"");
        }
    });
}

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Can I stop 100% Width Text Boxes from extending beyond their containers?

Actually, it's because CSS defines 100% relative to the entire width of the container, including its margins, borders, and padding; that means that the space avail. to its contents is some amount smaller than 100%, unless the container has no margins, borders, or padding.

This is counter-intuitive and widely regarded by many to be a mistake that we are now stuck with. It effectively means that % dimensions are no good for anything other than a top level container, and even then, only if it has no margins, borders or padding.

Note that the text field's margins, borders, and padding are included in the CSS size specified for it - it's the container's which throw things off.

I have tolerably worked around it by using 98%, but that is a less than perfect solution, since the input fields tend to fall further short as the container gets larger.


EDIT: I came across this similar question - I've never tried the answer given, and I don't know for sure if it applies to your problem, but it seems like it will.

Check if a variable is between two numbers with Java

I see some errors in your code.
Your probably meant the mathematical term

90 <= angle <= 180, meaning angle in range 90-180.

if (angle >= 90 && angle <= 180) {

// do action
}

JavaScript naming conventions

You can follow this Google JavaScript Style Guide

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

EDIT: See nice collection of JavaScript Style Guides And Beautifiers.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

In my case I had edited the eclipse.ini for a different purpose to include -vm parameter. That was causing the failure. I removed the -vm and following line where I had included \bin and that fixed the problem.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

This issue can also happen due to the following

1.In the Web.Config

<system.webServer>
     <modules runAllManagedModulesForAllRequests="true" /> 
<system.webServer>

2.Make sure the following are available in the bin folder on the server where the Web API is deployed

  • System.Net.Http

  • System.Net.Http.Formatting

  • System.Web.Http.WebHost

  • System.Web.Http

These assemblies won't be copied in the bin folder by default if the publish is through Visual Studio because the Web API packages are installed through Nuget in the development machine. Still if you want to achieve these files to be available as part of Visual Studio publish then you need to set CopyLocal to True for these Assemblies

Sadish Kumar.V

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

python: order a list of numbers without built-in sort, min, max function

My method-

s = [-5, -23, 5, 0, 23, -6, 23, 67]
nl = []
for i in range(len(s)):
    a = min(s)
    nl.append(a)
    s.remove(a)

print nl

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

Create PDF from a list of images

The best method to convert multiple images to PDF I have tried so far is to use PIL purely. It's quite simple yet powerful:

from PIL import Image

im1 = Image.open("/Users/apple/Desktop/bbd.jpg")
im2 = Image.open("/Users/apple/Desktop/bbd1.jpg")
im3 = Image.open("/Users/apple/Desktop/bbd2.jpg")
im_list = [im2,im3]

pdf1_filename = "/Users/apple/Desktop/bbd1.pdf"

im1.save(pdf1_filename, "PDF" ,resolution=100.0, save_all=True, append_images=im_list)

Just set save_all to True and append_images to the list of images which you want to add.

You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'. The solution is here Error while saving multiple JPEGs as a multi-page PDF

Note:Install the newest PIL to make sure save_all argument is available for PDF.

Hashmap with Streams in Java 8 Streams to collect value of Map

If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst :

Optional<List> o = id1.entrySet()
                      .stream()
                      .filter( e -> e.getKey() == 1)
                      .map(Map.Entry::getValue)
                      .findFirst();

In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :

List<List> list = id1.entrySet()
                     .stream()
                     .filter(.. some predicate...)
                     .map(Map.Entry::getValue)
                     .collect(Collectors.toList());

Should I learn C before learning C++?

My two cents:

I suggest to learn C first, because :

  • it is a fundamental language - a lot of languages descended from C
  • more platforms supports C compiler than C++,- be it embedded systems, GPU chips, etc.
  • according to TIOBE index C is still about 2 times more popular than C++.

UITapGestureRecognizer - single tap and double tap

Swift 3 solution:

let singleTap = UITapGestureRecognizer(target: self, action:#selector(self.singleTapAction(_:)))
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)

let doubleTap = UITapGestureRecognizer(target: self, action:#selector(self.doubleTapAction(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)

singleTap.require(toFail: doubleTap)

In the code line singleTap.require(toFail: doubleTap) we are forcing the single tap to wait and ensure that the tap event is not a double tap.

How do I migrate an SVN repository with history to a new Git repository?

Several answers here refer to https://github.com/nirvdrum/svn2git, but for large repositories this can be slow. I had a try using https://github.com/svn-all-fast-export/svn2git instead which is a tool with exactly the same name but was used to migrate KDE from SVN to Git.

Slightly more work to set it up but when done the conversion itself for me took minutes where the other script spent hours.

FIFO class in Java

Try ArrayDeque or LinkedList, which both implement the Queue interface.

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

The import javax.persistence cannot be resolved

Yes, you will likely need to add another jar or dependency

javax.persistence.* is part of the Java Persistence API (JPA). It is only an API, you can think of it as similar to an interface. There are many implementations of JPA and this answer gives a very good elaboration of each, as well as which to use.

If your javax.persistence.* import cannot be resolved, you will need to provide the jar that implements JPA. You can do that either by manually downloading it (and adding it to your project) or by adding a declaration to a dependency management tool (for eg, Ivy/Maven/Gradle). See here for the EclipseLink implementation (the reference implementation) on Maven repo.

After doing that, your imports should be resolved.

Also see here for what is JPA about. The xml you are referring to could be persistence.xml, which is explained on page 3 of the link.

That being said, you might just be pointing to the wrong target runtime

If i recall correctly, you don't need to provide a JPA implementation if you are deploying it into a JavaEE app server like JBoss. See here "Note that you typically don't need it when you deploy your application in a Java EE 6 application server (like JBoss AS 6 for example).". Try changing your project's target runtime.

If your local project was setup to point to Tomcat while your remote repo assumes a JavaEE server, this could be the case. See here for the difference between Tomcat and JBoss.

Edit: I changed my project to point to GlassFish instead of Tomcat and javax.persistence.* resolved fine without any explicit JPA dependency.

Click a button programmatically - JS

I have never developed with HangOut. I ran into the same problems with FB-login and I was trying so hard to get it to click programatically. Then later I discovered that the sdk won't allow you to programatically click the button because of some security reasons. The user has to physically click on the button. This also happens with async asp fileupload button. So please check if HangOut does allow you to programatically click a buttton. All above codes are correct and they should work. If you dig deep enough you will see that my answer is the right answer for your situation you.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Where do I find the current C or C++ standard documents?

Draft Links:

C++11 (+editorial fixes): N3337 HTML, PDF

C++14 (+editorial fixes): N4140 HTML, PDF

C11 N1570 (text)

C99 N1256

Drafts of the Standard are circulated for comment prior to ratification and publication.

Note that a working draft is not the standard currently in force, and it is not exactly the published standard

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Unable instantiate android.gms.maps.MapFragment

I don't get the true solution but I solve it after doing these things:
- Tick 'Copy projects into workspace' when importing google-play-services_lib
- Don't set the minSdkVersion below 13
- If you get error with theme, try changing your layout theme to any system theme
- Re-create your project from scratch or revert everything if you get it from somewhere

ssh "permissions are too open" error

AFAIK the values are:

700 for the hidden directory ".ssh" where key file is located

600 for the keyfile "id_rsa"

syntax error: unexpected token <

make sure you are not including the jquery code between the

< script > < /script >

If so remove that and code will work fine, It worked in my case.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>

By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>

How to draw rounded rectangle in Android UI?

I think, this is you exactly needed.

Here drawable(xml) file that creates rounded rectangle. round_rect_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

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

    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />

</shape>

Here layout file: my_layout.xml

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/round_rect_shape"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Something text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff0000" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>
</LinearLayout>

-> In the above code, LinearLayout having the background(That is the key role to place to create rounded rectangle). So you can place any view like TextView, EditText... in that LinearLayout to see background as round rectangle for all.

How can I push a specific commit to a remote, and not previous commits?

The simplest way to accomplish this is to use two commands.

First, get the local directory into the state that you want. Then,

$ git push origin +HEAD^:someBranch

removes the last commit from someBranch in the remote only, not local. You can do this a few times in a row, or change +HEAD^ to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use

$ git push origin someBranch

as normal to update the remote.

Is there a "goto" statement in bash?

This solution had the following issues:

  • Indiscriminately removes all code lines ending in a :
  • Treates label: anywhere on a line as a label

Here's a fixed (shell-check clean) version:


#!/bin/bash

# GOTO for bash, based upon https://stackoverflow.com/a/31269848/5353461
function goto
{
 local label=$1
 cmd=$(sed -En "/^[[:space:]]*#[[:space:]]*$label:[[:space:]]*#/{:a;n;p;ba};" "$0")
 eval "$cmd"
 exit
}

start=${1:-start}
goto "$start"  # GOTO start: by default

#start:#  Comments can occur after labels
echo start
goto end

  # skip: #  Whitespace is allowed
echo this is usually skipped

# end: #
echo end

PHP/MySQL insert row then get 'id'

Try this... it worked for me!

$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
    if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    $msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    $msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

Unable to install boto3

I had a similar problem, but the accepted answer did not resolve it - I was not using a virtual environment. This is what I had to do:

sudo python -m pip install boto3

I do not know why this behaved differently from sudo pip install boto3.

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Simply....If you are not using NDK, there is no problem at all. On the other this is just warning not an error. With warning you can go ahead but not errors. Any it's better to adjust the whitespaces. E.g if your SDK is at C:\program file\Android studio. There is a whitespaces "program file". There are 2 simple methods: 1. Remove the whitespaces 2. Install at another location which don't have whitespaces.

Cross origin requests are only supported for HTTP but it's not cross-domain

If you have nodejs installed, you can download and install the server using command line:

npm install -g http-server

Change directories to the directory where you want to serve files from:

$ cd ~/projects/angular/current_project 

Run the server:

$ http-server 

which will produce the message Starting up http-server, serving on:

Available on: http://your_ip:8080 and http://127.0.0.1:8080

That allows you to use urls in your browser like

http://your_ip:8080/index.html

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

Change Toolbar color in Appcompat 21

You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CustomToolbar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    } 

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);
    }



    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);
        }

      //Step 3: Changing the color of title and subtitle.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
            }
        }

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                              innerView.post(new Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });
                        }
                    }
                }
            }
        }
    }



}

then refer to it in your layout file. Now you can set a custom color using

toolbar.setItemColor(Color.Red);

Sources:

I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

Explicitly select items from a list or tuple

like often when you have a boolean numpy array like mask

[mylist[i] for i in np.arange(len(mask), dtype=int)[mask]]

A lambda that works for any sequence or np.array:

subseq = lambda myseq, mask : [myseq[i] for i in np.arange(len(mask), dtype=int)[mask]]

newseq = subseq(myseq, mask)

How do I collapse a table row in Bootstrap?

You just need to set the table cell padding to zero. Here's a jsfiddle (using Bootstrap 2.3.2) with your code slightly modified:

http://jsfiddle.net/marciowerner/fhjgn7b5/4/

The javascript is optional and only needed if you want to use a cell padding other than zero.

_x000D_
_x000D_
$('.collapse').on('show.bs.collapse', function() {_x000D_
  $(this).parent().removeClass("zeroPadding");_x000D_
});_x000D_
_x000D_
$('.collapse').on('hide.bs.collapse', function() {_x000D_
  $(this).parent().addClass("zeroPadding");_x000D_
});
_x000D_
.zeroPadding {_x000D_
  padding: 0 !important;_x000D_
}
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
  <script type="text/javascript" src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
  <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table class="table table-bordered table-striped">_x000D_
    <tr>_x000D_
      <td>_x000D_
        <button type="button" class="btn" data-toggle="collapse" data-target="#collapseme">Click to expand</button>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="zeroPadding">_x000D_
        <div class="collapse out" id="collapseme">Should be collapsed</div>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Unexpected end of file error

You did forget to include stdafx.h in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h" is the first line in your .cpp file, otherwise you will see the same error even if you've included "stdafx.h" in your source file (but not in the very beginning of the file).

How do I declare a two dimensional array?

Just declare? You don't have to. Just make sure variable exists:

$d = array();

Arrays are resized dynamically, and attempt to write anything to non-exsistant element creates it (and creates entire array if needed)

$d[1][2] = 3;

This is valid for any number of dimensions without prior declarations.

ArrayList: how does the size increase?

Default capacity of ArrayList is 10. Once the Capacity reaches its maximum capacity, Size of the ArrayList will be 16, once the capacity reaches its maximum capacity of 16, size of the ArrayList will be 25 and keep on increasing based on Data size.....

How? Here is the Answer and Formula

New capacity = (Current Capacity * 3/2) + 1

So, if the default capacity is 10, then

Current Capacity = 10
New capacity = (10 * 3/2) + 1
Output is 16

Calculating time difference in Milliseconds

No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis(). That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.

To measure how long something takes, consider using System.nanoTime instead. The important point here isn't that the precision is greater, but that the resolution will be greater... but only when used to measure the time between two calls. It must not be used as a "wall clock".

Note that even System.nanoTime just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:

public class Test {
    public static void main(String[] args) throws Exception {

        long[] differences = new long[5];
        long previous = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            long current;
            while ((current = System.nanoTime()) == previous) {
                // Do nothing...
            }
            differences[i] = current - previous;
            previous = current;            
        }

        for (long difference : differences) {
            System.out.println(difference);
        }
    }
}

On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

How to read a text file in project's root directory?

private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

The method above will bring you something like this:

"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"

From here you can navigate backwards using System.IO.Directory.GetParent:

_filePath = Directory.GetParent(_filePath).FullName;

1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:

_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;

Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:

_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);

Hope it helps.

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

Deny access to one specific folder in .htaccess

You can do this dynamically that way:

mkdir($dirname);
@touch($dirname . "/.htaccess");
  $f = fopen($dirname . "/.htaccess", "w");
  fwrite($f, "deny from all");
fclose($f);

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

I would use this in HTML 5... Just sayin

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #f5f5f5;
}

Excel formula to reference 'CELL TO THE LEFT'

When creating a User Defined Function, I found out that the other answers involving the functions OFFSET and INDIRECT cannot be applied.

Instead, you have to use Application.Caller to refer to the cell the User Defined Function (UDF) has been used in. In a second step, you convert the column's index to the corresponding column's name.
Finally, you are able to reference the left cell using the active worksheet's Range function.

Function my_user_defined_function(argument1, argument2)
    ' Way to convert a column number to its name copied from StackOverflow
    ' http://stackoverflow.com/a/10107264
    ' Answer by Siddarth Rout (http://stackoverflow.com/users/1140579/siddharth-rout)
    ' License (if applicable due to the small amount of code): CC BY-SA 3.0
    colName = Split(Cells(, (Application.Caller(1).Column - 1)).Address, "$")(1)

    rowNumber = Application.Caller(1).Row

    left_cell_value = ActiveSheet.Range(colName & rowNumber).Value

    ' Now do something with left_cell_value

Set content of iframe

Using Blob:

var iframe = document.getElementById("myiframe");
var blob = new Blob([s], {type: "text/html; charset=utf-8"});
iframe.src = URL.createObjectURL(blob);

How can I refresh c# dataGridView after update ?

Rebind your DatagridView to the source.

DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;

// Update Data in src1

dg1.DataSource = null;
dg1.DataSource = src1;

Pause Console in C++ program

I just want to add that there is a way to get what you want, but it will require to use some a third party library (or that you write the platform dependent code yourself).

As far as I'm concerned, the biggest drawback with cin is that you are required to hit Return, and not just any key.

Assuming you had a key-listener you could quite easily write a function that waits for the user to hit any key. However finding a platform independent key listener is no trivial task, and will most likely require you to load parts of a larger library.

I am thinking something along the lines of:

char wait_for_key() {
    int key;
    while ( ! (key == key_pressed(ANY)) ) {
          this_thread::yield();
    }
    return convert_virtual_key_to_char(key);
}

The actual function would obviously be quite different from what I wrote, depending on the library you use.

I know the following libraries have keylisteners (Feel free to add more in an edit if you know of any.):

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

Batch Renaming of Files in a Directory

directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"

for counter, filename in enumerate(os.listdir(directoryName)):

    filenameWithPath = os.path.join(filePathWithSlash, filename)

    os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
          str(counter).zfill(4) + ".jpg" ))

# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
# The string.replace call swaps in the new filename into 
# the current filename within the filenameWitPath string. Which    
# is then used by os.rename to rename the file in place, using the  
# current (unmodified) filenameWithPath.

# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os 
# a specific location of the file to be renamed is required.

# this code is from Windows 

Does --disable-web-security Work In Chrome Anymore?

Try this :

Windows:

Fire below commands in CMD to start a new instance of chrome browser with disabled security

Go to Chrome folder:

cd C:\Program Files (x86)\Google\Chrome\Application

Run below command:

chrome.exe --disable-web-security --user-data-dir=c:\my-chrome-data\data

MAC OS:

Run this command in terminal:

open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_sess_1" --disable-web-security

Hope this will help both Windows & Mac users!

MVC Razor Hidden input and passing values

A move from WebForms to MVC requires a complete sea-change in logic and brain processes. You're no longer interacting with the 'form' both server-side and client-side (and in fact even with WebForms you weren't interacting client-side). You've probably just mixed up a bit of thinking there, in that with WebForms and RUNAT="SERVER" you were merely interacting with the building of the Web page.

MVC is somewhat similar in that you have server-side code in constructing the model (the data you need to build what your user will see), but once you have built the HTML you need to appreciate that the link between the server and the user no longer exists. They have a page of HTML, that's it.

So the HTML you are building is read-only. You pass the model through to the Razor page, which will build HTML appropriate to that model.

If you want to have a hidden element which sets true or false depending on whether this is the first view or not you need a bool in your model, and set it to True in the Action if it's in response to a follow up. This could be done by having different actions depending on whether the request is [HttpGet] or [HttpPost] (if that's appropriate for how you set up your form: a GET request for the first visit and a POST request if submitting a form).

Alternatively the model could be set to True when it's created (which will be the first time you visit the page), but after you check the value as being True or False (since a bool defaults to False when it's instantiated). Then using:

@Html.HiddenFor(x => x.HiddenPostBack)

in your form, which will put a hidden True. When the form is posted back to your server the model will now have that value set to True.

It's hard to give much more advice than that as your question isn't specific as to why you want to do this. It's perhaps vital that you read a good book on moving to MVC from WebForms, such as Steve Sanderson's Pro ASP.NET MVC.

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/

One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..

It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)

How to convert an address to a latitude/longitude?

Google has a geocoding API which seems to work pretty well for most of the locations that they have Google Maps data for.

http://googlemapsapi.blogspot.com/2006/06/geocoding-at-last.html

They provide online geocoding (via JavaScript):

http://code.google.com/apis/maps/documentation/services.html#Geocoding

Or backend geocoding (via an HTTP request):

http://code.google.com/apis/maps/documentation/services.html#Geocoding_Direct

The data is usually the same used by Google Maps itself. (note that there are some exceptions to this, such as the UK or Israel, where the data is from a different source and of slightly reduced quality)

SQL JOIN - WHERE clause vs. ON clause

In terms of the optimizer, it shouldn't make a difference whether you define your join clauses with ON or WHERE.

However, IMHO, I think it's much clearer to use the ON clause when performing joins. That way you have a specific section of you query that dictates how the join is handled versus intermixed with the rest of the WHERE clauses.

Convert iterator to pointer?

A vector is a container with full ownership of it's elements. One vector cannot hold a partial view of another, even a const-view. That's the root cause here.

If you need that, make your own container that has views with weak_ptr's to the data, or look at ranges. Pair of iterators (even pointers work well as iterators into a vector) or, even better, boost::iterator_range that work pretty seamlessly.

It depends on the templatability of your code. Use std::pair if you need to hide the code in a cpp.

selectOneMenu ajax events

Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as

<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>

then,

<p:selectOneMenu .....></p:selectOneMenu>

and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SET NOCOUNT ON usage

SET NOCOUNT ON;

This line of code is used in SQL for not returning the number rows affected in the execution of the query. If we don't require the number of rows affected, we can use this as this would help in saving memory usage and increase the speeed of execution of the query.

Differences between Ant and Maven

Ant is mainly a build tool.

Maven is a project and dependencies management tool (which of course builds your project as well).

Ant+Ivy is a pretty good combination if you want to avoid Maven.

Swift UIView background color opacity

Setting alpha property of a view affects its subviews. If you want just transparent background set view's backgroundColor proprty to a color that has alpha component smaller than 1.

view.backgroundColor = UIColor.white.withAlphaComponent(0.5)

Converting a value to 2 decimal places within jQuery

you can use just javascript for it

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 

Getting the base url of the website and globally passing it to twig in Symfony 2

Base url is defined inside Symfony\Component\Routing\RequestContext.

It can be fetched from controller like this:

$this->container->get('router')->getContext()->getBaseUrl()

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

PHP - define constant inside a class

See Class Constants:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".


EDIT - Perhaps what you're looking for is this static properties / variables:

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

Convert Existing Eclipse Project to Maven Project

I was having the same issue and wanted to Mavenise entire eclipse workspace containing around 60 Eclipse projects. Doing so manually required a lot of time and alternate options were not that viable. To solve the issue I finally created a project called eclipse-to-maven on github. As eclipse doesn't have all necessary information about the dependencies, it does the following:

  • Based on <classpathentry/> XML elements in .classpath file, it creates the dependencies on another project, identifies the library jar file and based on its name (for instance jakarta-oro-2.0.8.jar) identifies its version. Currently artifactId and groupId are same as I couldn't find something which could return me the Maven groupId of the dependency based on artifactId. Though this is not a perfect solution it provides a good ground to speed up Mavenisation.

  • It moves all source folders according to Maven convention (like src/main/java)

  • As Eclipse projects having names with spaces are difficult to deal on Linux/Unix environment, it renames them as well with names without spaces.

  • Resultant pom.xml files contain the dependencies and basic pom structure. You have to add required Maven plugins manually.

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

SQL Server: How to check if CLR is enabled?

The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.

I use this script to enable on a server, if the option is disabled:

if not exists(
    SELECT value
    FROM sys.configurations
    WHERE name = 'clr enabled'
     and value = 1
)
begin
    exec sp_configure @configname=clr_enabled, @configvalue=1
    reconfigure
end

How to make a class JSON serializable

Do you have an idea about the expected output? For example, will this do?

>>> f  = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'

In that case you can merely call json.dumps(f.__dict__).

If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization.

For a trivial example, see below.

>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
        def default(self, o):
            return o.__dict__    

>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'

Then you pass this class into the json.dumps() method as cls kwarg:

json.dumps(cls=MyEncoder)

If you also want to decode then you'll have to supply a custom object_hook to the JSONDecoder class. For example:

>>> def from_json(json_object):
        if 'fname' in json_object:
            return FileItem(json_object['fname'])
>>> f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')
>>> f
<__main__.FileItem object at 0x9337fac>
>>> 

How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

Add number of days to a date

$date = "04/28/2013 07:30:00";

$dates = explode(" ",$date);

$date = strtotime($dates[0]);

$date = strtotime("+6 days", $date);

echo date('m/d/Y', $date)." ".$dates[1];

What is the equivalent of Java's System.out.println() in Javascript?

I'm also about to ask the same question. But from what I've learned from codeacademy.com below code is enough to display the output or text?

print("hello world")  

When a 'blur' event occurs, how can I find out which element focus went *to*?

I am also trying to make Autocompleter ignore blurring if a specific element clicked and have a working solution, but for only Firefox due to explicitOriginalTarget

Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( 
        function(origfunc, ev) {
            if ($(this.options.ignoreBlurEventElement)) {
                var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);
                if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {
                    return origfunc(ev);
                }
            }
        }
    );

This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.

private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
    {
        // row represent particular row you want to bold its content.
        for (i = 0; i < columnCollection.Count; i++)
        {
            DataColumn col = columnCollection[i];
            xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
            // Some Font Styles
            xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
            xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
            //xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
        }
    }

You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection to your columns name and change col.Caption to specific column name.

Alternate

You may do this to cell of excel sheet you want bold.

xlWorkSheet.Cells[row, column].Style.Font.Bold = true;

How to show current time in JavaScript in the format HH:MM:SS?

_x000D_
_x000D_
function realtime() {
  
  let time = moment().format('hh:mm:ss.SS a').replace("m", "");
  document.getElementById('time').innerHTML = time;
  
  setInterval(() => {
    time = moment().format('hh:mm:ss.SS A');
    document.getElementById('time').innerHTML = time;
  }, 0)
}

realtime();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

<div id="time"></div>
_x000D_
_x000D_
_x000D_

Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

Entity Framework: There is already an open DataReader associated with this Command

A good middle-ground between enabling MARS and retrieving the entire result set into memory is to retrieve only IDs in an initial query, and then loop through the IDs materializing each entity as you go.

For example (using the "Blog and Posts" sample entities as in this answer):

using (var context = new BlogContext())
{
    // Get the IDs of all the items to loop through. This is
    // materialized so that the data reader is closed by the
    // time we're looping through the list.
    var blogIds = context.Blogs.Select(blog => blog.Id).ToList();

    // This query represents all our items in their full glory,
    // but, items are only materialized one at a time as we
    // loop through them.
    var blogs =
        blogIds.Select(id => context.Blogs.First(blog => blog.Id == id));

    foreach (var blog in blogs)
    {
        this.DoSomethingWith(blog.Posts);

        context.SaveChanges();
    }
}

Doing this means that you only pull a few thousand integers into memory, as opposed to thousands of entire object graphs, which should minimize memory usage while enabling you to work item-by-item without enabling MARS.

Another nice benefit of this, as seen in the sample, is that you can save changes as you loop through each item, instead of having to wait until the end of the loop (or some other such workaround), as would be needed even with MARS enabled (see here and here).

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

adding onclick event to dynamically added button?

but.onclick = callJavascriptFunction;

no double quotes no parentheses.

Show special characters in Unix while using 'less' Command

In the same spirit as https://stackoverflow.com/a/6943976/7154924:

cat -A

-A, --show-all
       equivalent to -vET
-v, --show-nonprinting
       use ^ and M- notation, except for LFD and TAB
-E, --show-ends
       display $ at end of each line
-T, --show-tabs
       display TAB characters as ^I

Alternatively, or at the same time, you can pipe to tr to substitute arbitrary characters to the desired ones for display, before piping to a pager like less if desired.

How do function pointers in C work?

One of the big uses for function pointers in C is to call a function selected at run-time. For example, the C run-time library has two routines, qsort and bsearch, which take a pointer to a function that is called to compare two items being sorted; this allows you to sort or search, respectively, anything, based on any criteria you wish to use.

A very basic example, if there is one function called print(int x, int y) which in turn may require to call a function (either add() or sub(), which are of the same type) then what we will do, we will add one function pointer argument to the print() function as shown below:

#include <stdio.h>

int add()
{
   return (100+10);
}

int sub()
{
   return (100-10);
}

void print(int x, int y, int (*func)())
{
    printf("value is: %d\n", (x+y+(*func)()));
}

int main()
{
    int x=100, y=200;
    print(x,y,add);
    print(x,y,sub);

    return 0;
}

The output is:

value is: 410
value is: 390

Nginx: stat() failed (13: permission denied)

I finally found my way through. In short, let's say your username is joe and you hold a website under your personal filesystem /home/joe/path/to/website.

You literally have to tell the system that nginx is your pal.
Place nginx in joe group :

sudo gpasswd -a nginx joe

After that if it still doesn't work, check right access of /home/joe directory. That's probably the reason why nginx can't reach the file because even if he is your friend now you have to open him the door to your house :

sudo chmod g+x /home/joe

That's it. That's literally all you have to do to give nginx access to your local files :)

I don't think there are security concerns with this method because nginx is the high authority and only an admin can change the group. nginx can now read what's in joe directories. It's only a security breach if the holder of the nginx account is different with the user you open directory access from, but in my case I'm the holder of both parties, that is in a local context.

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

POST request with JSON body

I think cURL would be a good solution. This is not tested, but you can try something like this:

$body = '{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

How to get label text value form a html page?

This will get what you want in plain JS.

var el = document.getElementById('*spaM4');
text = (el.innerText || el.textContent);

FIDDLE

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


How to get name of dataframe column in pyspark?

I found the answer is very very simple...

// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();

The variable "theNameOftheCol" is "colName"

Android Studio is slow (how to speed up)?

It's not compiling that's hurting me here, it's the typing. I could disable all the smart features and be back to notepad++ like TomTsagk suggested in a comment. For today I need more cores and RAM.

Playing devil's advocate I'd argue that typing shouldn't require a 16Gb PC octacore PC. Liked Sajan Rana's advice but things are so slow here it felt mostly a placebo.

To be fair I am using 1.4RC1, which is just short of being in the stable branch. Turning the internet off helped a little. The new feature of simultaneous Design (Preview) and Text views working with XML layouts is very helpful.

No, it is ridiculous. Never leave the stable channel.

find all unchecked checkbox in jquery

To select by class, you can do this:

$("input.className:checkbox:not(:checked)")

What's a good (free) visual merge tool for Git? (on windows)

  • TortoiseMerge (part of ToroiseSVN) is much better than kdiff3 (I use both and can compare);
  • p4merge (from Perforce) works also very well;
  • Diffuse isn't so bad;
  • Diffmerge from SourceGear has only one flaw in handling UTF8-files without BOM, making in unusable for this case.

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

Delete all lines beginning with a # from a file

Here is it with a loop for all files with some extension:

ll -ltr *.filename_extension > list.lst

for i in $(cat list.lst | awk '{ print $8 }') # validate if it is the 8 column on ls 
do
    echo $i
    sed -i '/^#/d' $i
done

Laravel 5 - redirect to HTTPS

You can use RewriteRule to force ssl in .htaccess same folder with your index.php
Please add as picture attach, add it before all rule others setting ssl .htaccess

How to convert int to float in C?

I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.

AngularJS. How to call controller function from outside of controller component

It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.

But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.

Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)

How do I remove leading whitespace in Python?

To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

Is it possible to disable the network in iOS Simulator?

There are two way to disable IOS Simulator internet:

  • Unplug your network connection
  • Turn Wi-Fi off

It's the simplest way

Storing Form Data as a Session Variable

Yes this is possible. kizzie is correct with the session_start(); having to go first.

another observation I made is that you need to filter your form data using:

strip_tags($value);

and/or

stripslashes($value);

How to change the icon of .bat file programmatically?

Try BatToExe converter. It will convert your batch file to an executable, and allow you to set an icon for it.

Same font except its weight seems different on different browsers

I collected and tested discussed solutions:

Windows10 Prof x64:

* FireFox v.56.0 x32 
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0

Semi (still micro fat in Safari) solved fatty fonts:

text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac

Have no visual effect

line-height: 1;
text-rendering: optimizeLegibility; 
speak: none;
font-style: normal;
font-variant: normal;

Wrong visual effect:

-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari

do not forget to set !important when testing or be sure that your style is not overridden

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

How to get anchor text/href on click using jQuery?

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

How to get duplicate items from a list using LINQ?

I was trying to solve the same with a list of objects and was having issues because I was trying to repack the list of groups into the original list. So I came up with looping through the groups to repack the original List with items that have duplicates.

public List<MediaFileInfo> GetDuplicatePictures()
{
    List<MediaFileInfo> dupes = new List<MediaFileInfo>();
    var grpDupes = from f in _fileRepo
                   group f by f.Length into grps
                   where grps.Count() >1
                   select grps;
    foreach (var item in grpDupes)
    {
        foreach (var thing in item)
        {
            dupes.Add(thing);
        }
    }
    return dupes;
}