Programs & Examples On #Uiimage

The basic image handling class of Cocoa-Touch on iOS. It is Available in iOS 2.0 and later.

UIImageView aspect fit and center

[your_imageview setContentMode:UIViewContentModeCenter];

How to Rotate a UIImage 90 degrees?

For Swift: Here is a simple extension to UIImage:

//ImageRotation.swift

import UIKit

extension UIImage {  
    public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
        let radiansToDegrees: (CGFloat) -> CGFloat = {
            return $0 * (180.0 / CGFloat(M_PI))
        }
        let degreesToRadians: (CGFloat) -> CGFloat = {
            return $0 / 180.0 * CGFloat(M_PI)
        }

        // calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
        let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
        rotatedViewBox.transform = t
        let rotatedSize = rotatedViewBox.frame.size

        // Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize)
        let bitmap = UIGraphicsGetCurrentContext()

        // Move the origin to the middle of the image so we will rotate and scale around the center.
        CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);

        //   // Rotate the image context
        CGContextRotateCTM(bitmap, degreesToRadians(degrees));

        // Now, draw the rotated/scaled image into the context
        var yFlip: CGFloat

        if(flip){
            yFlip = CGFloat(-1.0)
        } else {
            yFlip = CGFloat(1.0)
        }

        CGContextScaleCTM(bitmap, yFlip, -1.0)
        CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }
}

(Source)

Use it with:

rotatedPhoto = rotatedPhoto?.imageRotatedByDegrees(90, flip: false) 

The former will rotate an image and flip it if flip is set to true.

UIImage resize (Scale proportion)

Try to make the bounds's size integer.

#include <math.h>
....

    if (ratio > 1) {
        bounds.size.width = resolution;
        bounds.size.height = round(bounds.size.width / ratio);
    } else {
        bounds.size.height = resolution;
        bounds.size.width = round(bounds.size.height * ratio);
    }

How to set the opacity/alpha of a UIImage?

If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:

    UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
//  UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);

If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.

Hopefully, this reply will save beginners a lot of aggravation.

How can I take an UIImage and give it a black border?

This function will return you image with black border try this.. hope this will help you

- (UIImage *)addBorderToImage:(UIImage *)image frameImage:(UIImage *)blackBorderImage
{
    CGSize size = CGSizeMake(image.size.width,image.size.height);
    UIGraphicsBeginImageContext(size);

    CGPoint thumbPoint = CGPointMake(0,0);

    [image drawAtPoint:thumbPoint];


    UIGraphicsBeginImageContext(size);
    CGImageRef imgRef = blackBorderImage.CGImage;
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width,size.height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGPoint starredPoint = CGPointMake(0, 0);
    [imageCopy drawAtPoint:starredPoint];
    UIImage *imageC = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageC;
}

Creating a UIImage from a UIColor to use as a background image for UIButton

Are you using ARC? The problem here is that you don't have a reference to the UIColor object that you're trying to apply; the CGColor is backed by that UIColor, but ARC will deallocate the UIColor before you have a chance to use the CGColor.

The clearest solution is to have a local variable pointing to your UIColor with the objc_precise_lifetime attribute.

You can read more about this exact case on this article about UIColor and short ARC lifetimes or get more details about the objc_precise_lifetime attribute.

How to Resize image in Swift?

Swift 3 Version and Extension style

This answer come from @Kirit Modi.

extension UIImage {

    func resizeImage(targetSize: CGSize) -> UIImage {
        let size = self.size

        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height

        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}

add image to uitableview cell

Swift 4 solution:

    cell.imageView?.image = UIImage(named: "yourImageName")

The simplest way to resize an UIImage?

Swift 4 answer:

func scaleDown(image: UIImage, withSize: CGSize) -> UIImage {
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(withSize, false, scale)
    image.draw(in: CGRect(x: 0, y: 0, width: withSize.width, height: withSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

How to save picture to iPhone photo library?

For Swift 5.0

I used this code to copy images to photo albums my application had created; When I want to copy images files I call "startSavingPhotoAlbume()" function. First I get UIImage from App folder then save it to photo albums. Because it is irrelevant I dont show how to read image from App folder.

var saveToPhotoAlbumCounter = 0



func startSavingPhotoAlbume(){
    saveToPhotoAlbumCounter = 0
    saveToPhotoAlbume()
}

func saveToPhotoAlbume(){  
    let image = loadImageFile(fileName: imagefileList[saveToPhotoAlbumCounter], folderName: folderName)
    UIImageWriteToSavedPhotosAlbum(image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}

@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if (error != nil) {
        print("ptoto albume savin error for \(imageFileList[saveToPhotoAlbumCounter])")
    } else {
        
        if saveToPhotoAlbumCounter < imageFileList.count - 1 {
            saveToPhotoAlbumCounter += 1
            saveToPhotoAlbume()
        } else {
            print("saveToPhotoAlbume is finished with \(saveToPhotoAlbumCounter) files")
        }
    }
}

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How can I color a UIImage in Swift?

For iOS13+ there are withTintColor(__:) and withTintColor(_:renderingMode:) methods.

Example usage:

let newImage = oldImage.withTintColor(.red)

or

let newImage = oldImage.withTintColor(.red, renderingMode: .alwaysTemplate)

Convert between UIImage and Base64 string

//convert Image to Base64 (Encoding)

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

print(strBase64)

// convert Base64 to Image (Decoding)

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!

let decodedimage:UIImage = UIImage(data: dataDecoded)!

print(decodedimage)

yourImageView.image = decodedimage

How do you create a UIImage View Programmatically - Swift

You can use above in one line.

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

iOS UIImagePickerController result image orientation after upload

This what I have found for fixing orientation issue

UIImage *initialImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *data = UIImagePNGRepresentation(self.initialImage);

UIImage *tempImage = [UIImage imageWithData:data];
UIImage *fixedOrientationImage = [UIImage imageWithCGImage:tempImage.CGImage
                                     scale:initialImage.scale
                               orientation:self.initialImage.imageOrientation];
initialImage = fixedOrientationImage;

EDIT:

UIImage *initialImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *data = UIImagePNGRepresentation(self.initialImage);

initialImage = [UIImage imageWithCGImage:[UIImage imageWithData:data].CGImage
                                                     scale:initialImage.scale
                                               orientation:self.initialImage.imageOrientation];

How can I change image tintColor in iOS and WatchKit

For swift 3 purposes

theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red

Loading/Downloading image from URL on Swift

The only things there is missing is a !

let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData!)

How to zoom in/out an UIImage object when user pinches screen?

The simplest way to do this, if all you want is pinch zooming, is to place your image inside a UIWebView (write small amount of html wrapper code, reference your image, and you're basically done). The more complcated way to do this is to use touchesBegan, touchesMoved, and touchesEnded to keep track of the user's fingers, and adjust your view's transform property appropriately.

Navigation bar with UIImage for title

Objective-C version:

//create the space for the image
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 256, 144)];
//bind the image with the ImageView allocated
myImage.image = [UIImage imageNamed:@"logo.png"];
//add image into imageview
_myNavigationItem.titleView = myImage;

Just in case someone (like me) had arrived here looking for the answer in Objective-C.

How to set image for bar button with swift?

If your UIBarButtonItem is already allocated like in a storyboard. (printBtn)

    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
    btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
    printBtn.customView = btn

iOS - UIImageView - how to handle UIImage image orientation

You can completely avoid manually doing the transforms and scaling yourself, as suggested by an0 in this answer here:

- (UIImage *)normalizedImage {
    if (self.imageOrientation == UIImageOrientationUp) return self; 

    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

The documentation for the UIImage methods size and drawInRect explicitly states that they take into account orientation.

How to capture UIView to UIImage without loss of quality on retina display

Some times drawRect Method makes problem so I got these answers more appropriate. You too may have a look on it Capture UIImage of UIView stuck in DrawRect method

UIImageView - How to get the file name of the image assigned?

Or you can use the restoration identifier, like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

How to animate the change of image in an UIImageView?

In the words of Michael Scott, keep it simple stupid. Here is a simple way to do this in Swift 3 and Swift 4:

UIView.transition(with: imageView,
                  duration: 0.75,
                  options: .transitionCrossDissolve,
                  animations: { self.imageView.image = toImage },
                  completion: nil)

How can I get the height and width of an uiimage?

    import func AVFoundation.AVMakeRect

    let imageRect = AVMakeRect(aspectRatio: self.image!.size, insideRect: self.bounds)

    x = imageRect.minX

    y = imageRect.minY

Can I load a UIImage from a URL?

And the swift version :

   let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
    var err: NSError?
    var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    var bgImage = UIImage(data:imageData)

Search File And Find Exact Match And Print Line?

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

Export table data from one SQL Server to another

Try using the SQL Server Import and Export Wizard (under Tasks -> Export Data).

It offers to create the tables in the destination database. Whereas, as you've seen, the scripting wizard can only create the table structure.

iPhone and WireShark

I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.

  1. In Fiddler, Tools -> Fiddler Options -> Connections -> [x] Allow remote computers to connect.
  2. Make sure your windows firewall is disabled.
  3. On the iphone/ipod, go to your wireless settings, use a manual proxy server, enter the fiddler machine's ip address and the same port (defaults to 8888).

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

Laravel Checking If a Record Exists

Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.

if ( User::find( $userId ) === null ) {

    return "user does not exist";
}
else {
    $user = User::find( $userId );

    return $user;
}

It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

Calculate a MD5 hash from a string

You can use Convert.ToBase64String to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw== for your example)

Split array into chunks

Hi try this -

 function split(arr, howMany) {
        var newArr = []; start = 0; end = howMany;
        for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
            newArr.push(arr.slice(start, end));
            start = start + howMany;
            end = end + howMany
        }
        console.log(newArr)
    }
    split([1,2,3,4,55,6,7,8,8,9],3)

URL encoding in Android

You don't encode the entire URL, only parts of it that come from "unreliable sources".

