Programs & Examples On #Intellipad

Class file has wrong version 52.0, should be 50.0

Select "File" -> "Project Structure".

Under "Project Settings" select "Project"

From there you can select the "Project SDK".

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest Additions are available for MacOS starting with VirtualBox 6.0.

Installing:

  1. Boot & login into your guest macOS.
  2. In VirtualBox UI, use menu Devices | Insert Guest Additions CD image...
  3. CD will appear on your macOS desktop, open it.
  4. Run VBoxDarwinAdditions.pkg.
  5. Go through installer, it's mostly about clicking Next.
  6. At some step, macOS will be asking about permissions for Oracle. Click the button to go to System Preferences and allow it.
  7. If you forgot/misclicked in step 6, go to macOS System Preferences | Security & Privacy | General. In the bottom, there will be a question to allow permissions for Oracle. Allow it.

Troubleshooting

  1. macOS 10.15 introduced new code signing requirements; Guest additions installation will fail. However, if you reboot and apply step 7 from list above, shared clipboard will still work.
  2. VirtualBox < 6.0.12 has a bug where Guest Additions service doesn't start. Use newer VirtualBox.

Android "elevation" not showing a shadow

Setting android:clipToPadding="false" in the top relative layout has solved the problem.

Can't create project on Netbeans 8.2

Yes it s working: remove the path of jdk 9.0 and uninstall this from Cantroll panel instead install jdk 8version and set it's path, it is working easily with netbean 8.2.

What does "Changes not staged for commit" mean

You have to use git add to stage them, or they won't commit. Take it that it informs git which are the changes you want to commit.

git add -u :/ adds all modified file changes to the stage git add * :/ adds modified and any new files (that's not gitignore'ed) to the stage

Git push rejected "non-fast-forward"

In Eclipse do the following:

GIT Repositories > Remotes > Origin > Right click and say fetch

GIT Repositories > Remote Tracking > Select your branch and say merge

Go to project, right click on your file and say Fetch from upstream.

ExecuteNonQuery: Connection property has not been initialized.

Actually this error occurs when server makes connection but can't build due to failure in identifying connection function identifier. This problem can be solved by typing connection function in code. For this I take a simple example. In this case function is con your may be different.

SqlCommand cmd = new SqlCommand("insert into ptb(pword,rpword) values(@a,@b)",con);

Convert International String to \u Codes in java

In case you need this to write a .properties file you can just add the Strings into a Properties object and then save it to a file. It will take care for the conversion.

Spring Boot - How to log all requests and responses with exceptions in single place?

@hahn's answer required a bit of modification for it to work for me, but it is by far the most customizable thing I could get.

It didn't work for me, probably because I also have a HandlerInterceptorAdapter[??] but I kept getting a bad response from the server in that version. Here's my modification of it.

public class LoggableDispatcherServlet extends DispatcherServlet {

    private final Log logger = LogFactory.getLog(getClass());

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {

        long startTime = System.currentTimeMillis();
        try {
            super.doDispatch(request, response);
        } finally {
            log(new ContentCachingRequestWrapper(request), new ContentCachingResponseWrapper(response),
                    System.currentTimeMillis() - startTime);
        }
    }

    private void log(HttpServletRequest requestToCache, HttpServletResponse responseToCache, long timeTaken) {
        int status = responseToCache.getStatus();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("httpStatus", status);
        jsonObject.addProperty("path", requestToCache.getRequestURI());
        jsonObject.addProperty("httpMethod", requestToCache.getMethod());
        jsonObject.addProperty("timeTakenMs", timeTaken);
        jsonObject.addProperty("clientIP", requestToCache.getRemoteAddr());
        if (status > 299) {
            String requestBody = null;
            try {
                requestBody = requestToCache.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonObject.addProperty("requestBody", requestBody);
            jsonObject.addProperty("requestParams", requestToCache.getQueryString());
            jsonObject.addProperty("tokenExpiringHeader",
                    responseToCache.getHeader(ResponseHeaderModifierInterceptor.HEADER_TOKEN_EXPIRING));
        }
        logger.info(jsonObject);
    }
}

Pandas conditional creation of a series/dataframe column

List comprehension is another way to create another column conditionally. If you are working with object dtypes in columns, like in your example, list comprehensions typically outperform most other methods.

Example list comprehension:

df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]

%timeit tests:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
%timeit df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
%timeit df['color'] = np.where(df['Set']=='Z', 'green', 'red')
%timeit df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')

1000 loops, best of 3: 239 µs per loop
1000 loops, best of 3: 523 µs per loop
1000 loops, best of 3: 263 µs per loop

Load image from resources area of project in C#

You need to load it from resource stream.

Bitmap bmp = new Bitmap(
  System.Reflection.Assembly.GetEntryAssembly().
    GetManifestResourceStream("MyProject.Resources.myimage.png"));

If you want to know all resource names in your assembly, go with:

string[] all = System.Reflection.Assembly.GetEntryAssembly().
  GetManifestResourceNames();

foreach (string one in all) {
    MessageBox.Show(one);
}

How can I add a variable to console.log?

You can pass multiple args to log:

console.log("story", name, "story");

Selecting empty text input using jQuery

$(":text[value='']").doStuff();

?

By the way, your call of:

$('input[id=cmdSubmit]')...

can be greatly simplified and speeded up with:

$('#cmdSubmit')...

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

Entity Framework Provider type could not be loaded?

I've created a static "startup" file and added the code to force the DLL to be copied to the bin folder in it as a way to separate this 'configuration'.


[DbConfigurationType(typeof(DbContextConfiguration))] public static class Startup { }

public class DbContextConfiguration : DbConfiguration
{
    public DbContextConfiguration()
    {
        // This is needed to force the EntityFramework.SqlServer DLL to be copied to the bin folder
        SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}

Rollback to an old Git commit in a public repo

To rollback to a specific commit:

git reset --hard commit_sha

To rollback 10 commits back:

git reset --hard HEAD~10

You can use "git revert" as in the following post if you don't want to rewrite the history

How to revert Git repository to a previous commit?

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

How to create exe of a console application

an EXE file is created as long as you build the project. you can usually find this on the debug folder of you project.

C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug

How can I get my Android device country code without using GPS?

The checked answer has deprecated code. You need to implement this:

String locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0).getCountry();
} else {
    locale = context.getResources().getConfiguration().locale.getCountry();
}

What characters are valid for JavaScript variable names?

Basically, in regular expression form: [a-zA-Z_$][0-9a-zA-Z_$]*. In other words, the first character can be a letter or _ or $, and the other characters can be letters or _ or $ or numbers.

Note: While other answers have pointed out that you can use Unicode characters in JavaScript identifiers, the actual question was "What characters should I use for the name of an extension library like jQuery?" This is an answer to that question. You can use Unicode characters in identifiers, but don't do it. Encodings get screwed up all the time. Keep your public identifiers in the 32-126 ASCII range where it's safe.

How to insert text with single quotation sql server 2005

INSERT INTO Table1 (Column1) VALUES ('John''s')

Or you can use a stored procedure and pass the parameter as -

usp_Proc1 @Column1 = 'John''s'

If you are using an INSERT query and not a stored procedure, you'll have to escape the quote with two quotes, else its OK if you don't do it.

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

jQuery Ajax Request inside Ajax Request

Call second ajax from 'complete'

Here is the example

   var dt='';
   $.ajax({
    type: "post",
    url: "ajax/example.php",
    data: 'page='+btn_page,
    success: function(data){
        dt=data;
        /*Do something*/
    },
    complete:function(){
        $.ajax({
           var a=dt; // This line shows error.
           type: "post",
           url: "example.php",
           data: 'page='+a,
           success: function(data){
              /*do some thing in second function*/
           },
       });
    }
});

Put a Delay in Javascript

This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.

Convert base64 string to image

To decode:

byte[] image = Base64.getDecoder().decode(base64string);

To encode:

String text = Base64.getEncoder().encodeToString(imageData);

Help with packages in java - import does not work

It sounds like you are on the right track with your directory structure. When you compile the dependent code, specify the -classpath argument of javac. Use the parent directory of the com directory, where com, in turn, contains company/thing/YourClass.class

So, when you do this:

javac -classpath <parent> client.java

The <parent> should be referring to the parent of com. If you are in com, it would be ../.

Bitwise operation and usage

Another common use-case is manipulating/testing file permissions. See the Python stat module: http://docs.python.org/library/stat.html.

For example, to compare a file's permissions to a desired permission set, you could do something like:

import os
import stat

#Get the actual mode of a file
mode = os.stat('file.txt').st_mode

#File should be a regular file, readable and writable by its owner
#Each permission value has a single 'on' bit.  Use bitwise or to combine 
#them.
desired_mode = stat.S_IFREG|stat.S_IRUSR|stat.S_IWUSR

#check for exact match:
mode == desired_mode
#check for at least one bit matching:
bool(mode & desired_mode)
#check for at least one bit 'on' in one, and not in the other:
bool(mode ^ desired_mode)
#check that all bits from desired_mode are set in mode, but I don't care about 
# other bits.
not bool((mode^desired_mode)&desired_mode)

I cast the results as booleans, because I only care about the truth or falsehood, but it would be a worthwhile exercise to print out the bin() values for each one.

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath*:spring-config.xml" /> 

This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.

Call two functions from same onclick

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

a workaround to this:

onclick="var temp = function1();function2(); return temp;"

Selenium WebDriver.get(url) does not open the URL

I was having the save issue. I assume you made sure your java server was running before you started your python script? The java server can be downloaded from selenium's download list.

When I did a netstat to evaluate the open ports, i noticed that the java server wasn't running on the specific "localhost" host:

When I started the server, I found that the port number was 4444 :

$ java -jar selenium-server-standalone-2.35.0.jar 
Sep 24, 2013 10:18:57 PM org.openqa.grid.selenium.GridLauncher main
INFO: Launching a standalone server
22:19:03.393 INFO - Java: Apple Inc. 20.51-b01-456
22:19:03.394 INFO - OS: Mac OS X 10.8.5 x86_64
22:19:03.418 INFO - v2.35.0, with Core v2.35.0. Built from revision c916b9d
22:19:03.681 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
22:19:03.683 INFO - Version Jetty/5.1.x
22:19:03.683 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
22:19:03.685 INFO - Started HttpContext[/selenium-server,/selenium-server]
22:19:03.685 INFO - Started HttpContext[/,/]
22:19:03.755 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@21b64e6a
22:19:03.755 INFO - Started HttpContext[/wd,/wd]
22:19:03.765 INFO - Started SocketListener on 0.0.0.0:4444

I was able to view my listening ports and their port numbers(the -n option) by running the following command in the terminal:

$netstat -an | egrep 'Proto|LISTEN'

This got me the following output

Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)    

tcp46      0      0  *.4444                 *.*                    LISTEN  

I realized this may be a problem, because selenium's socket utils, found in: webdriver/common/utils.py are trying to connect via "localhost" or 127.0.0.1:

socket_.connect(("localhost", port))

once I changed the "localhost" to '' (empty single quotes to represent all local addresses), it started working. So now, the previous line from utils.py looks like this:

socket_.connect(('', port))

I am using MacOs and Firefox 22. The latest version of Firefox at the time of this post is 24, but I heard there are some security issues with the version that may block some of selenium's functionality (I have not verified this). Regardless, for this reason, I am using the older version of Firefox.

Force encode from US-ASCII to UTF-8 (iconv)

Short Answer

  • file only guesses at the file encoding and may be wrong (especially in cases where special characters only appear late in large files).
  • you can use hexdump to look at bytes of non-7-bit-ASCII text and compare against code tables for common encodings (ISO 8859-*, UTF-8) to decide for yourself what the encoding is.
  • iconv will use whatever input/output encoding you specify regardless of what the contents of the file are. If you specify the wrong input encoding, the output will be garbled.
  • even after running iconv, file may not report any change due to the limited way in which file attempts to guess at the encoding. For a specific example, see my long answer.
  • 7-bit ASCII (aka US ASCII) is identical at a byte level to UTF-8 and the 8-bit ASCII extensions (ISO 8859-*). So if your file only has 7-bit characters, then you can call it UTF-8, ISO 8859-* or US ASCII because at a byte level they are all identical. It only makes sense to talk about UTF-8 and other encodings (in this context) once your file has characters outside the 7-bit ASCII range.

Long Answer

I ran into this today and came across your question. Perhaps I can add a little more information to help other people who run into this issue.

ASCII

First, the term ASCII is overloaded, and that leads to confusion.

7-bit ASCII only includes 128 characters (00-7F or 0-127 in decimal). 7-bit ASCII is also sometimes referred to as US-ASCII.

ASCII

UTF-8

UTF-8 encoding uses the same encoding as 7-bit ASCII for its first 128 characters. So a text file that only contains characters from that range of the first 128 characters will be identical at a byte level whether encoded with UTF-8 or 7-bit ASCII.

Codepage layout

ISO 8859-* and other ASCII Extensions

The term extended ASCII (or high ASCII) refers to eight-bit or larger character encodings that include the standard seven-bit ASCII characters, plus additional characters.

Extended ASCII

ISO 8859-1 (aka "ISO Latin 1") is a specific 8-bit ASCII extension standard that covers most characters for Western Europe. There are other ISO standards for Eastern European languages and Cyrillic languages. ISO 8859-1 includes characters like Ö, é, ñ and ß for German and Spanish.

"Extension" means that ISO 8859-1 includes the 7-bit ASCII standard and adds characters to it by using the 8th bit. So for the first 128 characters, it is equivalent at a byte level to ASCII and UTF-8 encoded files. However, when you start dealing with characters beyond the first 128, your are no longer UTF-8 equivalent at the byte level, and you must do a conversion if you want your "extended ASCII" file to be UTF-8 encoded.

ISO 8859 and proprietary adaptations

Detecting encoding with file

One lesson I learned today is that we can't trust file to always give correct interpretation of a file's character encoding.

file (command)

The command tells only what the file looks like, not what it is (in the case where file looks at the content). It is easy to fool the program by putting a magic number into a file the content of which does not match it. Thus the command is not usable as a security tool other than in specific situations.

file looks for magic numbers in the file that hint at the type, but these can be wrong, no guarantee of correctness. file also tries to guess the character encoding by looking at the bytes in the file. Basically file has a series of tests that helps it guess at the file type and encoding.

My file is a large CSV file. file reports this file as US ASCII encoded, which is WRONG.

$ ls -lh
total 850832
-rw-r--r--  1 mattp  staff   415M Mar 14 16:38 source-file
$ file -b --mime-type source-file
text/plain
$ file -b --mime-encoding source-file
us-ascii

My file has umlauts in it (ie Ö). The first non-7-bit-ascii doesn't show up until over 100k lines into the file. I suspect this is why file doesn't realize the file encoding isn't US-ASCII.

$ pcregrep -no '[^\x00-\x7F]' source-file | head -n1
102321:?

I'm on a Mac, so using PCRE's grep. With GNU grep you could use the -P option. Alternatively on a Mac, one could install coreutils (via Homebrew or other) in order to get GNU grep.

I haven't dug into the source-code of file, and the man page doesn't discuss the text encoding detection in detail, but I am guessing file doesn't look at the whole file before guessing encoding.

Whatever my file's encoding is, these non-7-bit-ASCII characters break stuff. My German CSV file is ;-separated and extracting a single column doesn't work.

$ cut -d";" -f1 source-file > tmp
cut: stdin: Illegal byte sequence
$ wc -l *
 3081673 source-file
  102320 tmp
 3183993 total

Note the cut error and that my "tmp" file has only 102320 lines with the first special character on line 102321.

Let's take a look at how these non-ASCII characters are encoded. I dump the first non-7-bit-ascii into hexdump, do a little formatting, remove the newlines (0a) and take just the first few.

$ pcregrep -o '[^\x00-\x7F]' source-file | head -n1 | hexdump -v -e '1/1 "%02x\n"'
d6
0a

Another way. I know the first non-7-bit-ASCII char is at position 85 on line 102321. I grab that line and tell hexdump to take the two bytes starting at position 85. You can see the special (non-7-bit-ASCII) character represented by a ".", and the next byte is "M"... so this is a single-byte character encoding.

$ tail -n +102321 source-file | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

In both cases, we see the special character is represented by d6. Since this character is an Ö which is a German letter, I am guessing that ISO 8859-1 should include this. Sure enough, you can see "d6" is a match (ISO/IEC 8859-1).

Important question... how do I know this character is an Ö without being sure of the file encoding? The answer is context. I opened the file, read the text and then determined what character it is supposed to be. If I open it in Vim it displays as an Ö because Vim does a better job of guessing the character encoding (in this case) than file does.

So, my file seems to be ISO 8859-1. In theory I should check the rest of the non-7-bit-ASCII characters to make sure ISO 8859-1 is a good fit... There is nothing that forces a program to only use a single encoding when writing a file to disk (other than good manners).

I'll skip the check and move on to conversion step.

$ iconv -f iso-8859-1 -t utf8 source-file > output-file
$ file -b --mime-encoding output-file
us-ascii

Hmm. file still tells me this file is US ASCII even after conversion. Let's check with hexdump again.

$ tail -n +102321 output-file | head -n1 | hexdump -C -s85 -n2
00000055  c3 96                                             |..|
00000057

Definitely a change. Note that we have two bytes of non-7-bit-ASCII (represented by the "." on the right) and the hex code for the two bytes is now c3 96. If we take a look, seems we have UTF-8 now (c3 96 is the encoding of Ö in UTF-8) UTF-8 encoding table and Unicode characters

But file still reports our file as us-ascii? Well, I think this goes back to the point about file not looking at the whole file and the fact that the first non-7-bit-ASCII characters don't occur until late in the file.

I'll use sed to stick a Ö at the beginning of the file and see what happens.

$ sed '1s/^/Ö\'$'\n/' source-file > test-file
$ head -n1 test-file
Ö
$ head -n1 test-file | hexdump -C
00000000  c3 96 0a                                          |...|
00000003

Cool, we have an umlaut. Note the encoding though is c3 96 (UTF-8). Hmm.

Checking our other umlauts in the same file again:

$ tail -n +102322 test-file | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

ISO 8859-1. Oops! It just goes to show how easy it is to get the encodings screwed up. To be clear, I've managed to create a mix of UTF-8 and ISO 8859-1 encodings in the same file.