  • Java:

    String query = URLEncoder.encode("apples oranges", "utf-8");
    String url = "http://stackoverflow.com/search?q=" + query;
    
  • Kotlin:

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

Count unique values using pandas groupby

This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:

df.groupby(['group']).agg(['min','max','count','nunique'])

Hope you find it useful

how to load url into div tag

Try the load() function.

$('#content').load("http://vnexpress.net");

Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:

Access-Control-Allow-Origin:*

to allow requests from everywhere.

What is a "callback" in C and how are they implemented?

A callback in C is a function that is provided to another function to "call back to" at some point when the other function is doing its task.

There are two ways that a callback is used: synchronous callback and asynchronous callback. A synchronous callback is provided to another function which is going to do some task and then return to the caller with the task completed. An asynchronous callback is provided to another function which is going to start a task and then return to the caller with the task possibly not completed.

A synchronous callback is typically used to provide a delegate to another function to which the other function delegates some step of the task. Classic examples of this delegation are the functions bsearch() and qsort() from the C Standard Library. Both of these functions take a callback which is used during the task the function is providing so that the type of the data being searched, in the case of bsearch(), or sorted, in the case of qsort(), does not need to be known by the function being used.

For instance here is a small sample program with bsearch() using different comparison functions, synchronous callbacks. By allowing us to delegate the data comparison to a callback function, the bsearch() function allows us to decide at run time what kind of comparison we want to use. This is synchronous because when the bsearch() function returns the task is complete.

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

typedef struct {
    int iValue;
    int kValue;
    char label[6];
} MyData;

int cmpMyData_iValue (MyData *item1, MyData *item2)
{
    if (item1->iValue < item2->iValue) return -1;
    if (item1->iValue > item2->iValue) return 1;
    return 0;
}

int cmpMyData_kValue (MyData *item1, MyData *item2)
{
    if (item1->kValue < item2->kValue) return -1;
    if (item1->kValue > item2->kValue) return 1;
    return 0;
}

int cmpMyData_label (MyData *item1, MyData *item2)
{
    return strcmp (item1->label, item2->label);
}

void bsearch_results (MyData *srch, MyData *found)
{
        if (found) {
            printf ("found - iValue = %d, kValue = %d, label = %s\n", found->iValue, found->kValue, found->label);
        } else {
            printf ("item not found, iValue = %d, kValue = %d, label = %s\n", srch->iValue, srch->kValue, srch->label);
        }
}

int main ()
{
    MyData dataList[256] = {0};

    {
        int i;
        for (i = 0; i < 20; i++) {
            dataList[i].iValue = i + 100;
            dataList[i].kValue = i + 1000;
            sprintf (dataList[i].label, "%2.2d", i + 10);
        }
    }

//  ... some code then we do a search
    {
        MyData srchItem = { 105, 1018, "13"};
        MyData *foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );

        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );
        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );
        bsearch_results (&srchItem, foundItem);
    }
}

An asynchronous callback is different in that when the called function to which we provide a callback returns, the task may not be completed. This type of callback is often used with asynchronous I/O in which an I/O operation is started and then when it is completed, the callback is invoked.

In the following program we create a socket to listen for TCP connection requests and when a request is received, the function doing the listening then invokes the callback function provided. This simple application can be exercised by running it in one window while using the telnet utility or a web browser to attempt to connect in another window.

I lifted most of the WinSock code from the example Microsoft provides with the accept() function at https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx

This application starts a listen() on the local host, 127.0.0.1, using port 8282 so you could use either telnet 127.0.0.1 8282 or http://127.0.0.1:8282/.

This sample application was created as a console application with Visual Studio 2017 Community Edition and it is using the Microsoft WinSock version of sockets. For a Linux application the WinSock functions would need to be replaced with the Linux alternatives and the Windows threads library would use pthreads instead.

#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>
#include <string.h>

#include <Windows.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

// function for the thread we are going to start up with _beginthreadex().
// this function/thread will create a listen server waiting for a TCP
// connection request to come into the designated port.
// _stdcall modifier required by _beginthreadex().
int _stdcall ioThread(void (*pOutput)())
{
    //----------------------
    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error: %ld\n", iResult);
        return 1;
    }
    //----------------------
    // Create a SOCKET for listening for
    // incoming connection requests.
    SOCKET ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    struct sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(8282);

    if (bind(ListenSocket, (SOCKADDR *)& service, sizeof(service)) == SOCKET_ERROR) {
        printf("bind failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Listen for incoming connection requests.
    // on the created socket
    if (listen(ListenSocket, 1) == SOCKET_ERROR) {
        printf("listen failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Create a SOCKET for accepting incoming requests.
    SOCKET AcceptSocket;
    printf("Waiting for client to connect...\n");

    //----------------------
    // Accept the connection.
    AcceptSocket = accept(ListenSocket, NULL, NULL);
    if (AcceptSocket == INVALID_SOCKET) {
        printf("accept failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    else
        pOutput ();   // we have a connection request so do the callback

    // No longer need server socket
    closesocket(ListenSocket);

    WSACleanup();
    return 0;
}

// our callback which is invoked whenever a connection is made.
void printOut(void)
{
    printf("connection received.\n");
}

#include <process.h>

int main()
{
     // start up our listen server and provide a callback
    _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);
    // do other things while waiting for a connection. In this case
    // just sleep for a while.
    Sleep(30000);
}

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

how to get yesterday's date in C#

The code you posted is wrong.

You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".

Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.

string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");

Angular 2.0 router not working on reloading the browser

You can use location strategy, Add useHash: true in routing file.

imports: [RouterModule.forRoot(routes, { useHash: true })]

How to make git mark a deleted and a new file as a file move?

For me it worked to stash save all the changes before the commit and pop them out again. This made git re-analyze the added / deleted files and it correctly marked them as moved.

Vue template or render function not defined yet I am using neither?

I am using Typescript with vue-property-decorator and what happened to me is that my IDE auto-completed "MyComponent.vue.js" instead of "MyComponent.vue". That got me this error.

It seems like the moral of the story is that if you get this error and you are using any kind of single-file component setup, check your imports in the router.

Speed tradeoff of Java's -Xms and -Xmx options

It is difficult to say how the memory allocation will affect your speed. It depends on the garbage collection algorithm the JVM is using. For example if your garbage collector needs to pause to do a full collection, then if you have 10 more memory than you really need then the collector will have 10 more garbage to clean up.

If you are using java 6 you can use the jconsole (in the bin directory of the jdk) to attach to your process and watch how the collector is behaving. In general the collectors are very smart and you won't need to do any tuning, but if you have a need there are numerous options you have use to further tune the collection process.

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast has runtime type checking and only works with references and pointers, whereas static_cast does not offer runtime type checking. For complete information, see the MSDN article static_cast Operator.

How to remove "index.php" in codeigniter's path

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /codeigniter/index.php/$0 [PT,L]

after changing RewriteRule .* index.php/$0 [PT,L] with the project folder name "codeigniter".its working for me. Thanks guys for your support.

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had the same in IIS 10.

I fixed it by importing the .pfx file using IIS manager.

Select server root (above the sites-node), click 'Server Certificates' in the right hand pane and import pfx there. Then I could select it from the dropdown when creating ssl binding for a website under sites

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

How to include multiple js files using jQuery $.getScript() method

Great answer, adeneo.

It took me a little while to figure out how to make your answer more generic (so that I could load an array of code-defined scripts). Callback gets called when all scripts have loaded and executed. Here is my solution:

    function loadMultipleScripts(scripts, callback){
        var array = [];

        scripts.forEach(function(script){
            array.push($.getScript( script ))
        });

        array.push($.Deferred(function( deferred ){
                    $( deferred.resolve );
                }));

        $.when.apply($, array).done(function(){
                if (callback){
                    callback();
                }
            });
    }

Convert UTC date time to local date time

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".

In angular, (following Hulvej) make a localdate filter:

myFilters.filter('localdate', function () {
    return function(input) {
        var date = new Date(input + '.000Z');
        return date;
    };
})

Then, display local time like:

{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

Using Chrome, how to find to which events are bound to an element

findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js

Steps

  1. Paste the raw code directely into chrome's console(note:must have jquery loaded already)

  2. Use the following function call: findEventHandlers(eventType, selector);
    to find the corresponding's selector specified element's eventType handler.

Example:

findEventHandlers("click", "#clickThis");

Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition

See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/

Array or List in Java. Which is faster?

Don't get into the trap of optimizing without proper benchmarking. As others have suggested use a profiler before making any assumption.

The different data structures that you have enumerated have different purposes. A list is very efficient at inserting elements in the beginning and at the end but suffers a lot when accessing random elements. An array has fixed storage but provides fast random access. Finally an ArrayList improves the interface to an array by allowing it to grow. Normally the data structure to be used should be dictated by how the data stored will be access or added.

About memory consumption. You seem to be mixing some things. An array will only give you a continuous chunk of memory for the type of data that you have. Don't forget that java has a fixed data types: boolean, char, int, long, float and Object (this include all objects, even an array is an Object). It means that if you declare an array of String strings [1000] or MyObject myObjects [1000] you only get a 1000 memory boxes big enough to store the location (references or pointers) of the objects. You don't get a 1000 memory boxes big enough to fit the size of the objects. Don't forget that your objects are first created with "new". This is when the memory allocation is done and later a reference (their memory address) is stored in the array. The object doesn't get copied into the array only it's reference.

Connection refused to MongoDB errno 111

For Ubuntu Server 15.04 and 16.04 you need execute only this command

sudo apt-get install --reinstall mongodb

How to get the error message from the error code returned by GetLastError()?

In general, you need to use FormatMessage to convert from a Win32 error code to text.

From the MSDN documentation:

Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

The declaration of FormatMessage:

DWORD WINAPI FormatMessage(
  __in      DWORD dwFlags,
  __in_opt  LPCVOID lpSource,
  __in      DWORD dwMessageId, // your error code
  __in      DWORD dwLanguageId,
  __out     LPTSTR lpBuffer,
  __in      DWORD nSize,
  __in_opt  va_list *Arguments
);

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

PHP cURL HTTP PUT

Using Postman for Chrome, selecting CODE you get this... And works

_x000D_
_x000D_
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
  CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
  CURLOPT_RETURNTRANSFER => true,_x000D_
  CURLOPT_ENCODING => "",_x000D_
  CURLOPT_MAXREDIRS => 10,_x000D_
  CURLOPT_TIMEOUT => 30,_x000D_
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
  CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"[email protected]\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
  CURLOPT_HTTPHEADER => array(_x000D_
    "cache-control: no-cache",_x000D_
    "content-type: application/json",_x000D_
    "x-api-key: whateveriyouneedinyourheader"_x000D_
  ),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
  echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
  echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

How do I reference a local image in React?

const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

Passing by reference in C

Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.

How to change the port number for Asp.Net core app?

in your hosting.json replace"Url": "http://localhost:80" by"Url": "http://*:80" and you will be able now access to your application by http://your_local_machine_ip:80 for example http://192.168.1.4:80

Calling Python in Java?

Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:

Convert datetime object to a String of date only in Python

If you looking for a simple way of datetime to string conversion and can omit the format. You can convert datetime object to str and then use array slicing.

In [1]: from datetime import datetime

In [2]: now = datetime.now()

In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'

In [5]: str(now)[:10]
Out[5]: '2019-04-26'

In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'

But note the following thing. If other solutions will rise an AttributeError when the variable is None in this case you will receive a 'None' string.

In [9]: str(None)[:19]
Out[9]: 'None'

How to add a TextView to a LinearLayout dynamically in Android?

I customized more @Suragch code. My output looks

enter image description here

I wrote a method to stop code redundancy.

public TextView createATextView(int layout_widh, int layout_height, int align,
        String text, int fontSize, int margin, int padding) {

    TextView textView_item_name = new TextView(this);

    // LayoutParams layoutParams = new LayoutParams(
    // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    // layoutParams.gravity = Gravity.LEFT;
    RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
            layout_widh, layout_height);

    _params.setMargins(margin, margin, margin, margin);
    _params.addRule(align);
    textView_item_name.setLayoutParams(_params);

    textView_item_name.setText(text);
    textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
    textView_item_name.setTextColor(Color.parseColor("#000000"));
    // textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView_item_name.setPadding(padding, padding, padding, padding);

    return textView_item_name;

}

It can be called like

createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20);

Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.

    RelativeLayout primary_layout = new RelativeLayout(this);

    LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);

    primary_layout.setLayoutParams(layoutParam);

    // FOR LINEAR LAYOUT SET ORIENTATION
    // primary_layout.setOrientation(LinearLayout.HORIZONTAL);

    // FOR BACKGROUND COLOR 
    primary_layout.setBackgroundColor(0xff99ccff);

    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
            20, 10, 20));
    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20));

How to generate access token using refresh token through google drive API?

It's an old question but seems to me it wasn't completely answered, and I needed this information too so I'll post my answer.

If you want to use the Google Api Client Library, then you just need to have an access token that includes the refresh token in it, and then - even though the access token will expire after an hour - the library will refresh the token for you automatically.

In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline");) and you will get it. Just keep in mind you will get the access token with the refresh token only in the first authorization, so make sure to save that access token in the first time, and you will be able to use it anytime.

Hope that helps anyone :-)

Initialization of an ArrayList in one line

Try with this code line:

Collections.singletonList(provider)

App not setup: This app is still in development mode

make sure your app is live on developer.facebook.com

This green circle is indicating the app is live enter image description here

If it is not then follow this two steps for make your app live

Step 1 Go to your application -> setting => and add Contact Email and apply save Changes

Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot

enter image description here

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check:

Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect.

You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in Control Panel > ODBC Drivers > New

Query Mongodb on month, day, year... of a datetime

If you want to search for documents that belong to a specific month, make sure to query like this:

// Anything greater than this month and less than the next month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 7, 1)}});

Avoid quering like below as much as possible.

// This may not find document with date as the last date of the month
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lt: new Date(2015, 6, 30)}});

// don't do this too
db.posts.find({created_on: {$gte: new Date(2015, 6, 1), $lte: new Date(2015, 6, 30)}});

Subtract 1 day with PHP

Not sure why your current code isn't working but if you don't specifically need a date object this will work:

$first_date = strtotime($date_raw);
$second_date = strtotime('-1 day', $first_date);

print 'First Date ' . date('Y-m-d', $first_date);
print 'Next Date ' . date('Y-m-d', $second_date);

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

How to use sed to extract substring

You want awk.

This would be a quick and dirty hack:

awk -F "\"" '{print $2}' /tmp/file.txt

PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription

Bootstrap table without stripe / borders

In some cases, one must also use border-spacing in the table class, like:

border-spacing: 0 !important;

How to use a Bootstrap 3 glyphicon in an html select

I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
        Select icon <span class="caret"></span>
    </button>
    <ul class="dropdown-menu list-inline" role="menu">
        <li><span class="glyphicon glyphicon-cutlery"></span></li>
        <li><span class="glyphicon glyphicon-fire"></span></li>
        <li><span class="glyphicon glyphicon-glass"></span></li>
        <li><span class="glyphicon glyphicon-heart"></span></li>          
    </ul>
</div>

I'm using Angular.js so this is the actual code I used:

<div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                Avatar <span class="caret"></span>
            </button>
            <ul class="dropdown-menu list-inline" role="menu">
                <li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
                    <span ng-class="getAvatar(avatar)"></span>
                </li>
            </ul>
        </div>

And in my controller:

$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];

$scope.getAvatar=function(avatar){
     return 'glyphicon glyphicon-'+avatar;
};

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined Ă— 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined Ă— 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

Retrieve Button value with jQuery

Give the buttons a value attribute and then retrieve the values using this:

$("button").click(function(){
  var value=$(this).attr("value");
});

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

OSX - How to auto Close Terminal window after the "exit" command executed.

I tried several variations of the answers here. No matter what I try, I can always find a use case where the user is prompted to close Terminal.

Since my script is a simple (drutil -drive 2 tray open -- to open a specific DVD drive), the user does not need to see the Terminal window while the script runs.

My solution was to turn the script into an app, which runs the script without displaying a Terminal window. The added benefit is that any terminal windows that are already open stay open, and if none are open, then Terminal doesn't stay resident after the script ends. It doesn't seem to launch Terminal at all to run the bash script.

I followed these instructions to turn my script into an app: https://superuser.com/a/1354541/162011

How to set 24-hours format for date on java?

This will give you the date in 24 hour format.

    Date date = new Date();
    date.setHours(date.getHours() + 8);
    System.out.println(date);
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.format(date));

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

How to redirect output to a file and stdout

Bonus answer since this use-case brought me here:

In the case where you need to do this as some other user

echo "some output" | sudo -u some_user tee /some/path/some_file

Note that the echo will happen as you and the file write will happen as "some_user" what will NOT work is if you were to run the echo as "some_user" and redirect the output with >> "some_file" because the file redirect will happen as you.

Hint: tee also supports append with the -a flag, if you need to replace a line in a file as another user you could execute sed as the desired user.

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

Eclipse Java Missing required source folder: 'src'

I think it's because of the .classpath getting saved with the deleted source folder configuration.

  1. Create the missing folder [ 'src' in your case] manually inside the root of the project. When I say manually, I meant outside Eclipse, using the file explorer.

  2. Then, come back to eclipse and refresh the project. Now, the error saying it's already there will be gone.

  3. Now, Right click on the project > Build Path > Configure Build path. It should take us to the Java build path side menu.

  4. Make sure we are on the 'Source' tab. Delete the source folder causing the problem. Now, maybe the folder might show up in the project structure and you may delete that too.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