Let's try converting our new test file with the umlaut (Ö) at the front and see what happens.

$ iconv -f iso-8859-1 -t utf8 test-file > test-file-converted
$ head -n1 test-file-converted | hexdump -C
00000000  c3 83 c2 96 0a                                    |.....|
00000005
$ tail -n +102322 test-file-converted | head -n1 | hexdump -C -s85 -n2
00000055  c3 96                                             |..|
00000057

Oops. The first umlaut that was UTF-8 was interpreted as ISO 8859-1 since that is what we told iconv. The second umlaut is correctly converted from d6 (ISO 8859-1) to c3 96 (UTF-8).

I'll try again, but this time I will use Vim to do the Ö insertion instead of sed. Vim seemed to detect the encoding better (as "latin1" aka ISO 8859-1) so perhaps it will insert the new Ö with a consistent encoding.

$ vim source-file
$ head -n1 test-file-2
?
$ head -n1 test-file-2 | hexdump -C
00000000  d6 0d 0a                                          |...|
00000003
$ tail -n +102322 test-file-2 | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

It looks good. It looks like ISO 8859-1 for new and old umlauts.

Now the test.

$ file -b --mime-encoding test-file-2
iso-8859-1
$ iconv -f iso-8859-1 -t utf8 test-file-2 > test-file-2-converted
$ file -b --mime-encoding test-file-2-converted
utf-8

Boom! Moral of the story. Don't trust file to always guess your encoding right. It is easy to mix encodings within the same file. When in doubt, look at the hex.

A hack (also prone to failure) that would address this specific limitation of file when dealing with large files would be to shorten the file to make sure that special (non-ascii) characters appear early in the file so file is more likely to find them.

$ first_special=$(pcregrep -o1 -n '()[^\x00-\x7F]' source-file | head -n1 | cut -d":" -f1)
$ tail -n +$first_special source-file > /tmp/source-file-shorter
$ file -b --mime-encoding /tmp/source-file-shorter
iso-8859-1

You could then use (presumably correct) detected encoding to feed as input to iconv to ensure you are converting correctly.

Update

Christos Zoulas updated file to make the amount of bytes looked at configurable. One day turn-around on the feature request, awesome!

http://bugs.gw.com/view.php?id=533 Allow altering how many bytes to read from analyzed files from the command line

The feature was released in file version 5.26.

Looking at more of a large file before making a guess about encoding takes time. However, it is nice to have the option for specific use-cases where a better guess may outweigh additional time and I/O.

Use the following option:

-P, --parameter name=value

    Set various parameter limits.

    Name    Default     Explanation
    bytes   1048576     max number of bytes to read from file

Something like...

file_to_check="myfile"
bytes_to_scan=$(wc -c < $file_to_check)
file -b --mime-encoding -P bytes=$bytes_to_scan $file_to_check

... it should do the trick if you want to force file to look at the whole file before making a guess. Of course, this only works if you have file 5.26 or newer.

Forcing file to display UTF-8 instead of US-ASCII

Some of the other answers seem to focus on trying to make file display UTF-8 even if the file only contains plain 7-bit ascii. If you think this through you should probably never want to do this.

  1. If a file contains only 7-bit ascii but the file command is saying the file is UTF-8, that implies that the file contains some characters with UTF-8 specific encoding. If that isn't really true, it could cause confusion or problems down the line. If file displayed UTF-8 when the file only contained 7-bit ascii characters, this would be a bug in the file program.
  2. Any software that requires UTF-8 formatted input files should not have any problem consuming plain 7-bit ascii since this is the same on a byte level as UTF-8. If there is software that is using the file command output before accepting a file as input and it won't process the file unless it "sees" UTF-8...well that is pretty bad design. I would argue this is a bug in that program.

If you absolutely must take a plain 7-bit ascii file and convert it to UTF-8, simply insert a single non-7-bit-ascii character into the file with UTF-8 encoding for that character and you are done. But I can't imagine a use-case where you would need to do this. The easiest UTF-8 character to use for this is the Byte Order Mark (BOM) which is a special non-printing character that hints that the file is non-ascii. This is probably the best choice because it should not visually impact the file contents as it will generally be ignored.

Microsoft compilers and interpreters, and many pieces of software on Microsoft Windows such as Notepad treat the BOM as a required magic number rather than use heuristics. These tools add a BOM when saving text as UTF-8, and cannot interpret UTF-8 unless the BOM is present or the file contains only ASCII.

This is key:

or the file contains only ASCII

So some tools on windows have trouble reading UTF-8 files unless the BOM character is present. However this does not affect plain 7-bit ascii only files. I.e. this is not a reason for forcing plain 7-bit ascii files to be UTF-8 by adding a BOM character.

Here is more discussion about potential pitfalls of using the BOM when not needed (it IS needed for actual UTF-8 files that are consumed by some Microsoft apps). https://stackoverflow.com/a/13398447/3616686

Nevertheless if you still want to do it, I would be interested in hearing your use case. Here is how. In UTF-8 the BOM is represented by hex sequence 0xEF,0xBB,0xBF and so we can easily add this character to the front of our plain 7-bit ascii file. By adding a non-7-bit ascii character to the file, the file is no longer only 7-bit ascii. Note that we have not modified or converted the original 7-bit-ascii content at all. We have added a single non-7-bit-ascii character to the beginning of the file and so the file is no longer entirely composed of 7-bit-ascii characters.

$ printf '\xEF\xBB\xBF' > bom.txt # put a UTF-8 BOM char in new file
$ file bom.txt
bom.txt: UTF-8 Unicode text, with no line terminators
$ file plain-ascii.txt  # our pure 7-bit ascii file
plain-ascii.txt: ASCII text
$ cat bom.txt plain-ascii.txt > plain-ascii-with-utf8-bom.txt # put them together into one new file with the BOM first
$ file plain-ascii-with-utf8-bom.txt
plain-ascii-with-utf8-bom.txt: UTF-8 Unicode (with BOM) text

display Java.util.Date in a specific format

Use the SimpleDateFormat.format

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

How to auto resize and adjust Form controls with change in resolution

sorry I saw the question late, Here is an easy programmatically solution that works well on me,

Create those global variables:

 float firstWidth;
 float firstHeight;

after on load, fill those variables;

 firstWidth = this.Size.Width;
 firstHeight = this.Size.Height;

then select your form and put these code to your form's SizeChange event;

 private void AnaMenu_SizeChanged(object sender, EventArgs e)
    {
        

        float size1 = this.Size.Width /  firstWidth;
        float size2 = this.Size.Height / firstHeight;

            SizeF scale = new SizeF(size1, size2);
        firstWidth = this.Size.Width;
        firstHeight = this.Size.Height;

        foreach (Control control in this.Controls)
        {
                
            control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
            
            control.Scale(scale);
                

        }


    }

I hope this helps, it works perfect on my projects.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)

How to convert decimal to hexadecimal in JavaScript

I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:

((0xFF + number +1) & 0x0FF).toString(16);

You can use this instruction to any number bytes, only you add FF in respective places. For example, to two bytes:

((0xFFFF + number +1) & 0x0FFFF).toString(16);

If you want cast an array integer to string hexadecimal:

s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
    s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}

jQuery: How to detect window width on the fly?

Put your if condition inside resize function:

var windowsize = $(window).width();

$(window).resize(function() {
  windowsize = $(window).width();
  if (windowsize > 440) {
    //if the window is greater than 440px wide then turn on jScrollPane..
      $('#pane1').jScrollPane({
         scrollbarWidth:15, 
         scrollbarMargin:52
      });
  }
});

JAVA_HOME directory in Linux

Just another solution, this one's cross platform (uses java), and points you to the location of the jre.

java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'

Outputs all of java's current settings, and finds the one called java.home.

For windows, you can go with findstr instead of grep.

java -XshowSettings:properties -version 2>&1 | findstr "java.home"

Get 2 Digit Number For The Month

Function

FORMAT(date,'MM') 

will do the job with two digit.

Fastest way to determine if an integer's square root is an integer

It's been pointed out that the last d digits of a perfect square can only take on certain values. The last d digits (in base b) of a number n is the same as the remainder when n is divided by bd, ie. in C notation n % pow(b, d).

This can be generalized to any modulus m, ie. n % m can be used to rule out some percentage of numbers from being perfect squares. The modulus you are currently using is 64, which allows 12, ie. 19% of remainders, as possible squares. With a little coding I found the modulus 110880, which allows only 2016, ie. 1.8% of remainders as possible squares. So depending on the cost of a modulus operation (ie. division) and a table lookup versus a square root on your machine, using this modulus might be faster.

By the way if Java has a way to store a packed array of bits for the lookup table, don't use it. 110880 32-bit words is not much RAM these days and fetching a machine word is going to be faster than fetching a single bit.

FFmpeg on Android

Here are the steps I went through in getting ffmpeg to work on Android:

  1. Build static libraries of ffmpeg for Android. This was achieved by building olvaffe's ffmpeg android port (libffmpeg) using the Android Build System. Simply place the sources under /external and make away. You'll need to extract bionic(libc) and zlib(libz) from the Android build as well, as ffmpeg libraries depend on them.
  2. Create a dynamic library wrapping ffmpeg functionality using the Android NDK. There's a lot of documentation out there on how to work with the NDK. Basically you'll need to write some C/C++ code to export the functionality you need out of ffmpeg into a library java can interact with through JNI. The NDK allows you to easily link against the static libraries you've generated in step 1, just add a line similar to this to Android.mk: LOCAL_STATIC_LIBRARIES := libavcodec libavformat libavutil libc libz

  3. Use the ffmpeg-wrapping dynamic library from your java sources. There's enough documentation on JNI out there, you should be fine.