How to draw vertical lines on a given plot in matplotlib

In addition to the plt.axvline and plt.plot((x1, x2), (y1, y2)) OR plt.plot([x1, x2], [y1, y2]) as provided in the answers above, one can also use

plt.vlines(x_pos, ymin=y1, ymax=y2)

to plot a vertical line at x_pos spanning from y1 to y2 where the values y1 and y2 are in absolute data coordinates.

Batch Extract path and filename from a variable

All of this works for me:

@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul

Output:

Directory = D:\Users\Thejordster135\Desktop\Code\BAT\

Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"

Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat

Bat File Drive = D:

Full File Name = Path.bat

File Name Without Extension = Path

File Extension = .bat

how to implement a pop up dialog box in iOS

Updated for iOS 8.0

Since iOS 8.0, you will need to use UIAlertController as the following:

-(void)alertMessage:(NSString*)message
{
    UIAlertController* alert = [UIAlertController
          alertControllerWithTitle:@"Alert"
          message:message
          preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction 
          actionWithTitle:@"OK" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.

David

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

&& (AND) and || (OR) in IF statements

All the answers here are great but, just to illustrate where this comes from, for questions like this it's good to go to the source: the Java Language Specification.

Section 15:23, Conditional-And operator (&&), says:

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. [...] At run time, the left-hand operand expression is evaluated first [...] if the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated [...] the resulting value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

And similarly, Section 15:24, Conditional-Or operator (||), says:

The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. [...] At run time, the left-hand operand expression is evaluated first; [...] if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; [...] the resulting value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

A little repetitive, maybe, but the best confirmation of exactly how they work. Similarly the conditional operator (?:) only evaluates the appropriate 'half' (left half if the value is true, right half if it's false), allowing the use of expressions like:

int x = (y == null) ? 0 : y.getFoo();

without a NullPointerException.

Why use 'git rm' to remove a file instead of 'rm'?

Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory.

Here's how you might delete a file using rm -f and then remove it from your index with git rm

$ rm -f index.html
$ git status -s
 D index.html
$ git rm index.html
rm 'index.html'
$ git status -s
D  index.html

However you can do this all in one go with just git rm

$ git status -s
$ git rm index.html
rm 'index.html'
$ ls
lib vendor
$ git status -s
D  index.html

Regular expression for not allowing spaces in the input field

This will help to find the spaces in the beginning, middle and ending:

var regexp = /\s/g

SFTP in Python? (platform independent)

You can use the pexpect module

Here is a good intro post

child = pexpect.spawn ('/usr/bin/sftp ' + [email protected] )
child.expect ('.* password:')
child.sendline (your_password)
child.expect ('sftp> ')
child.sendline ('dir')
child.expect ('sftp> ')
file_list = child.before
child.sendline ('bye')

I haven't tested this but it should work

How do I cancel a build that is in progress in Visual Studio?

Ctrl + Break works, but only if the Build window is active. Also, interrupting the build will sometimes leave a corrupted .obj file that will have to be manually deleted in order for the build to proceed.

Only variable references should be returned by reference - Codeigniter

It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....

I make a solution for this problem. In your ckeditor_helper.php file line- 65

if($k !== end (array_keys($data['config']))) {
       $return .= ",";
}

Change this to-->

 $segment = array_keys($data['config']);
    if($k !== end($segment)) {
           $return .= ",";
    }

I think this is the best solution and then your problem notice will dissappear.

Change selected value of kendo ui dropdownlist

Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.

Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.

To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.

@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
    .Name("Status.StatusId")
    .DataTextField("StatusName")
    .DataValueField("StatusId")
    .BindTo(...)
)

//So that your ViewModel gets bound properly on the post, naming is a bit 
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');    

ddl.select(function(dataItem) {
    return dataItem.StatusName === "Active";
});

How to concat a string to xsl:value-of select="...?

Easiest method is

  <TD>
    <xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
  </TD>

when the XML Structure is

<title>The Confidence Man</title>
<author>
  <first-name>Herman</first-name>
  <last-name>Melville</last-name>
</author>
<price>11.99</price>

How to send a simple email from a Windows batch file?

Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:

Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "[email protected]"
objMail.To = "[email protected]"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing

Facebook Graph API error code list

I was looking for the same thing and I just found this list

https://developers.facebook.com/docs/reference/api/errors/

How to change value of ArrayList element in java

I think the problem is that you think the statement ...

x = Integer.valueOf(9);

... causes that the value of '9' get 'stored' into(!) the Object on which x is referencing.

But thats wrong.

Instead the statement causes something similar as if you would call

x = new Integer(9); 

If you have a look to the java source code, you will see what happens in Detail.

Here is the code of the "valueOf(int i)" method in the "Integer" class:

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

and further, whenever the IntegerCache class is used for the first time the following script gets invoked:

static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

You see that either a new Integer Object is created with "new Integer(i)" in the valueOf method ... ... or a reference to a Integer Object which is stored in the IntegerCache is returned.

In both cases x will reference to a new Object.

And this is why the reference to the Object in your list get lost when you call ...

x = Integer.valueOf(9);

Instead of doing so, in combination with a ListIterator use ...

i.set(Integer.valueOf(9));

... after you got the element you want to change with ...

i.next();

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

Laravel Fluent Query Builder Join with subquery

I think what you looking for is "joinSub". It's supported from laravel ^5.6. If you using laravel version below 5.6 you can also register it as macro in your app service provider file. like this https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/171#issuecomment-413062522

$subquery = DB::table('catch-text')
            ->select(DB::raw("user_id,MAX(created_at) as MaxDate"))
            ->groupBy('user_id');

$query = User::joinSub($subquery,'MaxDates',function($join){
          $join->on('users.id','=','MaxDates.user_id');
})->select(['users.*','MaxDates.*']);

convert epoch time to date

Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date, DateFormat and SimpleDateFormat classes. It all goes more natural with the modern Java date and time API.

To get a date-time object from your millis:

    ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
            .atZone(ZoneId.of("Australia/Sydney"));

If millis equals 1318388699000L, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.

If you want the date-time in your string format for presentation:

String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));

Result:

12/10/2011 14:04:59

PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59.

Command line tool to dump Windows DLL version?

Use Microsoft Sysinternals Sigcheck. This sample outputs just the version:

sigcheck -q -n foo.dll

Unpacked sigcheck.exe is only 228 KB.

How can I transition height: 0; to height: auto; using CSS?

Here's a solution I just used in combination with jQuery. This works for the following HTML structure:

<nav id="main-nav">
    <ul>
        <li>
            <a class="main-link" href="yourlink.html">Link</a>
            <ul>
                <li><a href="yourlink.html">Sub Link</a></li>
            </ul>
        </li>
    </ul>
</nav>

and the function:

    $('#main-nav li ul').each(function(){
        $me = $(this);

        //Count the number of li elements in this UL
        var liCount = $me.find('li').size(),
        //Multiply the liCount by the height + the margin on each li
            ulHeight = liCount * 28;

        //Store height in the data-height attribute in the UL
        $me.attr("data-height", ulHeight);
    });

You could then use a click function to set and remove the height using css()

$('#main-nav li a.main-link').click(function(){
    //Collapse all submenus back to 0
    $('#main-nav li ul').removeAttr('style');

    $(this).parent().addClass('current');

    //Set height on current submenu to it's height
    var $currentUl = $('li.current ul'),
        currentUlHeight = $currentUl.attr('data-height');
})

CSS:

#main-nav li ul { 
    height: 0;
    position: relative;
    overflow: hidden;
    opacity: 0; 
    filter: alpha(opacity=0); 
    -ms-filter: "alpha(opacity=0)";
    -khtml-opacity: 0; 
    -moz-opacity: 0;
    -webkit-transition: all .6s ease-in-out;
    -moz-transition: all .6s ease-in-out;
    -o-transition: all .6s ease-in-out;
    -ms-transition: all .6s ease-in-out;
    transition: all .6s ease-in-out;
}

#main-nav li.current ul {
    opacity: 1.0; 
    filter: alpha(opacity=100); 
    -ms-filter: "alpha(opacity=100)";
    -khtml-opacity: 1.0; 
    -moz-opacity: 1.0;
}

.ie #main-nav li.current ul { height: auto !important }

#main-nav li { height: 25px; display: block; margin-bottom: 3px }

Carriage return and Line feed... Are both required in C#?

It's always a good idea, and while it's not always required, the Windows standard is to include both.

\n actually represents a Line Feed, or the number 10, and canonically a Line Feed means just "move down one row" on terminals and teletypes.

\r represents CR, a Carriage Return, or the number 13. On Windows, Unix, and most terminals, a CR moves the cursor to the beginning of the line. (This is not the case for 8-bit computers: most of those do advance to the next line with a CR.)

Anyway, some processes, such as the text console, might add a CR automatically when you send an LF. However, since the CR simply moves to the start of the line, there's no harm in sending the CR twice.

On the other hand, dialog boxes, text boxes, and other display elements require both CR and LF to properly start a new line.

Since there's really no downside to sending both, and both are required in some situations, the simplest policy is to use both, if you're not sure.