Regarding using ffmpeg for playback, there are many examples (the ffmpeg binary itself is a good example), here's a basic tutorial. The best documentation can be found in the headers.

Good luck :)

ORDER BY using Criteria API

You need to create an alias for the mother.kind. You do this like so.

Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

Unit testing with Spring Security

Just do it the usual way and then insert it using SecurityContextHolder.setContext() in your test class, for example:

Controller:

Authentication a = SecurityContextHolder.getContext().getAuthentication();

Test:

Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

C++ alignment when printing cout <<

The ISO C++ standard way to do it is to #include <iomanip> and use io manipulators like std::setw. However, that said, those io manipulators are a real pain to use even for text, and are just about unusable for formatting numbers (I assume you want your dollar amounts to line up on the decimal, have the correct number of significant digits, etc.). Even for just plain text labels, the code will look something like this for the first part of your first line:

// using standard iomanip facilities
cout << setw(20) << "Artist"
     << setw(20) << "Title"
     << setw(8) << "Price";
// ... not going to try to write the numeric formatting...

If you are able to use the Boost libraries, run (don't walk) and use the Boost.Format library instead. It is fully compatible with the standard iostreams, and it gives you all the goodness for easy formatting with printf/Posix formatting string, but without losing any of the power and convenience of iostreams themselves. For example, the first parts of your first two lines would look something like:

// using Boost.Format
cout << format("%-20s %-20s %-8s\n")  % "Artist" % "Title" % "Price";
cout << format("%-20s %-20s %8.2f\n") % "Merle" % "Blue" % 12.99;

Callback functions in Java

For simplicity, you can use a Runnable:

private void runCallback(Runnable callback)
{
    // Run callback
    callback.run();
}

Usage:

runCallback(new Runnable()
{
    @Override
    public void run()
    {
        // Running callback
    }
});

How do I change the formatting of numbers on an axis with ggplot?

I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:

 ggplot + scale_x_continuous(labels = human_gbp)

which give you human readable numbers for x or y axes (or any number in general really).

You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.

Pretty printing XML with javascript

what about creating a stub node (document.createElement('div') - or using your library equivalent), filling it with the xml string (via innerHTML) and calling simple recursive function for the root element/or the stub element in case you don't have a root. The function would call itself for all the child nodes.

You could then syntax-highlight along the way, be certain the markup is well-formed (done automatically by browser when appending via innerHTML) etc. It wouldn't be that much code and probably fast enough.

Add a column with a default value to an existing table in SQL Server

This has a lot of answers, but I feel the need to add this extended method. This seems a lot longer, but it is extremely useful if you're adding a NOT NULL field to a table with millions of rows in an active database.

ALTER TABLE {schemaName}.{tableName}
    ADD {columnName} {datatype} NULL
    CONSTRAINT {constraintName} DEFAULT {DefaultValue}

UPDATE {schemaName}.{tableName}
    SET {columnName} = {DefaultValue}
    WHERE {columName} IS NULL

ALTER TABLE {schemaName}.{tableName}
    ALTER COLUMN {columnName} {datatype} NOT NULL

What this will do is add the column as a nullable field and with the default value, update all fields to the default value (or you can assign more meaningful values), and finally it will change the column to be NOT NULL.

The reason for this is if you update a large scale table and add a new not null field it has to write to every single row and hereby will lock out the entire table as it adds the column and then writes all the values.

This method will add the nullable column which operates a lot faster by itself, then fills the data before setting the not null status.

I've found that doing the entire thing in one statement will lock out one of our more active tables for 4-8 minutes and quite often I have killed the process. This method each part usually takes only a few seconds and causes minimal locking.

Additionally, if you have a table in the area of billions of rows it may be worth batching the update like so:

WHILE 1=1
BEGIN
    UPDATE TOP (1000000) {schemaName}.{tableName}
        SET {columnName} = {DefaultValue}
        WHERE {columName} IS NULL

    IF @@ROWCOUNT < 1000000
        BREAK;
END

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

How can I pass a username/password in the header to a SOAP WCF Service

I got a better method from here: WCF: Creating Custom Headers, How To Add and Consume Those Headers

Client Identifies Itself
The goal here is to have the client provide some sort of information which the server can use to determine who is sending the message. The following C# code will add a header named ClientId:

var cl = new ActiveDirectoryClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientId",       // Header Name
                                                   string.Empty,     // Namespace
                                                    "OmegaClient")); // Header Value
cl.Endpoint.Address = eab.ToEndpointAddress();

// Now do an operation provided by the service.
cl.ProcessInfo("ABC");

What that code is doing is adding an endpoint header named ClientId with a value of OmegaClient to be inserted into the soap header without a namespace.

Custom Header in Client’s Config File
There is an alternate way of doing a custom header. That can be achieved in the Xml config file of the client where all messages sent by specifying the custom header as part of the endpoint as so:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IActiveDirectory" />
            </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://localhost:41863/ActiveDirectoryService.svc"
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IActiveDirectory"
              contract="ADService.IActiveDirectory" name="BasicHttpBinding_IActiveDirectory">
            <headers>
              <ClientId>Console_Client</ClientId>
            </headers>
          </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Fill an array with random numbers

Probably the cleanest way to do it in Java 8:

private int[] randomIntArray() {
   Random rand = new Random();
   return IntStream.range(0, 23).map(i -> rand.nextInt()).toArray();
}

How to convert number of minutes to hh:mm format in TSQL?

DECLARE @Duration int

SET @Duration= 12540 /* for example big hour amount in minutes -> 209h */

SELECT CAST( CAST((@Duration) AS int) / 60 AS varchar) + ':'  + right('0' + CAST(CAST((@Duration) AS int) % 60 AS varchar(2)),2)

/* you will get hours and minutes divided by : */

How can I write text on a HTML5 canvas element?

Depends on what you want to do with it I guess. If you just want to write some normal text you can use .fillText().

Cannot ignore .idea/workspace.xml - keeps popping up

I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:

mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea 
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea

After than make sure to ignore .idea in your .gitignore

Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.

Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.

Cannot execute script: Insufficient memory to continue the execution of the program

Below script works perfectly:

sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x

Symptoms:

When executing a recovery script with sqlcmd utility, the ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered.

Cause:

This is a sqlcmd utility limitation. If the SQL script contains dollar sign ($) in any form, the utility is unable to properly execute the script, since it is substituting all variables automatically by default.

Resolution:

In order to execute script that has a dollar ($) sign in any form, it is necessary to add “-x” parameter to the command line.

e.g.

Original: sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql

Fixed: sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x

X-Frame-Options Allow-From multiple domains

Strictly speaking no, you cant.

You can however specify X-Frame-Options: mysite.com and therefore allow subdomain1.mysite.com and subdomain2.mysite.com. But yes, that's still one domain. There happens to be some workaround for this, but I think it's easiest to read that directly at the RFC specs: https://tools.ietf.org/html/rfc7034

It's also worth to point out that the Content-Security-Policy (CSP) header's frame-ancestor directive obsoletes X-Frame-Options. Read more here.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.

How to copy sheets to another workbook using vba?

    Workbooks.Open Filename:="Path(Ex: C:\Reports\ClientWiseReport.xls)"ReadOnly:=True


    For Each Sheet In ActiveWorkbook.Sheets

        Sheet.Copy After:=ThisWorkbook.Sheets(1)

    Next Sheet

Yarn: How to upgrade yarn version using terminal?

  1. Add Yarn Package Directory:

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

  1. Install Yarn:

sudo apt-get update && sudo apt-get install yarn

Please note that the last command will upgrade yarn to latest version if package already installed.

For more info you can check the docs: yarn installation

How to rename a table in SQL Server?

This is what I use:

EXEC sp_rename 'MyTable', 'MyTableNewName';

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

Adding external library in Android studio

I had also faced this problem. Those time I followed some steps like:

  1. File > New > Import module > select your library_project. Then include 'library_project' will be added in settings.gradle file.

  2. File > Project Structure > App > Dependencies Tab > select library_project. If library_project not displaying then, Click on + button then select your library_project.

  3. Clean and build your project. The following lines will be added in your app module build.gradle (hint: this is not the one where classpath is defined).

 dependencies {
     compile fileTree(dir: 'libs', include: ['*.jar'])
     compile project(':library_project')
 }
  1. If these lines are not present, you must add them manually and clean and rebuild your project again (Ctrl + F9).

  2. A folder named library_project will be created in your app folder.

  3. If any icon or task merging error is created, go to AndroidManifest file and add <application tools:replace="icon,label,theme">

How to access the GET parameters after "?" in Express?

Update: req.param() is now deprecated, so going forward do not use this answer.


Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue).

In your case:

var color = req.param('color');

From the express guide:

lookup is performed in the following order:

  • req.params
  • req.body
  • req.query

Note the guide does state the following:

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

However in practice I've actually found req.param() to be clear enough and makes certain types of refactoring easier.