Add URL link in CSS Background Image?

Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:

<div class="wrapWithBackgroundImage">
    <a href="#" class="invisibleLink"></a>
</div>

.wrapWithBackgroundImage {
    background-image: url(...);
}
.invisibleLink {
    display: block;
    left: 55px; top: 55px;
    position: absolute;
    height: 55px width: 55px;
}

How to load external webpage in WebView

Please use this code:-

Main.Xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/background">
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:background="@drawable/top_heading"
        android:id="@+id/rlayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_centerVertical="true" android:layout_centerHorizontal="true"
            android:textColor="#ffffff" android:textSize="22dip"
            android:textStyle="bold" android:layout_height="wrap_content"
            android:text="More Information" android:id="@+id/txtviewfbdisplaytitle" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_below="@+id/rlayout1"
        android:id="@+id/rlayout2">
        <WebView android:id="@+id/webview1" android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0" />
    </RelativeLayout>
</RelativeLayout>

MainActivity.Java

public class MainActivity extends Activity {
    private class MyWebViewClient extends WebViewClient {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
              view.loadUrl(url);
              return true;
          }
    }
    Button btnBack;
    WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webview=(WebView)findViewById(R.id.webview1);
        webview.setWebViewClient(new MyWebViewClient());
        openURL();
    }

     /** Opens the URL in a browser */
    private void openURL() {
        webview.loadUrl("http://www.google.com");
        webview.requestFocus();
    }
}

Try this code if any query ask me.

onChange and onSelect in DropDownList

hmm. why don't you use onClick()

<select id="mySelect" onChange="enable();">
   <option onClick="disable();">No</option>
   <option onClick="enable();">Yes</option>
</select>

How to get folder directory from HTML input type "file" or any other way?

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:

https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

How to change the time format (12/24 hours) of an <input>?

It depends on the time format of the user's operating system when the web browser was launched.

So:

  • If your computer's system prefs are set to use a 24-hour clock, the browser will render the <input type="time"> element as --:-- (time range: 00:00–23:59).
  • If you change your computer's syst prefs to use 12-hour, the output won't change until you quit and relaunch the browser. Then it will change to --:-- -- (time range: 12:00 AM – 11:59 PM).

And (as of this writing), browser support is only about 75% (caniuse). Yay: Edge, Chrome, Opera, Android. Boo: IE, Firefox, Safari).

Direct download from Google Drive using Google Drive API

I simply create a javascript so that it automatically capture the link and download and close the tab with the help of tampermonkey.

// ==UserScript==
// @name         Bypass Google drive virus scan
// @namespace    SmartManoj
// @version      0.1
// @description  Quickly get the download link
// @author       SmartManoj
// @match        https://drive.google.com/uc?id=*&export=download*
// @grant        none
// ==/UserScript==

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function demo() {
        await sleep(5000);
        window.close();
    }

    (function() {
        location.replace(document.getElementById("uc-download-link").href);
        demo();
    })();

Similarly you can get the html source of the url and download in java.

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

Is object empty?

I'm assuming that by empty you mean "has no properties of its own".

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

function isEmpty(obj) {

    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // If it isn't an object at this point
    // it is empty, but it can't be anything *but* empty
    // Is it empty?  Depends on your application.
    if (typeof obj !== "object") return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

Examples:

isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true

isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false

If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames instead of the hasOwnProperty loop:

if (Object.getOwnPropertyNames(obj).length > 0) return false;

This will ensure that even if the object only has non-enumerable properties isEmpty will still give you the correct results.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Allow anonymous authentication for a single folder in web.config?

I added web.config to the specific folder say "Users" (VS 2015, C#) and the added following code

<?xml version="1.0"?>
 <configuration>
  <system.web>
    <authorization>     
    <deny users="?"/>
  </authorization>
</system.web>
</configuration>

Initially i used location tag but that didn't worked.

How do I make a semi transparent background?

Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.

My solution works for background images or color backgrounds.

_x000D_
_x000D_
#parent {_x000D_
    font-family: 'Open Sans Condensed', sans-serif;_x000D_
    font-size: 19px;_x000D_
    text-transform: uppercase;_x000D_
    border-radius: 50%;_x000D_
    margin: 20px auto;_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    background-color: #476172;_x000D_
    background-image: url('https://unsplash.it/200/300/?random');_x000D_
    line-height: 29px;_x000D_
    text-align:center;_x000D_
}_x000D_
_x000D_
#content {_x000D_
    color: white;_x000D_
    height: 125px !important;_x000D_
    width: 125px !important;_x000D_
    display: table-cell;_x000D_
    border-radius: 50%;_x000D_
    vertical-align: middle;_x000D_
    background: rgba(0,0,0, .3);_x000D_
}
_x000D_
<h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
_x000D_
_x000D_
_x000D_

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Try

$sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user={$rows['user']} ";

You need curly brackets for array access in double quoted strings.

In Perl, how can I read an entire file into a string?

This is more of a suggestion on how NOT to do it. I've just had a bad time finding a bug in a rather big Perl application. Most of the modules had its own configuration files. To read the configuration files as-a-whole, I found this single line of Perl somewhere on the Internet:

# Bad! Don't do that!
my $content = do{local(@ARGV,$/)=$filename;<>};

It reassigns the line separator as explained before. But it also reassigns the STDIN.

This had at least one side effect that cost me hours to find: It does not close the implicit file handle properly (since it does not call closeat all).

For example, doing that:

use strict;
use warnings;

my $filename = 'some-file.txt';

my $content = do{local(@ARGV,$/)=$filename;<>};
my $content2 = do{local(@ARGV,$/)=$filename;<>};
my $content3 = do{local(@ARGV,$/)=$filename;<>};

print "After reading a file 3 times redirecting to STDIN: $.\n";

open (FILE, "<", $filename) or die $!;

print "After opening a file using dedicated file handle: $.\n";

while (<FILE>) {
    print "read line: $.\n";
}

print "before close: $.\n";
close FILE;
print "after close: $.\n";

results in:

After reading a file 3 times redirecting to STDIN: 3
After opening a file using dedicated file handle: 3
read line: 1
read line: 2
(...)
read line: 46
before close: 46
after close: 0

The strange thing is, that the line counter $. is increased for every file by one. It's not reset, and it does not contain the number of lines. And it is not reset to zero when opening another file until at least one line is read. In my case, I was doing something like this:

while($. < $skipLines) {<FILE>};

Because of this problem, the condition was false because the line counter was not reset properly. I don't know if this is a bug or simply wrong code... Also calling close; oder close STDIN; does not help.

I replaced this unreadable code by using open, string concatenation and close. However, the solution posted by Brad Gilbert also works since it uses an explicit file handle instead.

The three lines at the beginning can be replaced by:

my $content = do{local $/; open(my $f1, '<', $filename) or die $!; my $tmp1 = <$f1>; close $f1 or die $!; $tmp1};
my $content2 = do{local $/; open(my $f2, '<', $filename) or die $!; my $tmp2 = <$f2>; close $f2 or die $!; $tmp2};
my $content3 = do{local $/; open(my $f3, '<', $filename) or die $!; my $tmp3 = <$f3>; close $f3 or die $!; $tmp3};

which properly closes the file handle.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

semaphore implementation

The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:

  • POSIX IPC API, which is a standard API
  • System V API, which is coming from the old Unix world, but practically available almost all Unix systems

Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.

To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.

These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:

  • it builds on semaphore sets, so once you created an object with semget() that is a set of semaphores rather then a single one
  • the System V API allows you to do atomic operations on these sets. so you can modify or wait for multiple semaphores in a set
  • the SysV API allows you to wait for a semaphore to reach a threshold rather than only being non-zero. waiting for a non-zero threshold is also supported, but my previous sentence implies that
  • the semaphore resources are pretty limited on every unixes. you can check these with the 'ipcs' command
  • there is an undo feature of the System V semaphores, so you can make sure that abnormal program termination doesn't leave your semaphores in an undesired state

mongodb count num of distinct values per field/key

With MongoDb 3.4.4 and newer, you can leverage the use of $arrayToObject operator and a $replaceRoot pipeline to get the counts.

For example, suppose you have a collection of users with different roles and you would like to calculate the distinct counts of the roles. You would need to run the following aggregate pipeline:

db.users.aggregate([
    { "$group": {
        "_id": { "$toLower": "$role" },
        "count": { "$sum": 1 }
    } },
    { "$group": {
        "_id": null,
        "counts": {
            "$push": { "k": "$_id", "v": "$count" }
        }
    } },
    { "$replaceRoot": {
        "newRoot": { "$arrayToObject": "$counts" }
    } }    
])

Example Output

{
    "user" : 67,
    "superuser" : 5,
    "admin" : 4,
    "moderator" : 12
}

iPhone: How to get current milliseconds?

In Swift we can make a function and do as follows