How do I Convert DateTime.now to UTC in Ruby?

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009

Printing all variables value from a class

Addition with @cletus answer, You have to fetch all model fields(upper hierarchy) and set field.setAccessible(true) to access private members. Here is the full snippet:

@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    String newLine = System.getProperty("line.separator");

    result.append(getClass().getSimpleName());
    result.append( " {" );
    result.append(newLine);

    List<Field> fields = getAllModelFields(getClass());

    for (Field field : fields) {
        result.append("  ");
        try {
            result.append(field.getName());
            result.append(": ");
            field.setAccessible(true);
            result.append(field.get(this));

        } catch ( IllegalAccessException ex ) {
//                System.err.println(ex);
        }
        result.append(newLine);
    }
    result.append("}");
    result.append(newLine);

    return result.toString();
}

private List<Field> getAllModelFields(Class aClass) {
    List<Field> fields = new ArrayList<>();
    do {
        Collections.addAll(fields, aClass.getDeclaredFields());
        aClass = aClass.getSuperclass();
    } while (aClass != null);
    return fields;
}

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How to use 'cp' command to exclude a specific directory?

Well, if exclusion of certain filename patterns had to be performed by every unix-ish file utility (like cp, mv, rm, tar, rsync, scp, ...), an immense duplication of effort would occur. Instead, such things can be done as part of globbing, i.e. by your shell.

bash

man 1 bash, / extglob.

Example:

$ shopt -s extglob
$ echo images/*
images/004.bmp images/033.jpg images/1276338351183.jpg images/2252.png
$ echo images/!(*.jpg)
images/004.bmp images/2252.png

So you just put a pattern inside !(), and it negates the match. The pattern can be arbitrarily complex, starting from enumeration of individual paths (as Vanwaril shows in another answer): !(filename1|path2|etc3), to regex-like things with stars and character classes. Refer to the manpage for details.

zsh

man 1 zshexpn, / filename generation.

You can do setopt KSH_GLOB and use bash-like patterns. Or,

% setopt EXTENDED_GLOB
% echo images/*
images/004.bmp images/033.jpg images/1276338351183.jpg images/2252.png
% echo images/*~*.jpg
images/004.bmp images/2252.png

So x~y matches pattern x, but excludes pattern y. Once again, for full details refer to manpage.


fishnew!

The fish shell has a much prettier answer to this:

 cp (string match -v '*.excluded.names' -- srcdir/*) destdir

Bonus pro-tip

Type cp *, hit CtrlX* and just see what happens. it's not harmful I promise

Query to list all stored procedures

This can also help to list procedure except the system procedures:

select * from sys.all_objects where type='p' and is_ms_shipped=0

figure of imshow() is too small

Update 2020

as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.

This works with matplotlip 3.2.1:

from matplotlib import pyplot as plt
import random
import numpy as np

random = np.random.random ([8,90])

plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')

This plots:

enter image description here

To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).

Space between Column's children in Flutter

Columns Has no height by default, You can Wrap your Column to the Container and add the specific height to your Container. Then You can use something like below:

Container(
   width: double.infinity,//Your desire Width
   height: height,//Your desire Height
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two')
      ],
   ),
),

Shortcut to create properties in Visual Studio?

Start from:

private int myVar;

When you select "myVar" and right click then select "Refactor" and select "Encapsulate Field".

It will automatically create:

{
    get { return myVar; }
    set { myVar = value; }
}

Or you can shortcut it by pressing Ctrl + R + E.

Getting SyntaxError for print with keyword argument end=' '

we need to import a header before using end='', as it is not included in the python's normal runtime.

from __future__ import print_function

it shall work perfectly now

Nginx: stat() failed (13: permission denied)

You may have Security-Enhanced Linux running, so add rule for that. I had permission 13 errors, even though permissions were set and user existed..

chcon -Rt httpd_sys_content_t /username/test/static

Sass .scss: Nesting and multiple classes?

You can use the parent selector reference &, it will be replaced by the parent selector after compilation:

For your example:

.container {
    background:red;
    &.desc{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
.container.desc {
    background: blue;
}

The & will completely resolve, so if your parent selector is nested itself, the nesting will be resolved before replacing the &.

This notation is most often used to write pseudo-elements and -classes:

.element{
    &:hover{ ... }
    &:nth-child(1){ ... }
}

However, you can place the & at virtually any position you like*, so the following is possible too:

.container {
    background:red;
    #id &{
       background:blue;
    }
}

/* compiles to: */
.container {
    background: red;
}
#id .container {
    background: blue;
}

However be aware, that this somehow breaks your nesting structure and thus may increase the effort of finding a specific rule in your stylesheet.

*: No other characters than whitespaces are allowed in front of the &. So you cannot do a direct concatenation of selector+& - #id& would throw an error.

How to get file's last modified date on Windows command line?

Useful reference to get file properties using a batch file, included is the last modified time:

FOR %%? IN ("C:\somefile\path\file.txt") DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Drive and Path       : %%~dp?
    ECHO Drive                : %%~d?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)

Get real path from URI, Android KitKat new storage access framework

I had the exact same problem. I need the filename so to be able to upload it to a website.

It worked for me, if I changed the intent to PICK. This was tested in AVD for Android 4.4 and in AVD for Android 2.1.

Add permission READ_EXTERNAL_STORAGE :

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

Change the Intent :

Intent i = new Intent(
  Intent.ACTION_PICK,
  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
  );
startActivityForResult(i, 66453666);

/* OLD CODE
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
  Intent.createChooser( intent, "Select Image" ),
  66453666
  );
*/

I did not have to change my code the get the actual path:

// Convert the image URI to the direct file system path of the image file
 public String mf_szGetRealPathFromURI(final Context context, final Uri ac_Uri )
 {
     String result = "";
     boolean isok = false;

     Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(ac_Uri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
        isok = true;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }

      return isok ? result : "";
 }

Add UIPickerView & a Button in Action sheet - How?

One more solution:

  • no toolbar but a segmented control (eyecandy)

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                        delegate:nil
                                                        cancelButtonTitle:nil
                                                        destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
    
    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    [actionSheet addSubview:pickerView];
    [pickerView release];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];
    
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    

How to exit when back button is pressed?

A better user experience:

/**
 * Back button listener.
 * Will close the application if the back button pressed twice.
 */
@Override
public void onBackPressed()
{
    if(backButtonCount >= 1)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
        backButtonCount++;
    }
}

Getting a list of files in a directory with a glob

stringWithFileSystemRepresentation doesn't appear to be available in iOS.

Rails ActiveRecord date between

I have been using the 3 dots, instead of 2. Three dots gives you a range that is open at the beginning and closed at the end, so if you do 2 queries for subsequent ranges, you can't get the same row back in both.

2.2.2 :003 > Comment.where(updated_at: 2.days.ago.beginning_of_day..1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" BETWEEN '2015-07-12 00:00:00.000000' AND '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 
2.2.2 :004 > Comment.where(updated_at: 2.days.ago.beginning_of_day...1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" >= '2015-07-12 00:00:00.000000' AND "comments"."updated_at" < '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 

And, yes, always nice to use a scope!

How do I connect to a Websphere Datasource with a given JNDI name?

Find below code to get database connection from your web app server. Just create datasource in app server and use following code to get connection :

// To Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/abcd");
// Get Connection and Statement
Connection c = ds.getConnection();
stmt = c.createStatement();

Import naming and sql classes. No need to add any xml file or to edit anything in project.
That's it..

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Check if date is a valid one

var date = moment('2016-10-19', 'DD-MM-YYYY', true);

You should add a third argument when invoking moment that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.

git clone through ssh

I want to attempt an answer that includes git-flow, and three 'points' or use-cases, the git central repository, the local development and the production machine. This is not well tested.

I am giving incredibly specific commands. Instead of saying <your folder>, I will say /root/git. The only place where I am changing the original command is replacing my specific server name with example.com. I will explain the folders purpose is so you can adjust it accordingly. Please let me know of any confusion and I will update the answer.

The git version on the server is 1.7.1. The server is CentOS 6.3 (Final).

The git version on the development machine is 1.8.1.1. This is Mac OS X 10.8.4.

The central repository and the production machine are on the same machine.

the central repository, which svn users can related to as 'server' is configured as follows. I have a folder /root/git where I keep all my git repositories. I want to create a git repository for a project I call 'flowers'.

cd /root/git
git clone --bare flowers flowers.git

The git command gave two messages:

Initialized empty Git repository in /root/git/flowers.git/
warning: You appear to have cloned an empty repository.

Nothing to worry about.

On the development machine is configured as follows. I have a folder /home/kinjal/Sites where I put all my projects. I now want to get the central git repository.

cd /home/kinjal/Sites
git clone [email protected]:/root/git/flowers.git

This gets me to a point where I can start adding stuff to it. I first set up git flow

git flow init -d

By default this is on branch develop. I add my code here, now. Then I need to commit to the central git repository.

git add .
git commit -am 'initial'
git push

At this point it pushed to the develop branch. I want to also add this to the master branch.

git flow release start v0.0.0 develop
git flow release finish v0.0.0
git push

Note that I did nothing between the release start and release finish. And when I did the release finish I was prompted to edit two files. This pushed the develop branch to master.

On the production site, which is on the same machine as my central git repository, I want put the repository in /var/www/vhosts/example.net. I already have /var/www/vhosts.

cd /var/www/vhosts
git clone file:///root/git/flowers.git example.net

If the production machine would also be on a different machine, the git clone command would look like the one used on the development machine.

HTML5 Email Validation

A bit late for the party, but this regular expression helped me to validate email type input in the client side. Though, we should always do verification in server side also.

<input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">

You can find more regex of all kinds here.

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

Xcode iOS 8 Keyboard types not supported

I have fixed this issue by unchecking 'Connect Hardware Keyboard'. Please refer to the image below to fix this issueenter image description here

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

How to use apply a custom drawable to RadioButton?

full solution here:

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:checked="true"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/oragne_toggle_btn"
        android:layout_marginTop="20dp"
        android:text="RadioButton" />
</RadioGroup>

selector XML

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected"    android:state_checked="false"/>

 </selector>

Style input element to fill remaining width of its container

Easiest way to achieve this would be :

CSS :

label{ float: left; }

span
{
    display: block;
    overflow: hidden;
    padding-right: 5px;
    padding-left: 10px;
}

span > input{ width: 100%; }

HTML :

<fieldset>
    <label>label</label><span><input type="text" /></span>
    <label>longer label</label><span><input type="text" /></span>
</fieldset>

Looks like : http://jsfiddle.net/JwfRX/

Change :hover CSS properties with JavaScript

Had some same problems, used addEventListener for events "mousenter", "mouseleave":

let DOMelement = document.querySelector('CSS selector for your HTML element');

// if you want to change e.g color: 
let origColorStyle = DOMelement.style.color;

DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });

DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })

Or something else for style when cursor is above the DOMelement. DOMElement can be chosen by various ways.

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

error: Libtool library used but 'LIBTOOL' is undefined

A good answer for me was to install libtool:

sudo apt-get install libtool

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

How to import existing Git repository into another?

Based on this article, using subtree is what worked for me and only applicable history was transferred. Posting here in case anyone needs the steps (make sure to replace the placeholders with values applicable to you):

in your source repository split subfolder into a new branch

git subtree split --prefix=<source-path-to-merge> -b subtree-split-result

in your destination repo merge in the split result branch

git remote add merge-source-repo <path-to-your-source-repository>
git fetch merge-source-repo
git merge -s ours --no-commit merge-source-repo/subtree-split-result
git read-tree --prefix=<destination-path-to-merge-into> -u merge-source-repo/subtree-split-result

verify your changes and commit

git status
git commit

Don't forget to

Clean up by deleting the subtree-split-result branch

git branch -D subtree-split-result

Remove the remote you added to fetch the data from source repo

git remote rm merge-source-repo

How do I import a sql data file into SQL Server?

If you are talking about an actual database (an mdf file) you would Attach it

.sql files are typically run using SQL Server Management Studio. They are basically saved SQL statements, so could be anything. You don't "import" them. More precisely, you "execute" them. Even though the script may indeed insert data.

Also, to expand on Jamie F's answer, don't run a SQL file against your database unless you know what it is doing. SQL scripts can be as dangerous as unchecked exe's

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       bc.lastname,
       b.title,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
       p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
  ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN  book_order bo
  ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
  ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

Connection refused to MongoDB errno 111

These commands fixed the issue for me,

sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --repair
sudo service mongod start
sudo service mongod status

If you are behind proxy, use:-
export http_proxy="http://username:[email protected]:port/"
export https_proxy="http://username:[email protected]:port/"

Reference: https://stackoverflow.com/a/24410282/4359237

How to convert Set<String> to String[]?

Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.

String[] GPXFILES1 = myset.toArray(String[]::new);

If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

String[] GPXFILES1 = myset.toArray(new String[0]);

Flutter - Layout a Grid

There are few named constructors in GridView for different scenarios,

Constructors

  1. GridView
  2. GridView.builder
  3. GridView.count
  4. GridView.custom
  5. GridView.extent

Below is a example of GridView constructor:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: ExampleGrid(),
  ),
);

class ExampleGrid extends StatelessWidget {
  List<String> images = [
    "https://uae.microless.com/cdn/no_image.jpg",
    "https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
    "https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
    "https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
    "https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
    "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
    "https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
    "https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
    "https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
        children: images.map((url) {
          return Card(child: Image.network(url));
        }).toList(),
      ),
    );
  }
}

If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView package. I have provided an answer with example here.

Below is an example for a GridView.count:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 4,
        children: List.generate(40, (index) {
          return Card(
            child: Image.network("https://robohash.org/$index"),
          ); //robohash.org api provide you different images for any number you are giving
        }),
      ),
    );
  }
}

Screenshot for above snippet:

Flutter gridview example by blasanka using card widget and robohash api

Example for a SliverGridView:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(20.0),
            sliver: SliverGrid.count(
              crossAxisSpacing: 10.0,
              crossAxisCount: 2,
              children: List.generate(20, (index) {
                return Card(child: Image.network("https://robohash.org/$index"));
              }),
            ),
          ),
        ],
      )
    );
  }
}

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

PDF to byte array and vice versa

You can do it by using Apache Commons IO without worrying about internal details.

Use org.apache.commons.io.FileUtils.readFileToByteArray(File file) which return data of type byte[].

Click here for Javadoc

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

Setting DIV width and height in JavaScript

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

How do you create a custom AuthorizeAttribute in ASP.NET Core?

Based on Derek Greer GREAT answer, i did it with enums.

Here is an example of my code:

public enum PermissionItem
{
    User,
    Product,
    Contact,
    Review,
    Client
}

public enum PermissionAction
{
    Read,
    Create,
}


public class AuthorizeAttribute : TypeFilterAttribute
{
    public AuthorizeAttribute(PermissionItem item, PermissionAction action)
    : base(typeof(AuthorizeActionFilter))
    {
        Arguments = new object[] { item, action };
    }
}

public class AuthorizeActionFilter : IAuthorizationFilter
{
    private readonly PermissionItem _item;
    private readonly PermissionAction _action;
    public AuthorizeActionFilter(PermissionItem item, PermissionAction action)
    {
        _item = item;
        _action = action;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        bool isAuthorized = MumboJumboFunction(context.HttpContext.User, _item, _action); // :)

        if (!isAuthorized)
        {
            context.Result = new ForbidResult();
        }
    }
}

public class UserController : BaseController
{
    private readonly DbContext _context;

    public UserController( DbContext context) :
        base()
    {
        _logger = logger;
    }

    [Authorize(PermissionItem.User, PermissionAction.Read)]
    public async Task<IActionResult> Index()
    {
        return View(await _context.User.ToListAsync());
    }
}

How can I get the current page name in WordPress?

<?php wp_title(''); ?>

This worked for me.

If I understand correctly, you want to get the page name on a page that has post entries.

Use success() or complete() in AJAX call

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

How do I install PyCrypto on Windows?

For Windows 7:

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:\Python27\Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from "https://pypi.python.org/pypi/pycrypto"

Then change your current path to downloaded path using your terminal and user should be root:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It's worked for me. Hope works for all..

Generate random integers between 0 and 9

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

How to set tbody height with overflow scroll

Based on this answer, here's a minimal solution if you're already using Bootstrap:

div.scrollable-table-wrapper {
  height: 500px;
  overflow: auto;

  thead tr th {
    position: sticky;
    top: 0;
  }
}
<div class="scrollable-table-wrapper">
  <table class="table">
    <thead>...</thead>
    <tbody>...</tbody>
  </table>
</div>

Tested on Bootstrap v3

How can I add new dimensions to a Numpy array?

You could just create an array of the correct size up-front and fill it:

frames = np.empty((480, 640, 3, 100))

for k in xrange(nframes):
    frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))

if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).

Just a note, you might consider using a (nframes, 480,640,3) shaped array, instead.

Reading a text file and splitting it into single words in python

with open(filename) as file:
    words = file.read().split()

Its a List of all words in your file.

import re
with open(filename) as file:
    words = re.findall(r"([a-zA-Z\-]+)", file.read())

Recursive Fibonacci

Why not use iterative algorithm?

int fib(int n)
{
    int a = 1, b = 1;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }           
    return b;
}

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Command for restarting all running docker containers?

To start only stopped containers:

docker start $(docker ps -a -q -f status=exited)

(On windows it works in Powershell).

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

In my rare case it was color wrapper who spoiled gcc. Solved by disabling cw excluding its directory /usr/libexec/cw from PATH environmental variable.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I was able to fix this issue by matching my build version to the .NET version on the server.

I double clicked the .exe just to see what would happen and it told me to install 4.5....

So I downgraded to 4.0 and it worked!

So make sure your versions match. It ran on my dev box fine, but server had older .NET version.

Check whether a value exists in JSON object

iterate through the array and check its name value.

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

The problem is that in many cases the packages are multiarch already so the i386 package is not available, but other packages still depend on the i386 package only. This is a problem in the repository, and the managers of the repos should fix it

Error C1083: Cannot open include file: 'stdafx.h'

Just running through a Visual Studio Code tutorial and came across a similiar issue.

Replace #include "stdafx.h" with #include "pch.h" which is the updated name for the precompiled headers.

Convert timestamp to date in MySQL query

You should convert timestamp to date.

select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'

FROM_UNIXTIME