func getCurrentMillis()->Int64{
    return  Int64(NSDate().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

Though its working fine in Swift 3.0 but we can modify and use the Date class instead of NSDate in 3.0

Swift 3.0

func getCurrentMillis()->Int64 {
    return Int64(Date().timeIntervalSince1970 * 1000)
}

var currentTime = getCurrentMillis()

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

you can simply use JSON.stringify(options) convert JSON object to string before submit, then warning dismiss and works fine

Android Google Maps v2 - set zoom level for myLocation

Slightly different solution than HeatfanJohn's, where I change the zoom relatively to the current zoom level:

// Zoom out just a little
map.animateCamera(CameraUpdateFactory.zoomTo(map.getCameraPosition().zoom - 0.5f));

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

Shift elements in a numpy array

If you want a one-liner from numpy and aren't too concerned about performance, try:

np.sum(np.diag(the_array,1),0)[:-1]

Explanation: np.diag(the_array,1) creates a matrix with your array one-off the diagonal, np.sum(...,0) sums the matrix column-wise, and ...[:-1] takes the elements that would correspond to the size of the original array. Playing around with the 1 and :-1 as parameters can give you shifts in different directions.

conversion from infix to prefix

Infix to PostFix using Stack:

     Example: Infix-->         P-Q*R^S/T+U *V
     Postfix -->      PQRS^*T/-UV

     Rules:
    Operand ---> Add it to postfix
    "(" ---> Push it on the stack
    ")" ---> Pop and add to postfix all operators till 1st left parenthesis
   Operator ---> Pop and add to postfix those operators that have preceded 
          greater than or equal to the precedence of scanned operator.
          Push the scanned symbol operator on the stack

jQuery: click function exclude children.

I personally would add a click handler to the child element that did nothing but stop the propagation of the click. So it would look something like:

$('.example > div').click(function (e) {
    e.stopPropagation();
});

On Duplicate Key Update same as insert

I know it's late, but i hope someone will be helped of this answer

INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

You can read the tutorial below here :

https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/

http://www.mysqltutorial.org/mysql-insert-or-update-on-duplicate-key-update/

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Pandas groupby: How to get a union of strings

If you'd like to overwrite column B in the dataframe, this should work:

    df = df.groupby('A',as_index=False).agg(lambda x:'\n'.join(x))

Loop through an array php

Using foreach loop without key

foreach($array as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

Using foreach loop with key

foreach($array as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}

Using for loop

for ($i = 0; $i < count($array); $i++) {
    echo $array[$i]['filename'];
    echo $array[$i]['filepath'];
}

var_dump is a really useful function to get a snapshot of an array or object.

How do I limit the number of decimals printed for a double?

Check out DecimalFormat: http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

You'll do something like:

new DecimalFormat("$#.00").format(shippingCost);

Or since you're working with currency, you could see how NumberFormat.getCurrencyInstance() works for you.

Plotting multiple time series on the same plot using ggplot()

If both data frames have the same column names then you should add one data frame inside ggplot() call and also name x and y values inside aes() of ggplot() call. Then add first geom_line() for the first line and add second geom_line() call with data=df2 (where df2 is your second data frame). If you need to have lines in different colors then add color= and name for eahc line inside aes() of each geom_line().

df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))

ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
  geom_line(data=df2,aes(color="Second line"))+
  labs(color="Legend text")

enter image description here

Get keys of a Typescript interface as array of strings

You will need to make a class that implements your interface, instantiate it and then use Object.keys(yourObject) to get the properties.

export class YourClass implements IMyTable {
    ...
}

then

let yourObject:YourClass = new YourClass();
Object.keys(yourObject).forEach((...) => { ... });

Changing the Git remote 'push to' default

Very simply, and cobbling together some of the great comments here along with my own research into this.

First, check out the local branch you want to tie to your remote branch:

git checkout mybranch

Next:

git branch -u origin/mybranch

where:

git branch -u {remote name}/{branch name}

You should get a message:

"Branch mybranch set up to track remote branch mybranch from origin."

How to use z-index in svg elements?

Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.

var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);

Target: Is an element for which we need to bring it to top svg: Is the container of elements

Get parent of current directory from Python script

You can simply use../your_script_name.py For example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csv located in trading system/data/. You simply need to refer to it as ../data/volume.csv

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

Android Studio: Where is the Compiler Error Output Window?

You can also see the error in the Build window by clicking on the toggle button.

enter image description here

How do you make an anchor link non-clickable or disabled?

The easyest way

In your html:

<a id="foo" disabled="true">xxxxx<a>

In your js:

$('#foo').attr("disabled", false);

If you use it as attribute works perfectly

How to scroll table's "tbody" independent of "thead"?

try this.

table 
{
    background-color: #aaa;
}

tbody 
{
    background-color: #ddd;
    height: 100px;
    overflow-y: scroll;
    position: absolute;
}

td 
{
    padding: 3px 10px;
    color: green;
    width: 100px;
}

MySQL equivalent of DECODE function in Oracle

Try this:

Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
   'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person

How do I search an SQL Server database for a string?

This will search every column of every table in a specific database. Create the stored procedure on the database that you want to search in.

The Ten Most Asked SQL Server Questions And Their Answers:

CREATE PROCEDURE FindMyData_String
    @DataToFind NVARCHAR(4000),
    @ExactMatch BIT = 0
AS
SET NOCOUNT ON

DECLARE @Temp TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), DataFound BIT)

    INSERT  INTO @Temp(TableName,SchemaName, ColumnName, DataType)
    SELECT  C.Table_Name,C.TABLE_SCHEMA, C.Column_Name, C.Data_Type
    FROM    Information_Schema.Columns AS C
            INNER Join Information_Schema.Tables AS T
                ON C.Table_Name = T.Table_Name
        AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
    WHERE   Table_Type = 'Base Table'
            And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')


DECLARE @i INT
DECLARE @MAX INT
DECLARE @TableName sysname
DECLARE @ColumnName sysname
DECLARE @SchemaName sysname
DECLARE @SQL NVARCHAR(4000)
DECLARE @PARAMETERS NVARCHAR(4000)
DECLARE @DataExists BIT
DECLARE @SQLTemplate NVARCHAR(4000)

SELECT  @SQLTemplate = CASE WHEN @ExactMatch = 1
                            THEN 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       = ''' + @DataToFind + '''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            ELSE 'If Exists(Select *
                                          From   ReplaceTableName
                                          Where  Convert(nVarChar(4000), [ReplaceColumnName])
                                                       Like ''%' + @DataToFind + '%''
                                          )
                                     Set @DataExists = 1
                                 Else
                                     Set @DataExists = 0'
                            END,
        @PARAMETERS = '@DataExists Bit OUTPUT',
        @i = 1

SELECT @i = 1, @MAX = MAX(RowId)
FROM   @Temp

WHILE @i <= @MAX
    BEGIN
        SELECT  @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
        FROM    @Temp
        WHERE   RowId = @i


        PRINT @SQL
        EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @DataExists = @DataExists OUTPUT

        IF @DataExists =1
            UPDATE @Temp SET DataFound = 1 WHERE RowId = @i

        SET @i = @i + 1
    END

SELECT  SchemaName,TableName, ColumnName
FROM    @Temp
WHERE   DataFound = 1
GO

To run it, just do this:

exec FindMyData_string 'google', 0

It works amazingly well!!!

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

Make child visible outside an overflow:hidden parent

You can use the clearfix to do "layout preserving" the same way overflow: hidden does.

.clearfix:before,
.clearfix:after {
    content: ".";    
    display: block;    
    height: 0;    
    overflow: hidden; 
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */

add class="clearfix" class to the parent, and remove overflow: hidden;

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

AttributeError: Module Pip has no attribute 'main'

Pip 10.0.* doesn't support main.

You have to downgrade to pip 9.0.3.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Can’t delete docker image with dependent child images

I had this issue and none of the short answers here worked, even in the page mentioned by @tudor above. I thought I would share here how I got rid of the images. I came up with the idea that dependent images must be >= the size of the parent image, which helps identify it so we can remove it.

I listed the images in size order to see if I could spot any correlations:

docker images --format '{{.Size}}\t{{.Repository}}\t{{.Tag}}\t{{.ID}}' | sort -h -r | column -t

What this does, is use some special formatting from docker to position the image size column first, then run a human readable sort in reverse order. Then I restore the easy-to-read columns.

Then I looked at the <none> containers, and matched the first one in the list with a similar size. I performed a simple docker rmi <image:tag> on that image and all the <none> child images went with it.

The problem image with all the child images was actually the damn myrepo/getstarted-lab image I used when I first started playing with docker. It was because I had created a new image from the first test image which created the chain.

Hopefully that helps someone else at some point.

Java SSLException: hostname in certificate didn't match

Thanks Vineet Reynolds. The link you provided held a lot of user comments - one of which I tried in desperation and it helped. I added this method :

// Do not do this in production!!!
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
    public boolean verify(String string,SSLSession ssls) {
        return true;
    }
});

This seems fine for me now, though I know this solution is temporary. I am working with the network people to identify why my hosts file is being ignored.

When to use LinkedList over ArrayList in Java?

In addition to the other good arguments above, you should notice ArrayList implements RandomAccess interface, while LinkedList implements Queue.

So, somehow they address slightly different problems, with difference of efficiency and behavior (see their list of methods).

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

First change apache listen port 80 to 8080 apache in /etc/apache2/ports.conf include

Listen 1.2.3.4:80 to 1.2.3.4:8080
sudo service apache2 restart 

or

sudo service httpd restart    // in case of centos

then add nginx as reverse proxy server that will listen apache port

server {
 listen   1.2.3.4:80;
 server_name  some.com;

 access_log  /var/log/nginx/something-access.log;

 location / {
  proxy_pass http://localhost:8080;
  proxy_redirect off;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }


location ~* ^.+\.(jpg|js|jpeg|png)$ {
   root /usr/share/nginx/html/;
}

location /404.html {
  root /usr/share/nginx/html/40x.html;
}

error_page 404 /404.html;
    location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
    location = /50x.html {
}

# put code for static content like js/css/images/fonts
}

After changes restart nginx server

sudo service nginx restart

Now all traffic will be handled by nginx server and send all dynamic request to apache and static conten is served by nginx server.

For advance configuration like cache :

https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#basic-nginx-caching

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

How to send a message to a particular client with socket.io

You can refer to socket.io rooms. When you handshaked socket - you can join him to named room, for instance "user.#{userid}".

After that, you can send private message to any client by convenient name, for instance:

io.sockets.in('user.125').emit('new_message', {text: "Hello world"})

In operation above we send "new_message" to user "125".

thanks.

How to check if input date is equal to today's date?

A simple date comparison in pure JS should be sufficient:

// Create date from input value
var inputDate = new Date("11/21/2011");

// Get today's date
var todaysDate = new Date();

// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
    // Date equals today's date
}

Here's a working JSFiddle.

Git: How to remove proxy

Some times, local config command won't show the proxy but it wont allow git push due to proxy. Run the following commands within the directory and see.

#git config --local --list

But the following commands displays the proxy set to local repository:

#git config http.proxy
#git config https.proxy

If the above command displays any proxy then clear it by running the following commands:

#git config https.proxy ""
#git config https.proxy ""

Rollback to last git commit

If you want to just uncommit the last commit use this:

git reset HEAD~

work like charm for me.

Passing html values into javascript functions

Here is the JSfiddle Demo

I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:

<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p> 

function verifyorder() {
        var order = document.getElementById('value').value;
        if (+order > 0) {
            alert(+order);
            return true;
        }
        else {
            alert("Sorry, you need to enter a positive integer value, try again");
            document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
        }
    }

Difference between a SOAP message and a WSDL?

A WSDL (Web Service Definition Language) is a meta-data file that describes the web service.

Things like operation name, parameters etc.

The soap messages are the actual payloads

IE8 support for CSS Media Query

Internet Explorer versions before IE9 do not support media queries.

If you are looking for a way of degrading the design for IE8 users, you may find IE's conditional commenting helpful. Using this, you can specify an IE 8/7/6 specific style sheet which over writes the previous rules.

For example:

<link rel="stylesheet" type="text/css" media="all" href="style.css"/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ie.css"/>
<![endif]-->

This won't allow for a responsive design in IE8, but could be a simpler and more accessible solution than using a JS plugin.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

How do I configure modprobe to find my module?

I think the key is to copy the module to the standard paths.

Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

  1. Open phpMyAdmin in a browser and log in as root.
  2. Create a database called phpmyadmin
  3. Create a user called pma and set the "host" to the hostname or IP address of your web server (if the web server and MySQL are on the same box use localhost), make a note of the password, and grant the new user full control over the phpmyadmin database. It is recommended that this user does not have access to anything other than this database.
  4. Go to the phpMyAdmin installation directory, where you should find a sub-directory called sql.
  5. In sql you will find a file called create_tables.sql. Open it in a text editor.
  6. In phpMyAdmin, select the phpmyadmin database and click on the "SQL" tab.
  7. Copy/paste the entire text from create_tables.sql into the text box, and run the query.
  8. Open the config.inc.php file in the phpMyAdmin install directory, and add the following lines (or change the existing settings if they are already there):

    $cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][1]['controluser'] = 'pma';
    $cfg['Servers'][1]['controlpass'] = '<your password>';
    
    // Note: The list below may grow as PMA evolves and more control tables are added
    // Use your common sense! Don't just blindly copypasta, look at what it means!
    $cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][1]['relation'] = 'pma_relation';
    $cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma_table_info';
    $cfg['Servers'][1]['column_info'] = 'pma_column_info';
    $cfg['Servers'][1]['history'] = 'pma_history';
    $cfg['Servers'][1]['recent'] = 'pma_recent';
    $cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
    $cfg['Servers'][1]['tracking'] = 'pma_tracking';
    $cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';
    
  9. Save and close the file.

IMPORTANT - PMA loads the config on login, evaluates it and stores it into the session data so the message will not disappear until you do this:

  1. Log out of phpMyAdmin and log in again

Problem solved.

HTML if image is not found

Try using border=0 in the img tag to make the ugly square go away.

<img src="someimage.png" border="0" alt="some alternate text" />

Unable to execute dex: Multiple dex files define

I found below solution in eclipse...hope it works for you :)

Right click on the Project Name

Select Java Build Path, go to the tab Order and Export

Unchecked your .jar library's

Netbeans - class does not have a main method

  1. Check for correct method declaration

public static void main(String [ ] args)

  1. Check netbeans project properties in Run > main Class

JQuery datepicker not working

For me.. the problem was that the anchor needs a title, and that was missing!

Appending an id to a list if not already present in a string

Your list just contains a string. Convert it to integer IDs:

L = ['350882 348521 350166\r\n']

ids = [int(i) for i in L[0].strip().split()]
print(ids)
id = 348521
if id not in ids:
    ids.append(id)
print(ids)
id = 348522
if id not in ids:
    ids.append(id)
print(ids)
# Turn it back into your odd format
L = [' '.join(str(id) for id in ids) + '\r\n']
print(L)

Output:

[350882, 348521, 350166]
[350882, 348521, 350166]
[350882, 348521, 350166, 348522]
['350882 348521 350166 348522\r\n']

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I tried to start my binary, compiled with Qt 5.7, on Ubuntu 16.04 LTS where Qt 5.5 is preinstalled. It didn't work.

At first, I inspected the binary itself with ldd as was suggested here, and "satisfied" all "not found" dependencies. Then this notorious This application failed to start because it could not find or load the Qt platform plugin "xcb" error was thrown.

How to resolve this in Linux

Firstly you should create platforms directory where your binary is, because it is the place where Qt looks for XCB library. Copy libqxcb.so there. I wonder why authors of other answers didn't mention this.

Then you may want to run your binary with QT_DEBUG_PLUGINS=1 environment variable set to check which dependencies of libqxcb.so are not "satisfied". (You may also use ldd for this as suggested in the accepted answer).

The command output may look like this:

me@xerus:/media/sf_Qt/Package$ LD_LIBRARY_PATH=. QT_DEBUG_PLUGINS=1 ./Binary
QFactoryLoader::QFactoryLoader() checking directory path "/media/sf_Qt/Package/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/media/sf_Qt/Package/platforms/libqxcb.so"
Found metadata in lib /media/sf_Qt/Package/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 329472
}


Got keys from plugin meta data ("xcb")
loaded library "/media/sf_Qt/Package/platforms/libqxcb.so"
QLibraryPrivate::loadPlugin failed on "/media/sf_Qt/Package/platforms/libqxcb.so" : "Cannot load library /media/sf_Qt/Package/platforms/libqxcb.so: (/usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by ./libQt5XcbQpa.so.5))"
This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".

Available platform plugins are: xcb.

Reinstalling the application may fix this problem.
Aborted (core dumped)

Note the failing libQt5DBus.so.5 library. Copy it to your libraries path, in my case it was the same directory where my binary is (hence LD_LIBRARY_PATH=.). Repeat this process until all dependencies are satisfied.

P.S. thanks to the author of this answer for QT_DEBUG_PLUGINS=1.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Rather than doing string manipulation, you can use the HOUR, MINUTE, SECOND functions to break apart the time. You can then multiply by 60*60*1000, 60*1000, and 1000 respectively to get milliseconds.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

how to fix groovy.lang.MissingMethodException: No signature of method:

In my case it was simply that I had a variable named the same as a function.

Example:

def cleanCache = functionReturningABoolean()

if( cleanCache ){
    echo "Clean cache option is true, do not uninstall previous features / urls"
    uninstallCmd = ""
    
    // and we call the cleanCache method
    cleanCache(userId, serverName)
}
...

and later in my code I have the function:

def cleanCache(user, server){

 //some operations to the server

}

Apparently the Groovy language does not support this (but other languages like Java does). I just renamed my function to executeCleanCache and it works perfectly (or you can also rename your variable whatever option you prefer).

How to remove item from array by value?

//edited thanks to MarcoCI for the advice

try this:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

hope this help you

How to read a single char from the console in Java (as the user types it)?

You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. jCurses might be interesting, though.

On a Unix system, this might work:

String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();

For example, if you want to take into account the time between keystrokes, here's sample code to get there.

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

adb not finding my device / phone (MacOS X)

On the LG G3 I was able to get it working by installing ADB via homebrew (Installing ADB on MAC OS X) and then disabling/enabling USB debugging.

Bash script to run php script

a quick way to find out WHERE YOUR particular executable is located on your $PATH, try.

Even quicker way to find out where php is ...

whereis php

I'm running debian and above command showing me

php: /usr/bin/php /usr/share/php /usr/share/man/man1/php.1.gz