Unzip files (7-zip) via cmd command

Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:

set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z

You should see as output (or something similar - as this is on my laptop running Windows 7):

C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\

C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\

C:\Users\Phillip>7z

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

<Commands>
  a: Add files to archive
  b: Benchmark
  d: Delete files from archive
  e: Extract files from archive (without using directory names)
  l: List contents of archive
  t: Test integrity of archive
  u: Update files to archive
  x: eXtract files with full paths
<Switches>
  -ai[r[-|0]]{@listfile|!wildcard}: Include archives
  -ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
  -bd: Disable percentage indicator
  -i[r[-|0]]{@listfile|!wildcard}: Include filenames
  -m{Parameters}: set compression Method
  -o{Directory}: set Output directory
  -p{Password}: set Password
  -r[-|0]: Recurse subdirectories
  -scs{UTF-8 | WIN | DOS}: set charset for list files
  -sfx[{name}]: Create SFX archive
  -si[{name}]: read data from stdin
  -slt: show technical information for l (List) command
  -so: write data to stdout
  -ssc[-]: set sensitive case mode
  -ssw: compress shared files
  -t{Type}: Set type of archive
  -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
  -v{Size}[b|k|m|g]: Create volumes
  -w[{path}]: assign Work directory. Empty path means a temporary directory
  -x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
  -y: assume Yes on all queries

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

How to pass a vector to a function?

You're using the argument as a reference but actually it's a pointer. Change vector<int>* to vector<int>&. And you should really set search4 to something before using it.

Can a shell script set environment variables of the calling shell?

In my .bash_profile I have :

# No Proxy
function noproxy
{
    /usr/local/sbin/noproxy  #turn off proxy server
    unset http_proxy HTTP_PROXY https_proxy HTTPs_PROXY
}


# Proxy
function setproxy
{
    sh /usr/local/sbin/proxyon  #turn on proxy server 
    http_proxy=http://127.0.0.1:8118/
    HTTP_PROXY=$http_proxy
    https_proxy=$http_proxy
    HTTPS_PROXY=$https_proxy
    export http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
}

So when I want to disable the proxy, the function(s) run in the login shell and sets the variables as expected and wanted.

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

How to set an environment variable from a Gradle build?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.

enter image description here

Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

What is the difference between int, Int16, Int32 and Int64?

  1. int and int32 are one and the same (32-bit integer)
  2. int16 is short int (2 bytes or 16-bits)
  3. int64 is the long datatype (8 bytes or 64-bits)

docker error: /var/run/docker.sock: no such file or directory

I also got this error. Though, I did not use boot2docker but just installed "plain" docker on Ubuntu (see https://docs.docker.com/installation/ubuntulinux/).

I got the error ("dial unix /var/run/docker.sock: no such file or directory. Are you trying to connect to a TLS-enabled daemon without TLS?") because the docker daemon was not running, yet.

On Ubuntu, you need to start the service:

sudo service docker start

See also http://blog.arungupta.me/resolve-dial-unix-docker-sock-error-techtip64

jQuery issue - #<an Object> has no method

This problem may also come up if you include different versions of jQuery.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Excel export script works on IE7+, Firefox and Chrome.

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Just create a blank iframe:

<iframe id="txtArea1" style="display:none"></iframe>

Call this function on:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's just a short form of writing an if-then-else statement. It means the same as the following code:

if(inPseudoEditMode)
  label.frame = kLabelIndentedRect;
else
  label.frame = kLabelRect;

Why is Tkinter Entry's get function returning nothing?

It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.

Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        print(self.entry.get())

app = SampleApp()
app.mainloop()

Run the program, type into the entry widget, then click on the button.

Find object in list that has attribute equal to some value (that meets any condition)

You could also implement rich comparison via __eq__ method for your Test class and use in operator. Not sure if this is the best stand-alone way, but in case if you need to compare Test instances based on value somewhere else, this could be useful.

class Test:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        """To implement 'in' operator"""
        # Comparing with int (assuming "value" is int)
        if isinstance(other, int):
            return self.value == other
        # Comparing with another Test object
        elif isinstance(other, Test):
            return self.value == other.value

import random

value = 5

test_list = [Test(random.randint(0,100)) for x in range(1000)]

if value in test_list:
    print "i found it"

Access an arbitrary element in a dictionary in Python

If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:

my_dict.keys()[0]     -> key of "first" element
my_dict.values()[0]   -> value of "first" element
my_dict.items()[0]    -> (key, value) tuple of "first" element

Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.

in Python 3:

list(my_dict.keys())[0]     -> key of "first" element
list(my_dict.values())[0]   -> value of "first" element
list(my_dict.items())[0]    -> (key, value) tuple of "first" element

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").html(data);
    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}

function show_popup2() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}

How do I remove blue "selected" outline on buttons?

This is an issue in the Chrome family and has been there forever.

A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208

It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse. You should see that outline only on keyboard tab-press.

I highly recommend using this fix: https://github.com/wicg/focus-visible.

Just do the following

npm install --save focus-visible

Add the script to your html:

<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>

or import into your main entry file if using webpack or something similar:

import 'focus-visible/dist/focus-visible.min';

then put this in your css file:

// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
  outline: none;
}

// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
  outline: magenta auto 5px;
}

You can just set:

button:focus {outline:0;}

but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

Change Placeholder Text using jQuery

try this

$('#Selector_ID').attr("placeholder", "your Placeholder");

iFrame onload JavaScript event

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

Use component from another module

One big and great approach is to load the module from a NgModuleFactory, you can load a module inside another module by calling this:

constructor(private loader: NgModuleFactoryLoader, private injector: Injector) {}

loadModule(path: string) {
    this.loader.load(path).then((moduleFactory: NgModuleFactory<any>) => {
        const entryComponent = (<any>moduleFactory.moduleType).entry;
        const moduleRef = moduleFactory.create(this.injector);
        const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);
        this.lazyOutlet.createComponent(compFactory);
    });
}

I got this from here.

What are the differences between git remote prune, git prune, git fetch --prune, etc

Note that one difference between git remote --prune and git fetch --prune is being fixed, with commit 10a6cc8, by Tom Miller (tmiller) (for git 1.9/2.0, Q1 2014):

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "**frotz"**, fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream.
git would inform the user to use "git remote prune" to fix the problem.

So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune was failing.

Not anymore:

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.

Angular: Can't find Promise, Map, Set and Iterator

Angular 2 Final

- es5 support (Works perfectly with TS 2.0.0 +)

Per update es6-shim isn't supported now, if you have both typings installed together es6-shim & core-js together. Remove es6-shim typing by mentioning in tsconfig.json. You could now refer below core-js typing for es5 support inside main.ts

///<reference path="./../typings/globals/core-js/index.d.ts"/>

tsconfig.json

exclude: [
   "node_modules", //<-- this would be needed in case of VS2015
   "node_modules/@typings",
   "typings"
]

- es6 suppport

You just need to set "target" property to es6, then all will error go away. And the transpiled code will be in es6 format.

android: how to change layout on button click?

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.

Center a DIV horizontally and vertically

I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.

My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.

So, with this HTML:

<div class="parentElement">  
  <div class="childElement">  
    ...Some Contents...  
  </div>  
</div>  

This CSS:

.parentElement {  
  position:relative;
  width:960px;
}
.childElement {
  position:absolute;
  top:50%;
  left:50%;
}

This jQuery might be useful:

$('.childElement').each(function(){
  // determine the real dimensions of the element: http://api.jquery.com/outerWidth/
  var x = $(this).outerWidth();
  var y = $(this).outerHeight();
  // adjust parent dimensions to fit child
  if($(this).parent().height() < y) {
    $(this).parent().css({height: y + 'px'});
  }
  // offset the child element using negative margins to "center" in both axes
  $(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});

Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...).

How to ignore whitespace in a regular expression subject string?

If you only want to allow spaces, then

\bc *a *t *s\b

should do it. To also allow tabs, use

\bc[ \t]*a[ \t]*t[ \t]*s\b

Remove the \b anchors if you also want to find cats within words like bobcats or catsup.

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

ORA-01031: insufficient privileges when selecting view

Finally I got it to work. Steve's answer is right but not for all cases. It fails when that view is being executed from a third schema. For that to work you have to add the grant option:

GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;

That way, [READ_USERNAME] can also grant select privilege over the view to another schema

How to add custom html attributes in JSX

For any custom attributes I use react-any-attr package https://www.npmjs.com/package/react-any-attr

Setting a backgroundImage With React Inline Styles

  1. Copy the image to the React Component's folder where you want to see it.
  2. Copy the following code:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. Give a height to your .welcomer using CSS so that you can see your image in the desired size.

Android Studio - mergeDebugResources exception

In my case, when I changed package name this issue appeared, I just followed below steps to fix my problem:

  1. Removed previously installed apk (uninstall)

  2. Applied project clean

  3. Run the app

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

Basically it depends on the precision you need for your locations. Using DOUBLE you'll have a 3.5nm precision. DECIMAL(8,6)/(9,6) goes down to 16cm. FLOAT is 1.7m...

This very interesting table has a more complete list: http://mysql.rjweb.org/doc.php/latlng :

Datatype               Bytes            Resolution