Hope that helps.

How do I correctly detect orientation change using Phonegap on iOS?

I'm creating a jQTouch app in PhoneGap for the iPhone. I've been battling with this issue for days. I've seen the eventlistener solution suggested a few times, but just could not get it to work.

In the end I came up with a different solution. It basically checks the width of the body periodically using settimeout. If the width is 320 then the orientation is portrait, if 480 then landscape. Then, if the orientation has changed since the last check, it will fire either a portrait stuff function or a landscape stuff function where you can do your thing for each orientation.

Code (note, I know there is some repetition in the code, just haven't bothered to trim it down yet!):

// get original orientation based on body width
deviceWidth = $('body').width();
if (deviceWidth == 320) {
    currentOrientation = "portrait";
}
else if (deviceWidth == 480) {
    currentOrientation = "landscape";
}

// fire a function that checks the orientation every x milliseconds
setInterval(checkOrientation, 500);

// check orientation
function checkOrientation() {
    deviceWidth = $('body').width();
    if (deviceWidth == '320') {
        newOrientation = "portrait";
    }
    else if (deviceWidth == '480') {
        newOrientation = "landscape";
    }
    // if orientation changed since last check, fire either the portrait or landscape function
    if (newOrientation != currentOrientation) {
        if (newOrientation == "portrait") {
            changedToPortrait();
        }
        else if (newOrientation == "landscape") {
            changedToLandscape();
        }
        currentOrientation = newOrientation;
    }
}

// landscape stuff
function changedToLandscape() {
    alert('Orientation has changed to Landscape!');
}

// portrait stuff
function changedToPortrait() {
    alert('Orientation has changed to Portrait!');
}

check android application is in foreground or not?

check if the app is in background or foreground. This method will return true if the app is in background.

First add the GET_TASKS permission to your AndroidManifest.xml

private boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

Print DIV content by JQuery

There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.

Css:

#SelectorToPrint{
     display: none;
}

Script:

  $("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})

This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

Bootstrap 3: Offset isn't working?

There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.

To get the result I believe you are looking for try this:

<div class="container">
    <div class="row">
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
    </div>
  </div>

Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.

Hope this helps.

Is there a way to do repetitive tasks at intervals?

Check out this library: https://github.com/robfig/cron

Example as below:

c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly",      func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()

How to implement "confirmation" dialog in Jquery UI dialog?

Personally I see this as a recurrent requirement in many views of many ASP.Net MVC applications.

That's why I defined a model class and a partial view:

using Resources;

namespace YourNamespace.Models
{
  public class SyConfirmationDialogModel
  {
    public SyConfirmationDialogModel()
    {
      this.DialogId = "dlgconfirm";
      this.DialogTitle = Global.LblTitleConfirm;
      this.UrlAttribute = "href";
      this.ButtonConfirmText = Global.LblButtonConfirm;
      this.ButtonCancelText = Global.LblButtonCancel;
    }

    public string DialogId { get; set; }
    public string DialogTitle { get; set; }
    public string DialogMessage { get; set; }
    public string JQueryClickSelector { get; set; }
    public string UrlAttribute { get; set; }
    public string ButtonConfirmText { get; set; }
    public string ButtonCancelText { get; set; }
  }
}

And my partial view:

@using YourNamespace.Models;

@model SyConfirmationDialogModel

<div id="@Model.DialogId" title="@Model.DialogTitle">
  @Model.DialogMessage
</div>

<script type="text/javascript">
  $(function() {
    $("#@Model.DialogId").dialog({
      autoOpen: false,
      modal: true
    });

    $("@Model.JQueryClickSelector").click(function (e) {
      e.preventDefault();
      var sTargetUrl = $(this).attr("@Model.UrlAttribute");

      $("#@Model.DialogId").dialog({
        buttons: {
          "@Model.ButtonConfirmText": function () {
            window.location.href = sTargetUrl;
          },  
          "@Model.ButtonCancelText": function () {
            $(this).dialog("close");
          }
        }
      });

      $("#@Model.DialogId").dialog("open");
    });
  });
</script>

And then, every time you need it in a view, you just use @Html.Partial (in did it in section scripts so that JQuery is defined):

@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})

The trick is to specify the JQueryClickSelector that will match the elements that need a confirmation dialog. In my case, all anchors with the class SyLinkDelete but it could be an identifier, a different class etc. For me it was a list of:

<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
    <img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

How to detect installed version of MS-Office?

Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.

As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.

After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext.

So, my logic follows below:

Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing.

Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume)

Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail(which is also a product ID) along with some other values.

The possible productIds are provided here.

To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext and try to see if any name has a prefix o365, if it finds it then its O365. If it does not, then its Office 2019.

Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.

Hope this will help whoever's interest.

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.

I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.

To summarize:

  • posix: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.
  • win32: No C++11 multithreading features.

Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.

New line character in VB.Net?

Check out Environment.NewLine. As for web pages, break lines with <br> or <p></p> tags.

How to convert an address to a latitude/longitude?

You could also try the OpenStreetMap NameFinder (or the current Nominatim), which contains open source, wiki-like street data for (potentially) the entire world.

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

Is there an XSLT name-of element?

<xsl:for-each select="person">
  <xsl:for-each select="*">
    <xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
  </xsl:for-each>  
</xsl:for-each>

GET parameters in the URL with CodeIgniter

You simply need to enable it in the config.php and you can use $this->input->get('param_name'); to get parameters.

posting hidden value

You should never assume register_global_variables is turned on. Even if it is, it's deprecated and you should never use it that way.

Refer directly to the $_POST or $_GET variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:

<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />

If this doesn't work for you right away, print out the $_POST or $_GET variable on the page that would have the hidden form field and determine exactly what you want and refer to it.

echo "<pre>";
print_r($_POST);
echo "</pre>";

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

Open Source Javascript PDF viewer

You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.

I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.

How to sum columns in a dataTable?

 for (int i=0;i<=dtB.Columns.Count-1;i++)
 {
   array(0, i) = dtB.Compute("SUM([" & dtB.Columns(i).ColumnName & "])", "")                   
 }

How to close <img> tag properly?

The best use of tags you should use:

<img src="" alt=""/>

Also you can use in HTML5:

<img src="" alt="">

These two are completely valid in HTML5 Pick one of them and stick with that.

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

i would recommend Modern UI for WPF .

It has a very active maintainer it is awesome and free!

Modern UI for WPF (Screenshot of the sample application

I'm currently porting some projects to MUI, first (and meanwhile second) impression is just wow!

To see MUI in action you could download XAML Spy which is based on MUI.

EDIT: Using Modern UI for WPF a few months and i'm loving it!

How to change background and text colors in Sublime Text 3

Steps I followed for an overall dark theme including file browser:

  1. Goto Preferences->Theme...
  2. Choose Adaptive.sublime-theme

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

what is Promotional and Feature graphic in Android Market/Play Store?

I know there were several perfect answers but I found this page useful as well !

from: https://support.google.com/googleplay/android-developer/answer/113469?hl=en

Quote from the site:

The Feature Graphic is used for promotions on Google Play. While this graphic is not required to save and publish your Store Listing, it is required in order to be featured on Google Play.

Commentary:

To be clear, these "promotions" are chosen at Google's discretion. Even though excellent the "This is a test" app demonstration (above) shows the Feature graphic used in common areas of the outdated "Android Market", this is no longer the case with today's "Play Store".

Quote from the site:

The Promo Graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to save and publish your Store Listing.

Commentary:

It appears that this is also at Google's discretion and not always used as the "This is a test" demo suggests. Even though an older device may not get an update to their Android version, the "Android Market" update bringing them to a modern version of "Play Store" should be available.

Android Studio - local path doesn't exist

For those who still can't solve this issue after following all the answers on here. Look in the Gradle console. I had build errors that for some reason were only showing on the Gradle console. Once I fixed them, I could run the app.

JAXB Exception: Class not known to this context

Your ProfileDto class is not referenced in SearchResultDto. Try adding @XmlSeeAlso(ProfileDto.class) to SearchResultDto.

Login to Microsoft SQL Server Error: 18456

SQL Server connection troubleshoot

In case you are not able to connect with SQL Authentication and you've tried the other solutions.

You may try the following:

Check connectivity

  • Disable Firewall.
  • Run PortQry on 1434 and check the answer.

Check the state

  • Try to connect with SSMS or sqlcmd and check the message.
  • State 1 is rarely documented but it just mean you don't have the right to know the true state.
  • Look at the log file in the directory of SQL server to know what is the state.

The State 5

What ? my login doesn't exist ? it's right there, I can see it in SSMS. How can it be ?

The most likely explanation is the most likely to be the right one.

The state of the login

  • Destroy, recreate it, enable it.
  • reset the password.

Or...

"You don't look at the right place" or "what you see is not what you think".

The Local DB and SQLEXPRESS conflict

If you connect with SSMS with Windows authentication, and your instance is named SQLEXPRESS, you are probably looking at the LocalDb and not the right server. So you just created your login on LocalDb.

When you connect through SQL Server authentication with SSMS, it will try to connect to SQLEXPRESS real server where your beloved login doesn't exist yet.

Additional note: Check in the connection parameters tab if you've not forgotten some strange connection string there.