Deg*100 (SMALLINT)     4      1570 m    1.0 mi  Cities
DECIMAL(4,2)/(5,2)     5      1570 m    1.0 mi  Cities
SMALLINT scaled        4       682 m    0.4 mi  Cities
Deg*10000 (MEDIUMINT)  6        16 m     52 ft  Houses/Businesses
DECIMAL(6,4)/(7,4)     7        16 m     52 ft  Houses/Businesses
MEDIUMINT scaled       6       2.7 m    8.8 ft
FLOAT                  8       1.7 m    5.6 ft
DECIMAL(8,6)/(9,6)     9        16cm    1/2 ft  Friends in a mall
Deg*10000000 (INT)     8        16mm    5/8 in  Marbles
DOUBLE                16       3.5nm     ...    Fleas on a dog

Hope this helps.

In Tkinter is there any way to make a widget not visible?

import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
    lb.config(visible=visible)
visiblelabel(x, False)  # Hide
visiblelabel(x, True)  # Show

P.S. config can change any attribute:

x.config(text='Hello')  # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold'))  # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white')  # Background: red, Foreground: white

It's a bypass of StringVar, IntVar etc.

How do I format a number in Java?

From this thread, there are different ways to do this:

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.

How do I sort a vector of pairs based on the second element of the pair?

EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

Just use a custom comparator (it's an optional 3rd argument to std::sort)

struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

Facebook Open Graph Error - Inferred Property

Are those tags on 'http://www.mywebaddress.com'?

Bear in mind the linter will follow the og:url tag as this tag should point to the canonical URL of the piece of content - so if you have a page, e.g. 'http://mywebaddress.com/article1' with an og:url tag pointing to 'http://mywebaddress.com', Facebook will go there and read the tags there also.

Failing that, the most common reason i've seen for seemingly correct tags not being detected by the linter is user-agent detection returning different content to Facebook's crawler than the content you're seeing when you manually check

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I was able to get the full text (99,208 chars) out of a NVARCHAR(MAX) column by selecting (Results To Grid) just that column and then right-clicking on it and then saving the result as a CSV file. To view the result open the CSV file with a text editor (NOT Excel). Funny enough, when I tried to run the same query, but having Results to File enabled, the output was truncated using the Results to Text limit.

The work-around that @MartinSmith described as a comment to the (currently) accepted answer didn't work for me (got an error when trying to view the full XML result complaining about "The '[' character, hexadecimal value 0x5B, cannot be included in a name").

How to check the value given is a positive or negative integer?

if(values >= 0) {
 // as zero is more likely positive than negative
} else {

}

How to find a whole word in a String in java

Hope this works for you:

String string = "I will come and meet you at the 123woods";
String keyword = "123woods";

Boolean found = Arrays.asList(string.split(" ")).contains(keyword);
if(found){
      System.out.println("Keyword matched the string");
}

http://codigounico.blogspot.com/

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

Sequelize.js delete query?

Sequelize methods return promises, and there is no delete() method. Sequelize uses destroy() instead.

Example

Model.destroy({
  where: {
    some_field: {
      //any selection operation
      // for example [Op.lte]:new Date()
    }
  }
}).then(result => {
  //some operation
}).catch(error => {
  console.log(error)
})

Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy

What are NDF Files?

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

Source: MSDN: Understanding Files and Filegroups

The recommended file name extension for secondary data files is .ndf, but this is not enforced.

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

The code is something like this:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN);

DecimalFormat df = new DecimalFormat();

df.setMaximumFractionDigits(2);

df.setMinimumFractionDigits(0);

df.setGroupingUsed(false);

String result = df.format(bd);

u'\ufeff' in Python string

This problem arise basically when you save your python code in a UTF-8 or UTF-16 encoding because python add some special character at the beginning of the code automatically (which is not shown by the text editors) to identify the encoding format. But, when you try to execute the code it gives you the syntax error in line 1 i.e, start of code because python compiler understands ASCII encoding. when you view the code of file using read() function you can see at the begin of the returned code '\ufeff' is shown. The one simplest solution to this problem is just by changing the encoding back to ASCII encoding(for this you can copy your code to a notepad and save it Remember! choose the ASCII encoding... Hope this will help.

Printing long int value in C

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

Ternary operator ?: vs if...else

They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")

How to make grep only match if the entire line matches?

I needed this feature, but also wanted to make sure I did not return lines with a prefix before the ABB.log:

  • ABB.log
  • ABB.log.122
  • ABB.log.123
  • 123ABB.log

grep "\WABB.log$" -w a.tmp

Move textfield when keyboard appears swift

I love clean Swift code. So here's the tightest code I could come up with to move a text view up/down with the keyboard. It's currently working in an iOS8/9 Swift 2 production app.

UPDATE (March 2016): I just tightened up my previous code as much as possible. Also, there are a bunch of popular answers here that hardcode the keyboard height and animation parameters. There's no need for that, not to mention that the numbers in these answers don't always line up with the actual values I'm seeing on my 6s+ iOS9 (keyboard height of 226, duration of 0.25, and animation curve of 7). In any case, it's almost no extra code to get those values straight from the system. See below.

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "animateWithKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}

func animateWithKeyboard(notification: NSNotification) {

    // Based on both Apple's docs and personal experience, 
    // I assume userInfo and its documented keys are available.
    // If you'd like, you can remove the forced unwrapping and add your own default values.

    let userInfo = notification.userInfo!
    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
    let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
    let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
    let moveUp = (notification.name == UIKeyboardWillShowNotification)

    // baseContraint is your Auto Layout constraint that pins the
    // text view to the bottom of the superview.

    baseConstraint.constant = moveUp ? -keyboardHeight : 0

    let options = UIViewAnimationOptions(rawValue: curve << 16)
    UIView.animateWithDuration(duration, delay: 0, options: options,
        animations: {
            self.view.layoutIfNeeded()
        },
        completion: nil
    )

}

NOTE: This code covers the most comment/general case. However, more code may be needed to handle different orientations and/or custom keyboards Here's an in-depth article on working with the iOS keyboard. If you need to handle every scenario, this may help.

Angular 2: How to access an HTTP response body?

This should work. You can get body using response.json() if its a json response.

   this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      subscribe((res: Response.json()) => {
        console.log(res);
      })

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

Jquery, set value of td in a table?

$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

How to format numbers?

                function formatThousands(n,dp,f) {
                    // dp - decimal places
                    // f - format >> 'us', 'eu'
                    if (n == 0) {
                        if(f == 'eu') {
                            return "0," + "0".repeat(dp);   
                        }
                        return "0." + "0".repeat(dp);
                    }

                    /* round to 2 decimal places */
                    //n = Math.round( n * 100 ) / 100;
                    var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
                    while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
                    var a = s.substr(0, i + 3) + r + (d ? '.' + Math.round((d+1) * Math.pow(10,dp)).toString().substr(1,dp) : '');
                    /* change format from 20,000.00 to 20.000,00 */
                    if (f == 'eu') {
                        var b = a.toString().replace(".", "#");
                        b = b.replace(",", ".");
                        return b.replace("#", ",");
                    }                   
                    return a;
                }

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

How I could add dir to $PATH in Makefile?

To set the PATH variable, within the Makefile only, use something like:

PATH := $(PATH):/my/dir

test:
@echo my new PATH = $(PATH)

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}

HTML Input="file" Accept Attribute File Type (CSV)

I have used text/comma-separated-values for CSV mime-type in accept attribute and it works fine in Opera. Tried text/csv without luck.

Some others MIME-Types for CSV if the suggested do not work:

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel
  • text/anytext

Source: http://filext.com/file-extension/CSV

javascript set cookie with expire time

Below are code snippets to create and delete a cookie. The cookie is set for 1 day.

// 1 Day = 24 Hrs = 24*60*60 = 86400.
  1. By using max-age:

    • Creating the cookie:

    document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
    
    • Deleting the cookie:

    document.cookie = "cookieName=; max-age=- (any digit); path=/;";
    
  2. By using expires:

    • Syntax for creating the cookie for one day:

    var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
    document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
    

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

  1. Download winutils.exe
  2. Create folder, say C:\winutils\bin
  3. Copy winutils.exe inside C:\winutils\bin
  4. Set environment variable HADOOP_HOME to C:\winutils

Is it good practice to make the constructor throw an exception?

I am not for throwing Exceptions in the constructor since I am considering this as non-clean. There are several reasons for my opinion.

  1. As Richard mentioned you cannot initialize an instance in an easy manner. Especially in tests it is really annoying to build a test-wide object only by surrounding it in a try-catch during initialization.

  2. Constructors should be logic-free. There is no reason at all to encapsulate logic in a constructor, since you are always aiming for the Separation of Concerns and Single Responsibility Principle. Since the concern of the constructor is to "construct an object" it should not encapsulate any exception handling if following this approach.

  3. It smells like bad design. Imho if I am forced to do exception handling in the constructor I am at first asking myself if I have any design frauds in my class. It is necessary sometimes, but then I outsource this to a builder or factory to keep the constructor as simple as possible.

So if it is necessary to do some exception handling in the constructor, why would you not outsource this logic to a Builder of Factory? It might be a few more lines of code but gives you the freedom to implement a far more robust and well suited exception handling since you can outsource the logic for the exception handling even more and are not sticked to the constructor, which will encapsulate too much logic. And the client does not need to know anything about your constructing logic if you delegate the exception handling properly.